Class ByteArrayInStream

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
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      * Implementation improvement suggested by Andrea Aime - Dec 15 2007
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         // don't try and copy past the end of the input
57         if ((position + numToRead) > buffer.length) {
58             numToRead = buffer.length - position;
59             System.arraycopy(buffer, position, buf, 0, numToRead);
60             // zero out the unread bytes
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