1 #ifndef _RAR_GETBITS_
2 #define _RAR_GETBITS_
3 
4 class BitInput
5 {
6   public:
7     enum BufferSize {MAX_SIZE=0x8000}; // Size of input buffer.
8 
9     int InAddr; // Curent byte position in the buffer.
10     int InBit;  // Current bit position in the current byte.
11 
12     bool ExternalBuffer;
13   public:
14     BitInput(bool AllocBuffer);
15     ~BitInput();
16 
17     byte *InBuf; // Dynamically allocated input buffer.
18 
InitBitInput()19     void InitBitInput()
20     {
21       InAddr=InBit=0;
22     }
23 
24     // Move forward by 'Bits' bits.
addbits(uint Bits)25     void addbits(uint Bits)
26     {
27       Bits+=InBit;
28       InAddr+=Bits>>3;
29       InBit=Bits&7;
30     }
31 
32     // Return 16 bits from current position in the buffer.
33     // Bit at (InAddr,InBit) has the highest position in returning data.
getbits()34     uint getbits()
35     {
36       uint BitField=(uint)InBuf[InAddr] << 16;
37       BitField|=(uint)InBuf[InAddr+1] << 8;
38       BitField|=(uint)InBuf[InAddr+2];
39       BitField >>= (8-InBit);
40       return BitField & 0xffff;
41     }
42 
43     // Return 32 bits from current position in the buffer.
44     // Bit at (InAddr,InBit) has the highest position in returning data.
getbits32()45     uint getbits32()
46     {
47       uint BitField=(uint)InBuf[InAddr] << 24;
48       BitField|=(uint)InBuf[InAddr+1] << 16;
49       BitField|=(uint)InBuf[InAddr+2] << 8;
50       BitField|=(uint)InBuf[InAddr+3];
51       BitField <<= InBit;
52       BitField|=(uint)InBuf[InAddr+4] >> (8-InBit);
53       return BitField & 0xffffffff;
54     }
55 
56     void faddbits(uint Bits);
57     uint fgetbits();
58 
59     // Check if buffer has enough space for IncPtr bytes. Returns 'true'
60     // if buffer will be overflown.
Overflow(uint IncPtr)61     bool Overflow(uint IncPtr)
62     {
63       return InAddr+IncPtr>=MAX_SIZE;
64     }
65 
66     void SetExternalBuffer(byte *Buf);
67 };
68 #endif
69