From b32e378ec80488c5ffbd0d9bb356217e6db0245f Mon Sep 17 00:00:00 2001 From: Sven Gothel Date: Thu, 4 May 2023 01:04:53 +0200 Subject: IOUtil.copyStreamChunk2ByteBuffer(..): Added new method to copy a chunk (segment) of the input stream (skipBytes, byteCount) This method is inspired by Bug 1280, , 'copy only needed bytes' for JOAL's com.jogamp.openal.util.WAVData.loadFromStream(..). This method is a revised version of the proposed IOHelpers.copyFromStream2ByteBuffer(..), see --- src/java/com/jogamp/common/util/IOUtil.java | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/java') diff --git a/src/java/com/jogamp/common/util/IOUtil.java b/src/java/com/jogamp/common/util/IOUtil.java index 499fa1b..e68c3b3 100644 --- a/src/java/com/jogamp/common/util/IOUtil.java +++ b/src/java/com/jogamp/common/util/IOUtil.java @@ -337,6 +337,39 @@ public class IOUtil { return data; } + /** + * Copy the specified input stream chunk to a NIO ByteBuffer w/ native byte order, which is being returned. + * + * @param stream input stream, which will be wrapped into a BufferedInputStream, if not already done. + * @param skipBytes initial bytes to skip from input stream. + * @param byteCount bytes to copy starting after skipBytes. + */ + public static ByteBuffer copyStreamChunk2ByteBuffer(InputStream stream, int skipBytes, int byteCount) throws IOException { + if( !(stream instanceof BufferedInputStream) ) { + stream = new BufferedInputStream(stream); + } + final MachineDataInfo machine = Platform.getMachineDataInfo(); + final ByteBuffer data = Buffers.newDirectByteBuffer( machine.pageAlignedSize( byteCount ) ); + final byte[] chunk = new byte[machine.pageSizeInBytes()]; + int numRead = 1; // EOS: -1 == numRead, EOF maybe reached earlier w/ 0 == numRead + while ( numRead > 0 && skipBytes > 0 ) { + final int chunk2Read = Math.min(machine.pageSizeInBytes(), skipBytes); + numRead = stream.read(chunk, 0, chunk2Read); + skipBytes -= numRead; + } + while ( numRead > 0 && byteCount > 0 ) { + final int chunk2Read = Math.min(machine.pageSizeInBytes(), byteCount); + numRead = stream.read(chunk, 0, chunk2Read); + if (numRead > 0) { + data.put(chunk, 0, numRead); + } + byteCount -= numRead; + } + + data.flip(); + return data; + } + /*** * * RESOURCE / FILE NAME STUFF -- cgit v1.2.3