01: package org.bouncycastle.util.encoders;
02:
03: /**
04: * a buffering class to allow translation from one format to another to
05: * be done in discrete chunks.
06: */
07: public class BufferedEncoder {
08: protected byte[] buf;
09: protected int bufOff;
10:
11: protected Translator translator;
12:
13: /**
14: * @param translator the translator to use.
15: * @param bufSize amount of input to buffer for each chunk.
16: */
17: public BufferedEncoder(Translator translator, int bufSize) {
18: this .translator = translator;
19:
20: if ((bufSize % translator.getEncodedBlockSize()) != 0) {
21: throw new IllegalArgumentException(
22: "buffer size not multiple of input block size");
23: }
24:
25: buf = new byte[bufSize];
26: bufOff = 0;
27: }
28:
29: public int processByte(byte in, byte[] out, int outOff) {
30: int resultLen = 0;
31:
32: buf[bufOff++] = in;
33:
34: if (bufOff == buf.length) {
35: resultLen = translator.encode(buf, 0, buf.length, out,
36: outOff);
37: bufOff = 0;
38: }
39:
40: return resultLen;
41: }
42:
43: public int processBytes(byte[] in, int inOff, int len, byte[] out,
44: int outOff) {
45: if (len < 0) {
46: throw new IllegalArgumentException(
47: "Can't have a negative input length!");
48: }
49:
50: int resultLen = 0;
51: int gapLen = buf.length - bufOff;
52:
53: if (len > gapLen) {
54: System.arraycopy(in, inOff, buf, bufOff, gapLen);
55:
56: resultLen += translator.encode(buf, 0, buf.length, out,
57: outOff);
58:
59: bufOff = 0;
60:
61: len -= gapLen;
62: inOff += gapLen;
63: outOff += resultLen;
64:
65: int chunkSize = len - (len % buf.length);
66:
67: resultLen += translator.encode(in, inOff, chunkSize, out,
68: outOff);
69:
70: len -= chunkSize;
71: inOff += chunkSize;
72: }
73:
74: if (len != 0) {
75: System.arraycopy(in, inOff, buf, bufOff, len);
76:
77: bufOff += len;
78: }
79:
80: return resultLen;
81: }
82: }
|