/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.kylin.storage.gtrecord;

import org.apache.kylin.shaded.com.google.common.collect.UnmodifiableIterator;
import org.apache.kylin.common.util.ImmutableBitSet;
import org.apache.kylin.gridtable.GTInfo;
import org.apache.kylin.gridtable.GTRecord;

import java.nio.ByteBuffer;
import java.util.NoSuchElementException;

/**
 * Support iterate over {@code GTRecord}s in storage partition result.
 *
 * <p>Note that the implementation returns the same object for next().
 * Client needs to copy the returned record when needed.
 */
public class PartitionResultIterator extends UnmodifiableIterator<GTRecord> {
    private final ByteBuffer buffer;
    private final ImmutableBitSet cols;
    private final GTRecord record; // reuse to avoid object creation

    public PartitionResultIterator(byte[] data, GTInfo info, ImmutableBitSet cols) {
        this.buffer = ByteBuffer.wrap(data);
        this.cols = cols;
        this.record = new GTRecord(info);
    }

    @Override
    public boolean hasNext() {
        return buffer.hasRemaining();
    }

    @Override
    public GTRecord next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        record.loadColumns(cols, buffer);
        return record;
    }
}
