Re-add ECI test case and groundwork for more tests of DecodedBitStreamParser
[zxing.git] / core / test / src / com / google / zxing / common / BitSourceBuilder.java
1 /*\r
2  * Copyright 2008 ZXing authors\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.google.zxing.common;\r
18 \r
19 import java.io.ByteArrayOutputStream;\r
20 \r
21 /**\r
22  * Class that lets one easily build an array of bytes by appending bits at a time.\r
23  *\r
24  * @author srowen@google.com (Sean Owen)\r
25  */\r
26 public final class BitSourceBuilder {\r
27 \r
28   private final ByteArrayOutputStream output;\r
29   private int nextByte;\r
30   private int bitsLeftInNextByte;\r
31 \r
32   public BitSourceBuilder() {\r
33     output = new ByteArrayOutputStream();\r
34     nextByte = 0;\r
35     bitsLeftInNextByte = 8;\r
36   }\r
37 \r
38   public void write(int value, int numBits) {\r
39     if (numBits <= bitsLeftInNextByte) {\r
40       nextByte <<= numBits;\r
41       nextByte |= value;\r
42       bitsLeftInNextByte -= numBits;\r
43       if (bitsLeftInNextByte == 0) {\r
44         output.write(nextByte);\r
45         nextByte = 0;\r
46         bitsLeftInNextByte = 8;\r
47       }\r
48     } else {\r
49       int bitsToWriteNow = bitsLeftInNextByte;\r
50       int numRestOfBits = numBits - bitsToWriteNow;\r
51       int mask = 0xFF >> (8 - bitsToWriteNow);\r
52       int valueToWriteNow = (value >>> numRestOfBits) & mask;\r
53       write(valueToWriteNow, bitsToWriteNow);\r
54       write(value, numRestOfBits);\r
55     }\r
56   }\r
57 \r
58   public byte[] toByteArray() {\r
59     if (bitsLeftInNextByte < 8) {\r
60       write(0, bitsLeftInNextByte);\r
61     }\r
62     return output.toByteArray();\r
63   }\r
64 \r
65 }