1 /**
2 *
3 * Copyright 2006 The Apache Software Foundation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package javax.mail.util;
19
20 import java.io.ByteArrayInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23
24 import javax.mail.internet.SharedInputStream;
25
26 public class SharedByteArrayInputStream extends ByteArrayInputStream implements SharedInputStream {
27
28 /**
29 * Position within shared buffer that this stream starts at.
30 */
31 protected int start;
32
33 /**
34 * Create a SharedByteArrayInputStream that shares the entire
35 * buffer.
36 *
37 * @param buf The input data.
38 */
39 public SharedByteArrayInputStream(byte[] buf) {
40 this(buf, 0, buf.length);
41 }
42
43
44 /**
45 * Create a SharedByteArrayInputStream using a subset of the
46 * array data.
47 *
48 * @param buf The source data array.
49 * @param offset The starting offset within the array.
50 * @param length The length of data to use.
51 */
52 public SharedByteArrayInputStream(byte[] buf, int offset, int length) {
53 super(buf, offset, length);
54 start = offset;
55 }
56
57
58 /**
59 * Get the position within the output stream, adjusted by the
60 * starting offset.
61 *
62 * @return The adjusted position within the stream.
63 */
64 public long getPosition() {
65 return pos - start;
66 }
67
68
69 /**
70 * Create a new input stream from this input stream, accessing
71 * a subset of the data. Think of it as a substring operation
72 * for a stream.
73 *
74 * The starting offset must be non-negative. The end offset can
75 * by -1, which means use the remainder of the stream.
76 *
77 * @param offset The starting offset.
78 * @param end The end offset (which can be -1).
79 *
80 * @return An InputStream configured to access the indicated data subrange.
81 */
82 public InputStream newStream(long offset, long end) {
83 if (offset < 0) {
84 throw new IllegalArgumentException("Starting position must be non-negative");
85 }
86 if (end == -1) {
87 end = count - start;
88 }
89 return new SharedByteArrayInputStream(buf, start + (int)offset, (int)(end - offset));
90 }
91 }