From 476109e1943c1a9561cc636ffc64ab8cdd1888f9 Mon Sep 17 00:00:00 2001 From: BenWhitehead Date: Mon, 31 Jan 2022 13:00:54 -0500 Subject: [PATCH] feat: add limit support to ReadChannel (#688) Add new methods to ReadChannel to allow limiting of the channel independent of any chunk sizes or buffers. ###### Motivation GCS supports range reads of objects, ReadChannel currently has `seek` to allow settings the begin offset, but doesn't provide limit to allow setting the end offset. The only alternative is to provide manually sized ByteBuffer(s) to read into that would have to track size externally. This new feature allows the Channel itself to absorb the burden and prevent reading more bytes than necessary from GCS. --- .../clirr-ignored-differences.xml | 15 ++++++++++ .../java/com/google/cloud/ReadChannel.java | 30 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 google-cloud-core/clirr-ignored-differences.xml diff --git a/google-cloud-core/clirr-ignored-differences.xml b/google-cloud-core/clirr-ignored-differences.xml new file mode 100644 index 0000000000..0f7f80a7b4 --- /dev/null +++ b/google-cloud-core/clirr-ignored-differences.xml @@ -0,0 +1,15 @@ + + + + + + 7012 + com/google/cloud/ReadChannel + * limit(long) + + + 7012 + com/google/cloud/ReadChannel + long limit() + + diff --git a/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java b/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java index e0a8f5f50b..9a24b4e553 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java @@ -53,4 +53,34 @@ public interface ReadChannel extends ReadableByteChannel, Closeable, Restorable< */ @Override RestorableState capture(); + + /** + * Limit the maximum number of bytes available to be read from this channel. If the limit is + * larger than the actual size of the content this will have no material impact. + * + *

NOTE:Implementers are not required to return a new instance from this method, however + * they are allowed to. Users of this method should always use the instance returned from this + * method. + * + *

Default Implementation:By default, this method will simply return {@code this}. + * + * @param limit the maximum number of bytes to limit this channel to + * @return The instance of channel which will respect the limit. + * @throws UnsupportedOperationException If the {@code this} instances does not support limiting + * @since 2.4.0 + */ + default ReadChannel limit(long limit) { + return this; + } + + /** + * The currently defined limit for this channel. Initial value is {@link Long#MAX_VALUE} + * + * @return the current limit for this channel + * @throws UnsupportedOperationException If the {@code this} instances does not support limiting + * @since 2.4.0 + */ + default long limit() { + return Long.MAX_VALUE; + } }