1 /**
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one or more
4 * contributor license agreements. See the NOTICE file distributed with
5 * this work for additional information regarding copyright ownership.
6 * The ASF licenses this file to You under the Apache License, Version 2.0
7 * (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package org.apache.geronimo.util.encoders;
20
21
22 /**
23 * a buffering class to allow translation from one format to another to
24 * be done in discrete chunks.
25 */
26 public class BufferedDecoder
27 {
28 protected byte[] buf;
29 protected int bufOff;
30
31 protected Translator translator;
32
33 /**
34 * @param translator the translator to use.
35 * @param bufSize amount of input to buffer for each chunk.
36 */
37 public BufferedDecoder(
38 Translator translator,
39 int bufSize)
40 {
41 this.translator = translator;
42
43 if ((bufSize % translator.getEncodedBlockSize()) != 0)
44 {
45 throw new IllegalArgumentException("buffer size not multiple of input block size");
46 }
47
48 buf = new byte[bufSize];
49 bufOff = 0;
50 }
51
52 public int processByte(
53 byte in,
54 byte[] out,
55 int outOff)
56 {
57 int resultLen = 0;
58
59 buf[bufOff++] = in;
60
61 if (bufOff == buf.length)
62 {
63 resultLen = translator.decode(buf, 0, buf.length, out, outOff);
64 bufOff = 0;
65 }
66
67 return resultLen;
68 }
69
70 public int processBytes(
71 byte[] in,
72 int inOff,
73 int len,
74 byte[] out,
75 int outOff)
76 {
77 if (len < 0)
78 {
79 throw new IllegalArgumentException("Can't have a negative input length!");
80 }
81
82 int resultLen = 0;
83 int gapLen = buf.length - bufOff;
84
85 if (len > gapLen)
86 {
87 System.arraycopy(in, inOff, buf, bufOff, gapLen);
88
89 resultLen += translator.decode(buf, 0, buf.length, out, outOff);
90
91 bufOff = 0;
92
93 len -= gapLen;
94 inOff += gapLen;
95 outOff += resultLen;
96
97 int chunkSize = len - (len % buf.length);
98
99 resultLen += translator.decode(in, inOff, chunkSize, out, outOff);
100
101 len -= chunkSize;
102 inOff += chunkSize;
103 }
104
105 if (len != 0)
106 {
107 System.arraycopy(in, inOff, buf, bufOff, len);
108
109 bufOff += len;
110 }
111
112 return resultLen;
113 }
114 }