• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  * SPDX-License-Identifier: Apache-2.0.
4  */
5 
6 package software.amazon.awssdk.crt.utils;
7 
8 import java.nio.ByteBuffer;
9 import java.nio.Buffer;
10 
11 /**
12  * Utility Class with Helper functions for working with ByteBuffers
13  */
14 public class ByteBufferUtils {
ByteBufferUtils()15     private ByteBufferUtils() {}
16 
17     /**
18      * Transfers as much data as possible from an input ByteBuffer to an output ByteBuffer
19      * @param in The input ByteBuffer
20      * @param out The output ByteBuffer
21      * @return The number of bytes transferred
22      */
transferData(ByteBuffer in, ByteBuffer out)23     public static int transferData(ByteBuffer in, ByteBuffer out) {
24         int amtToTransfer = Math.min(in.remaining(), out.remaining());
25 
26         // Make a new ByteBuffer that shares the same underlying buffer as the input ByteBuffer
27         ByteBuffer shallowCopy = in.duplicate();
28 
29         // Modify the shallow copy's read limit so that it matches the write space remaining in the output Buffer so
30         // we don't throw an OutOfBounds exception
31         // The weird cast is to avoid certain JDK8 JREs that don't think ByteBuffer
32         // inherits from Buffer
33         ((Buffer) shallowCopy).limit(shallowCopy.position() + amtToTransfer);
34 
35         // Transfer the data
36         out.put(shallowCopy);
37 
38         // Increment the read position of the original input buffer by the number of bytes transferred
39         in.position(in.position() + amtToTransfer);
40         return amtToTransfer;
41     }
42 }
43