Issue 163
[zxing.git] / cpp / core / src / common / BitSource.h
1 #ifndef __BIT_SOURCE_H__
2 #define __BIT_SOURCE_H__
3
4 /*
5  *  BitSource.h
6  *  zxing
7  *
8  *  Created by Christian Brunschen on 09/05/2008.
9  *  Copyright 2008 Google UK. All rights reserved.
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23
24 #include "Array.h"
25
26 namespace common {
27   /**
28    * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
29    * number of bits read is not often a multiple of 8.</p>
30    *
31    * <p>This class is not thread-safe.</p>
32    *
33    * @author srowen@google.com (Sean Owen)
34    * @author christian.brunschen@gmail.com (Christian Brunschen)
35    */
36   class BitSource : public Counted {
37     typedef unsigned char byte;
38   private:
39     ArrayRef<byte> bytes_;
40     int byteOffset_;
41     int bitOffset_;
42   public:
43     /**
44      * @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
45      * Bits are read within a byte from most-significant to least-significant bit.
46      */
47     BitSource(ArrayRef<byte> &bytes) : bytes_(bytes), byteOffset_(0),
48       bitOffset_(0) { }
49     
50     /**
51      * @param numBits number of bits to read
52      * @return int representing the bits read. The bits will appear as the least-significant
53      *         bits of the int
54      * @throws IllegalArgumentException if numBits isn't in [1,32]
55      */
56     int readBits(int numBits);
57     
58     /**
59      * @return number of bits that can be read successfully
60      */
61     int available();
62   };
63 }
64
65 #endif // __BIT_SOURCE_H__