001/* 002 * Copyright 2013 Alex Kasko (alexkasko.com) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.alexkasko.unsafe.offheaplong; 018 019import com.alexkasko.unsafe.offheap.OffHeapDisposableIterator; 020import com.alexkasko.unsafe.offheap.OffHeapUtils; 021 022import java.util.Iterator; 023 024/** 025 * <p>Iterator implementation for unsafe long collections. 026 * Underneath collection size will be remembered once on iterator creation. 027 * 028 * <p>Note: iterator will create new autoboxed Long object <b>on every</b> {@link #next()} call, 029 * this behaviour is inevitable with iterators in java 6/7. 030 * 031 * @author alexkasko 032 * Date: 7/3/13 033 */ 034class OffHeapLongIterator implements OffHeapDisposableIterator<Long> { 035 private final OffHeapLongAddressable data; 036 private final long size; 037 private long index = 0; 038 039 /** 040 * Constructor 041 * 042 * @param data offheap long collection 043 */ 044 OffHeapLongIterator(OffHeapLongAddressable data) { 045 this.data = data; 046 this.size = data.size(); 047 } 048 049 /** 050 * {@inheritDoc} 051 */ 052 @Override 053 public boolean hasNext() { 054 return index < size; 055 } 056 057 /** 058 * {@inheritDoc} 059 */ 060 @Override 061 public Long next() { 062 if (index >= size) throw new IllegalStateException( 063 "Current index: [" + index + "] is greater or equal then collection size: [" + size + "]"); 064 return data.get(index++); 065 } 066 067 /** 068 * Remove operation is not supported 069 * @throws UnsupportedOperationException 070 */ 071 @Override 072 public void remove() { 073 throw new UnsupportedOperationException("remove"); 074 } 075 076 /** 077 * {@inheritDoc} 078 */ 079 @Override 080 public String toString() { 081 final StringBuilder sb = new StringBuilder(); 082 sb.append("OffHeapLongIterator"); 083 sb.append("{data=").append(data); 084 sb.append(", size=").append(size); 085 sb.append(", index=").append(index); 086 sb.append('}'); 087 return sb.toString(); 088 } 089 090 /** 091 * {@inheritDoc} 092 */ 093 @Override 094 public long size() { 095 return data.size(); 096 } 097 098 /** 099 * {@inheritDoc} 100 */ 101 @Override 102 public void free() { 103 OffHeapUtils.free(data); 104 } 105}