1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package org.coach.util; 26 27 final class ModestOutputStream { 28 private byte bytes[]; 29 private int index; 30 private boolean little_endian; 31 private void AddBufferSize(int add) { 32 if (index + add > bytes.length) { 33 if (add < 256) { 34 add = 256; 35 } 36 byte b[] = new byte[bytes.length + add]; 37 38 System.arraycopy(bytes, 0, b, 0, index); 39 bytes = b; 40 } 41 } 42 43 public ModestOutputStream(boolean little_endian) { 44 45 this.little_endian = little_endian; 46 bytes = new byte[1024]; 47 bytes[0] = (byte)(little_endian ? 1 : 0); 48 index = 1; 49 } 50 51 public void WriteOctet(byte octet) { 52 AddBufferSize(1); 53 bytes[index++] = octet; 54 } 55 56 public void WriteUShort(short value) { 57 int al = index % 2; 58 AddBufferSize(al + 2); 59 index += al; 60 61 if (little_endian) { 62 bytes[index++] = (byte)value; 63 bytes[index++] = (byte)(value >> 8); 64 } else { 65 bytes[index++] = (byte)(value >> 8); 66 bytes[index++] = (byte)value; 67 } 68 } 69 70 public void WriteULong(int value) { 71 int al = index % 4; 72 73 if (al != 0) { 74 al = 4 - al; 75 AddBufferSize(al + 4); 76 index += al; 77 } else { 78 AddBufferSize(4); 79 } 80 81 if (little_endian) { 82 bytes[index++] = (byte)value; 83 bytes[index++] = (byte)(value >> 8); 84 bytes[index++] = (byte)(value >> 16); 85 bytes[index++] = (byte)(value >> 24); 86 } else { 87 bytes[index++] = (byte)(value >> 24); 88 bytes[index++] = (byte)(value >> 16); 89 bytes[index++] = (byte)(value >> 8); 90 bytes[index++] = (byte)value; 91 } 92 } 93 94 public void WriteString(String str) { 95 byte b[] = str.getBytes(); 96 int len = b.length; 97 WriteULong(len + 1); 98 AddBufferSize(len); 99 System.arraycopy(b, 0, bytes, index, len); 100 index += len; 101 WriteOctet((byte)0); 102 } 103 104 public void WriteOctetArray(byte b[]) { 105 int len = b.length; 106 WriteULong(len); 107 AddBufferSize(len); 108 System.arraycopy(b, 0, bytes, index, len); 109 index += len; 110 } 111 112 public byte[] GetBytes() { 113 byte b[] = new byte[index]; 114 System.arraycopy(bytes, 0, b, 0, index); 115 return b; 116 } 117 } 118 | Popular Tags |