1 package hudson.util; 2 3 import java.io.OutputStream ; 4 import java.io.IOException ; 5 import java.io.ByteArrayOutputStream ; 6 import java.io.InputStream ; 7 8 16 public class ByteBuffer extends OutputStream { 17 private byte[] buf = new byte[8192]; 18 21 private int size = 0; 22 23 24 public synchronized void write(byte b[], int off, int len) throws IOException { 25 ensureCapacity(len); 26 System.arraycopy(b,off,buf,size,len); 27 size+=len; 28 } 29 30 public synchronized void write(int b) throws IOException { 31 ensureCapacity(1); 32 buf[size++] = (byte)b; 33 } 34 35 public synchronized long length() { 36 return size; 37 } 38 39 private void ensureCapacity(int len) { 40 if(buf.length-size>len) 41 return; 42 43 byte[] n = new byte[Math.max(buf.length*2, size+len)]; 44 System.arraycopy(buf,0,n,0,size); 45 this.buf = n; 46 } 47 48 public synchronized String toString() { 49 return new String (buf,0,size); 50 } 51 52 55 public synchronized void writeTo(OutputStream os) throws IOException { 56 os.write(buf,0,size); 57 } 58 59 62 public InputStream newInputStream() { 63 return new InputStream () { 64 private int pos = 0; 65 public int read() throws IOException { 66 synchronized(ByteBuffer.this) { 67 if(pos>=size) return -1; 68 return buf[pos++]; 69 } 70 } 71 72 public int read(byte b[], int off, int len) throws IOException { 73 synchronized(ByteBuffer.this) { 74 if(size==pos) 75 return -1; 76 77 int sz = Math.min(len,size-pos); 78 System.arraycopy(buf,pos,b,off,sz); 79 pos+=sz; 80 return sz; 81 } 82 } 83 84 85 public int available() throws IOException { 86 synchronized(ByteBuffer.this) { 87 return size-pos; 88 } 89 } 90 91 public long skip(long n) throws IOException { 92 synchronized(ByteBuffer.this) { 93 int diff = (int) Math.min(n,size-pos); 94 pos+=diff; 95 return diff; 96 } 97 } 98 }; 99 } 100 } 101 | Popular Tags |