io.deephaven.chunk.sized.SizedCharChunk Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of deephaven-engine-chunk Show documentation
Show all versions of deephaven-engine-chunk Show documentation
Engine Chunks: Array-like data structures for dense, efficient data movement
The newest version!
//
// Copyright (c) 2016-2024 Deephaven Data Labs and Patent Pending
//
package io.deephaven.chunk.sized;
import io.deephaven.chunk.WritableCharChunk;
import io.deephaven.chunk.attributes.Any;
import io.deephaven.util.SafeCloseable;
import org.jetbrains.annotations.Nullable;
/**
* A wrapper for a char chunk that allows you to resize the chunk to a capacity.
*
* @param the chunk's attribute
*/
public final class SizedCharChunk implements SafeCloseable {
private WritableCharChunk chunk;
public SizedCharChunk() {}
public SizedCharChunk(final int initialSize) {
chunk = WritableCharChunk.makeWritableChunk(initialSize);
}
/**
* Get the underlying chunk.
*
* @return the underlying chunk. May be {@code null} if the chunk has not been initialized.
*/
@Nullable
public WritableCharChunk get() {
return chunk;
}
/**
* Ensure the underlying chunk has a capacity of at least {@code capacity}, preserving data.
*
* The data and size of the returned chunk are undefined. If you must maintain the data, then use
* {@link #ensureCapacityPreserve(int)}.
*
* @param capacity the minimum capacity for the chunk.
*
* @return the underlying chunk
*/
public WritableCharChunk ensureCapacity(int capacity) {
if (chunk == null || capacity > chunk.capacity()) {
if (chunk != null) {
chunk.close();
}
chunk = WritableCharChunk.makeWritableChunk(capacity);
}
return chunk;
}
/**
* Ensure the underlying chunk has a capacity of at least {@code capacity}.
*
* If the chunk has existing data, then it is copied to the new chunk.
*
* If the underlying chunk already exists, then the size of the chunk is the original size. If the chunk did not
* exist, then the size of the returned chunk is zero.
*
* @param capacity the minimum capacity for the chunk.
*
* @return the underlying chunk
*/
public WritableCharChunk ensureCapacityPreserve(int capacity) {
if (chunk == null || capacity > chunk.capacity()) {
final WritableCharChunk oldChunk = chunk;
chunk = WritableCharChunk.makeWritableChunk(capacity);
if (oldChunk != null) {
chunk.copyFromTypedChunk(oldChunk, 0, 0, oldChunk.size());
chunk.setSize(oldChunk.size());
oldChunk.close();
} else {
chunk.setSize(0);
}
}
return chunk;
}
@Override
public void close() {
if (chunk != null) {
chunk.close();
chunk = null;
}
}
}