1 package org.catacomb.movie.gif;
2
3 import org.catacomb.report.E;
4
5
6 public final class ByteAccumulator extends Object {
7 int iin;
8 byte[] ba;
9
10 int ipend;
11 int npend;
12
13 int inxb;
14 int iout;
15
16 static int[] msk = {0, 1, 3, 7, 15, 31, 63, 127, 255, 511};
17
18
19 public ByteAccumulator(int n) {
20 ba = new byte[n];
21 iin = 0;
22 }
23
24
25 public ByteAccumulator(byte[] ba) {
26 this.ba = ba;
27 iout = 0;
28 inxb = 0;
29 }
30
31
32
33 public int getNextWritePosition() {
34 return iin;
35 }
36
37 public void checkDoubleSpace() {
38 if (iin > ba.length/2) {
39 int n = ba.length;
40 byte[] bb = new byte[2*n];
41 for (int i = 0; i < n; i++) bb[i] = ba[i];
42 ba = bb;
43 }
44 }
45
46
47
48
49 public void trim() {
50 byte[] ret = new byte[iin];
51 System.arraycopy(ba, 0, ret, 0, ret.length);
52 ba = ret;
53 }
54
55 public byte[] getData() {
56 flush();
57 trim();
58 return ba;
59 }
60
61
62 public void setByte(int i, byte b) {
63 ba[i] = b;
64 }
65
66 public void setByte(int i, int b) {
67 ba[i] = (byte)b;
68 }
69
70
71
72 public void appendByte(byte b) {
73 ba[iin++] = b;
74 }
75
76 public void appendByte(int i) {
77 ba[iin++] = (byte)i;
78 }
79
80
81 public void appendBytes(byte[] b) {
82 System.arraycopy(b, 0, ba, iin, b.length);
83 iin += b.length;
84 }
85
86
87 public void appendBytes(byte[] b, int ioff, int nb) {
88 System.arraycopy(b, ioff, ba, iin, nb);
89 iin += nb;
90 }
91
92
93 public void appendString(String s) {
94 appendBytes(s.getBytes());
95 }
96
97
98 public void appendInt2(int i) {
99
100
101
102
103 byte[] bt = {(byte)((i) & 0xff),
104 (byte)((i >> 8) & 0xff)
105 };
106
107
108 appendBytes(bt);
109 }
110
111 public void appendInt4(int i) {
112 byte[] bt = {(byte)((i >> 24) & 0xff),
113 (byte)((i >> 16) & 0xff),
114 (byte)((i >> 8) & 0xff),
115 (byte)(i & 0xff)
116 };
117 appendBytes(bt);
118
119 }
120
121
122 public void append(int i, int p) {
123 if (i < 0) {
124 E.error("appending negeative no to byte stream");
125 }
126
127
128 ipend += (i << npend);
129 npend += p;
130 while (npend >= 8) {
131 appendByte(ipend & 0xff);
132 ipend = (ipend >> 8);
133 npend -= 8;
134 }
135 }
136
137
138 public void flush() {
139 if (npend > 0) {
140 appendByte(ipend & 0xff);
141 }
142 }
143
144
145 public int nextElt(int p) {
146 int ng = 0;
147
148 int ir = 0;
149
150 while (ng < p) {
151 if (iout >= ba.length) {
152 return -1;
153 }
154
155 int ntk = p - ng;
156 if (ntk > 8 - inxb) {
157 ntk = 8 - inxb;
158 }
159
160 ir += ((ba[iout] >> inxb) & msk[ntk]) << ng;
161
162
163 inxb += ntk;
164 if (inxb == 8) {
165 iout++;
166 inxb = 0;
167 }
168 ng += ntk;
169 }
170
171 return ir;
172 }
173
174
175 }
176
177
178
179
180
181