Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/pickle/ByteBufferInputStream.java

raw symbols SCIP
1 /* ****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 **************************************************************************** */
16 package org.jpype.pickle;
17
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.nio.ByteBuffer;
21 import java.util.LinkedList;
22
23 public class ByteBufferInputStream extends InputStream
24 {
25
26 private LinkedList<ByteBuffer> buffers = new LinkedList<>();
27
28 public void put(byte[] bytes)
29 {
30 // We can just wrap the buffer instead of copying it, since the buffer is
31 // wrapped we don't need to write the bytes to it. Wrapping the bytes relies
32 // on the array not being changed before being read.
33 ByteBuffer buffer = ByteBuffer.wrap(bytes);
34 buffers.add(buffer);
35 }
36
37 @Override
38 public int read() throws IOException
39 {
40 if (buffers.isEmpty())
41 return -1;
42
43 ByteBuffer b = buffers.getFirst();
44 while (b.remaining() == 0)
45 {
46 buffers.removeFirst();
47 if (buffers.isEmpty())
48 return -1; // EOF
49 b = buffers.getFirst();
50 }
51 return b.get() & 0xFF; // Mask with 0xFF to convert signed byte to int (range 0-255)
52 }
53
54 @Override
55 public int read(byte[] arg0) throws IOException
56 {
57 return read(arg0, 0, arg0.length);
58 }
59
60 @Override
61 public int read(byte[] buffer, int offset, int len) throws IOException
62 {
63 if (buffer == null)
64 throw new NullPointerException("Buffer cannot be null");
65 if (offset < 0 || len < 0 || len > buffer.length - offset)
66 throw new IndexOutOfBoundsException("Invalid offset/length parameters");
67 if (len == 0)
68 return 0;
69
70 int total = 0;
71 while (len > 0 && !buffers.isEmpty())
72 {
73 ByteBuffer b = buffers.getFirst();
74 int remaining = b.remaining();
75 if (remaining == 0)
76 {
77 buffers.removeFirst();
78 continue;
79 }
80
81 int toRead = Math.min(len, remaining);
82 b.get(buffer, offset, toRead);
83 total += toRead;
84 len -= toRead;
85 offset += toRead;
86 }
87 return (total == 0) ? -1 : total;
88 }
89
90 @Override
91 public void close() throws IOException
92 {
93 buffers.clear();
94 }
95 }