2 * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore.persisted;
10 import static java.util.Objects.requireNonNull;
12 import java.io.InputStream;
13 import java.util.Iterator;
15 final class ChunkedInputStream extends InputStream {
16 private final Iterator<byte[]> remainingChunks;
18 private byte[] currentChunk;
19 private int currentLimit;
20 private int currentOffset;
21 private int available;
23 ChunkedInputStream(final int size, final Iterator<byte[]> iterator) {
24 remainingChunks = requireNonNull(iterator);
25 currentChunk = remainingChunks.next();
26 currentLimit = currentChunk.length;
31 public int available() {
37 if (currentChunk == null) {
41 int ret = currentChunk[currentOffset] & 0xff;
47 @SuppressWarnings("checkstyle:ParameterName")
48 public int read(final byte[] b) {
49 return read(b, 0, b.length);
53 @SuppressWarnings("checkstyle:ParameterName")
54 public int read(final byte[] b, final int off, final int len) {
56 throw new IndexOutOfBoundsException();
58 if (currentChunk == null) {
62 final int result = Math.min(available, len);
67 final int count = currentBytes(toCopy);
68 System.arraycopy(currentChunk, currentOffset, b, toOffset, count);
78 @SuppressWarnings("checkstyle:ParameterName")
79 public long skip(final long n) {
80 final int result = (int) Math.min(available, n);
84 final int count = currentBytes(toSkip);
92 private int currentBytes(final int desired) {
93 return Math.min(desired, currentLimit - currentOffset);
96 private void consumeBytes(final int count) {
97 currentOffset += count;
100 if (currentOffset == currentLimit) {
101 if (remainingChunks.hasNext()) {
102 currentChunk = remainingChunks.next();
103 currentLimit = currentChunk.length;