001
014
015 package com.liferay.portal.kernel.io.unsync;
016
017 import java.io.InputStream;
018
019
026 public class UnsyncByteArrayInputStream extends InputStream {
027
028 public UnsyncByteArrayInputStream(byte[] buffer) {
029 this.buffer = buffer;
030 this.index = 0;
031 this.capacity = buffer.length;
032 }
033
034 public UnsyncByteArrayInputStream(byte[] buffer, int offset, int length) {
035 this.buffer = buffer;
036 this.index = offset;
037 this.capacity = Math.min(buffer.length, offset + length);
038 this.markIndex = offset;
039 }
040
041 @Override
042 public int available() {
043 return capacity - index;
044 }
045
046 @Override
047 public void mark(int readAheadLimit) {
048 markIndex = index;
049 }
050
051 @Override
052 public boolean markSupported() {
053 return true;
054 }
055
056 @Override
057 public int read() {
058 if (index < capacity) {
059 return buffer[index++] & 0xff;
060 }
061 else {
062 return -1;
063 }
064 }
065
066 @Override
067 public int read(byte[] bytes) {
068 return read(bytes, 0, bytes.length);
069 }
070
071 @Override
072 public int read(byte[] bytes, int offset, int length) {
073 if (length <= 0) {
074 return 0;
075 }
076
077 if (index >= capacity) {
078 return -1;
079 }
080
081 int read = length;
082
083 if ((index + read) > capacity) {
084 read = capacity - index;
085 }
086
087 System.arraycopy(buffer, index, bytes, offset, read);
088
089 index += read;
090
091 return read;
092 }
093
094 @Override
095 public void reset() {
096 index = markIndex;
097 }
098
099 @Override
100 public long skip(long skip) {
101 if (skip < 0) {
102 return 0;
103 }
104
105 if ((skip + index) > capacity) {
106 skip = capacity - index;
107 }
108
109 index += skip;
110
111 return skip;
112 }
113
114 protected byte[] buffer;
115 protected int capacity;
116 protected int index;
117 protected int markIndex;
118
119 }