1 package nom.tam.util;
2
3 /*
4 * #%L
5 * nom.tam FITS library
6 * %%
7 * Copyright (C) 1996 - 2024 nom-tam-fits
8 * %%
9 * This is free and unencumbered software released into the public domain.
10 *
11 * Anyone is free to copy, modify, publish, use, compile, sell, or
12 * distribute this software, either in source code form or as a compiled
13 * binary, for any purpose, commercial or non-commercial, and by any
14 * means.
15 *
16 * In jurisdictions that recognize copyright laws, the author or authors
17 * of this software dedicate any and all copyright interest in the
18 * software to the public domain. We make this dedication for the benefit
19 * of the public at large and to the detriment of our heirs and
20 * successors. We intend this dedication to be an overt act of
21 * relinquishment in perpetuity of all present and future rights to this
22 * software under copyright law.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
28 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
29 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
30 * OTHER DEALINGS IN THE SOFTWARE.
31 * #L%
32 */
33
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.nio.ByteBuffer;
37
38 /**
39 * Stream interface for reading from a {@link ByteBuffer} (<i>primarily for internal use</i>)
40 *
41 * @see ByteBufferOutputStream
42 * @see ByteArrayIO
43 */
44 public class ByteBufferInputStream extends InputStream {
45
46 private static final int BYTE_MASK = 0xFF;
47
48 private final ByteBuffer buf;
49
50 /**
51 * Creates an new <code>InpuStream</code>, which reads from a <code>ByteBuffer</code> starting at the current buffer
52 * position. Its <code>read()</code> methods can be intermixed with the <code>get()</code> methods of the buffer,
53 * and also with {@link ByteBuffer#position(int)}, maintaining overall sequentiality of the calls. In other words,
54 * the stream's input is not decopuled from direct access to the buffer.
55 *
56 * @param buffer the buffer to read from
57 */
58 public ByteBufferInputStream(ByteBuffer buffer) {
59 super();
60 buf = buffer;
61 }
62
63 @Override
64 public int read() throws IOException {
65 if (!buf.hasRemaining()) {
66 return -1;
67 }
68 return buf.get() & BYTE_MASK;
69 }
70
71 @Override
72 public int read(byte[] bytes, int off, int len) throws IOException {
73 if (!buf.hasRemaining()) {
74 return -1;
75 }
76 int readLen = Math.min(len, buf.remaining());
77 buf.get(bytes, off, readLen);
78 return readLen;
79 }
80 }