| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
package org.locationtech.jts.io; |
| 13 |
|
| 14 |
/** |
| 15 |
* Allows an array of bytes to be used as an {@link InStream}. |
| 16 |
* To optimize memory usage, instances can be reused |
| 17 |
* with different byte arrays. |
| 18 |
*/ |
| 19 |
public class ByteArrayInStream |
| 20 |
implements InStream |
| 21 |
{ |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
private byte[] buffer; |
| 27 |
private int position; |
| 28 |
|
| 29 |
/** |
| 30 |
* Creates a new stream based on the given buffer. |
| 31 |
* |
| 32 |
* @param buffer the bytes to read |
| 33 |
*/ |
| 34 |
public ByteArrayInStream(final byte[] buffer) { |
| 35 |
setBytes(buffer); |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* Sets this stream to read from the given buffer |
| 40 |
* |
| 41 |
* @param buffer the bytes to read |
| 42 |
*/ |
| 43 |
public void setBytes(final byte[] buffer) { |
| 44 |
this.buffer = buffer; |
| 45 |
this.position = 0; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Reads up to <tt>buf.length</tt> bytes from the stream |
| 50 |
* into the given byte buffer. |
| 51 |
* |
| 52 |
* @param buf the buffer to place the read bytes into |
| 53 |
*/ |
| 54 |
public void read(final byte[] buf) { |
| 55 |
int numToRead = buf.length; |
| 56 |
|
| 57 |
if ((position + numToRead) > buffer.length) { |
| 58 |
numToRead = buffer.length - position; |
| 59 |
System.arraycopy(buffer, position, buf, 0, numToRead); |
| 60 |
|
| 61 |
for (int i = numToRead; i < buf.length; i++) { |
| 62 |
buf[i] = 0; |
| 63 |
} |
| 64 |
} |
| 65 |
else { |
| 66 |
System.arraycopy(buffer, position, buf, 0, numToRead); |
| 67 |
} |
| 68 |
position += numToRead; |
| 69 |
} |
| 70 |
} |
| 71 |
|