001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019 020 package javax.mail.util; 021 022 import java.io.ByteArrayInputStream; 023 import java.io.IOException; 024 import java.io.InputStream; 025 026 import javax.mail.internet.SharedInputStream; 027 028 public class SharedByteArrayInputStream extends ByteArrayInputStream implements SharedInputStream { 029 030 /** 031 * Position within shared buffer that this stream starts at. 032 */ 033 protected int start; 034 035 /** 036 * Create a SharedByteArrayInputStream that shares the entire 037 * buffer. 038 * 039 * @param buf The input data. 040 */ 041 public SharedByteArrayInputStream(byte[] buf) { 042 this(buf, 0, buf.length); 043 } 044 045 046 /** 047 * Create a SharedByteArrayInputStream using a subset of the 048 * array data. 049 * 050 * @param buf The source data array. 051 * @param offset The starting offset within the array. 052 * @param length The length of data to use. 053 */ 054 public SharedByteArrayInputStream(byte[] buf, int offset, int length) { 055 super(buf, offset, length); 056 start = offset; 057 } 058 059 060 /** 061 * Get the position within the output stream, adjusted by the 062 * starting offset. 063 * 064 * @return The adjusted position within the stream. 065 */ 066 public long getPosition() { 067 return pos - start; 068 } 069 070 071 /** 072 * Create a new input stream from this input stream, accessing 073 * a subset of the data. Think of it as a substring operation 074 * for a stream. 075 * 076 * The starting offset must be non-negative. The end offset can 077 * by -1, which means use the remainder of the stream. 078 * 079 * @param offset The starting offset. 080 * @param end The end offset (which can be -1). 081 * 082 * @return An InputStream configured to access the indicated data subrange. 083 */ 084 public InputStream newStream(long offset, long end) { 085 if (offset < 0) { 086 throw new IllegalArgumentException("Starting position must be non-negative"); 087 } 088 if (end == -1) { 089 end = count - start; 090 } 091 return new SharedByteArrayInputStream(buf, start + (int)offset, (int)(end - offset)); 092 } 093 }