// 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.doris.flink.sink.batch;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

public class BatchBufferStream extends InputStream {
    private final Iterator<byte[]> iterator;
    private byte[] currentRow;
    private int currentPos;

    public BatchBufferStream(List<byte[]> buffer) {
        this.iterator = buffer.iterator();
    }

    @Override
    public int read() throws IOException {
        return 0;
    }

    @Override
    public int read(byte[] buf) throws IOException {
        return read(buf, 0, buf.length);
    }

    @Override
    public int read(byte[] buf, int off, int len) throws IOException {
        if (!iterator.hasNext() && currentRow == null) {
            return -1;
        }

        byte[] item = currentRow;
        int pos = currentPos;
        int readBytes = 0;
        while (readBytes < len && (item != null || iterator.hasNext())) {
            if (item == null) {
                item = iterator.next();
                pos = 0;
            }

            int size = Math.min(len - readBytes, item.length - pos);
            System.arraycopy(item, pos, buf, off + readBytes, size);
            readBytes += size;
            pos += size;

            if (pos == item.length) {
                item = null;
                pos = 0;
            }
        }
        currentRow = item;
        currentPos = pos;
        return readBytes;
    }
}
