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.offheapstruct;
018
019import com.alexkasko.unsafe.offheap.OffHeapDisposableIterator;
020import com.alexkasko.unsafe.offheap.OffHeapUtils;
021
022/**
023 * Iterator implementation for unsafe long collections.
024 * Underneath collection size will be remembered once on iterator creation.
025 *
026 * @author alexkasko
027 * Date: 7/3/13
028 */
029class OffHeapStructIterator implements OffHeapDisposableIterator<byte[]> {
030    private final OffHeapStructCollection data;
031    private final long size;
032    private final byte[] buffer;
033    private long index = 0;
034
035    /**
036     * Constructor
037     *
038     * @param data struct collection
039     */
040    OffHeapStructIterator(OffHeapStructCollection data) {
041        this.data = data;
042        this.size = data.size();
043        this.buffer = new byte[data.structLength()];
044    }
045
046    /**
047     * {@inheritDoc}
048     */
049    @Override
050    public boolean hasNext() {
051        return index < size;
052    }
053
054    /**
055     * {@inheritDoc}
056     */
057    @Override
058    public byte[] next() {
059        if (index >= size) throw new IllegalStateException(
060                "Current index: [" + index + "] is greater or equal then collection size: [" + size + "]");
061        data.get(index++, buffer);
062        return buffer;
063    }
064
065    /**
066     * Remove operation is not supported
067     *
068     * @throws UnsupportedOperationException
069     */
070    @Override
071    public void remove() {
072        throw new UnsupportedOperationException("remove");
073    }
074
075    /**
076     * {@inheritDoc}
077     */
078    @Override
079    public String toString() {
080        final StringBuilder sb = new StringBuilder();
081        sb.append("OffHeapStructIterator");
082        sb.append("{data=").append(data);
083        sb.append(", size=").append(size);
084        sb.append(", index=").append(index);
085        sb.append('}');
086        return sb.toString();
087    }
088
089    /**
090     * {@inheritDoc}
091     */
092    @Override
093    public void free() {
094        OffHeapUtils.free(data);
095    }
096
097    /**
098     * {@inheritDoc}
099     */
100    @Override
101    public long size() {
102        return data.size();
103    }
104}