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.io;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.Beta;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.MoreObjects;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.io.ByteSink;
17 import java.io.DataOutput;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.ObjectInput;
21 import java.util.ArrayList;
22 import java.util.List;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.opendaylight.yangtools.concepts.Immutable;
28 public final class ChunkedByteArray implements Immutable {
29 private final ImmutableList<byte[]> chunks;
30 private final int size;
32 ChunkedByteArray(final int size, final ImmutableList<byte[]> chunks) {
34 this.chunks = requireNonNull(chunks);
37 public static ChunkedByteArray readFrom(final ObjectInput in, final int size, final int chunkSize)
39 final List<byte[]> chunks = new ArrayList<>(requiredChunks(size, chunkSize));
42 final byte[] buffer = new byte[Math.min(remaining, chunkSize)];
45 remaining -= buffer.length;
46 } while (remaining != 0);
48 return new ChunkedByteArray(size, ImmutableList.copyOf(chunks));
55 public InputStream openStream() {
56 return new ChunkedInputStream(size, chunks.iterator());
59 public void copyTo(final DataOutput output) throws IOException {
60 for (byte[] chunk : chunks) {
61 output.write(chunk, 0, chunk.length);
65 public void copyTo(final ByteSink output) throws IOException {
66 for (byte[] chunk : chunks) {
72 public String toString() {
73 return MoreObjects.toStringHelper(this).add("size", size).add("chunkCount", chunks.size()).toString();
77 ImmutableList<byte[]> getChunks() {
81 private static int requiredChunks(final int size, final int chunkSize) {
82 final int div = size / chunkSize;
83 return size % chunkSize == 0 ? div : div + 1;