1 /*
2 Copyright 2007 nVidia, Inc.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
4 
5 You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6 
7 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
8 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 
10 See the License for the specific language governing permissions and limitations under the License.
11 */
12 #ifndef _ZOH_BITS_H
13 #define _ZOH_BITS_H
14 
15 // read/write a bitstream
16 
17 #include "nvcore/debug.h"
18 
19 namespace ZOH {
20 
21 class Bits
22 {
23 public:
24 
Bits(char * data,int maxdatabits)25 	Bits(char *data, int maxdatabits) { nvAssert (data && maxdatabits > 0); bptr = bend = 0; bits = data; maxbits = maxdatabits; readonly = 0;}
Bits(const char * data,int availdatabits)26 	Bits(const char *data, int availdatabits) { nvAssert (data && availdatabits > 0); bptr = 0; bend = availdatabits; cbits = data; maxbits = availdatabits; readonly = 1;}
27 
write(int value,int nbits)28 	void write(int value, int nbits) {
29 		nvAssert (nbits >= 0 && nbits < 32);
30 		nvAssert (sizeof(int)>= 4);
31 		for (int i=0; i<nbits; ++i)
32 			writeone(value>>i);
33 	}
read(int nbits)34 	int read(int nbits) {
35 		nvAssert (nbits >= 0 && nbits < 32);
36 		nvAssert (sizeof(int)>= 4);
37 		int out = 0;
38 		for (int i=0; i<nbits; ++i)
39 			out |= readone() << i;
40 		return out;
41 	}
getptr()42 	int getptr() { return bptr; }
setptr(int ptr)43 	void setptr(int ptr) { nvAssert (ptr >= 0 && ptr < maxbits); bptr = ptr; }
getsize()44 	int getsize() { return bend; }
45 
46 private:
47 	int	bptr;		// next bit to read
48 	int bend;		// last written bit + 1
49 	char *bits;		// ptr to user bit stream
50 	const char *cbits;	// ptr to const user bit stream
51 	int maxbits;	// max size of user bit stream
52 	char readonly;	// 1 if this is a read-only stream
53 
readone()54 	int readone() {
55 		nvAssert (bptr < bend);
56 		if (bptr >= bend) return 0;
57 		int bit = (readonly ? cbits[bptr>>3] : bits[bptr>>3]) & (1 << (bptr & 7));
58 		++bptr;
59 		return bit != 0;
60 	}
writeone(int bit)61 	void writeone(int bit) {
62 		nvAssert (!readonly); // "Writing a read-only bit stream"
63 		nvAssert (bptr < maxbits);
64 		if (bptr >= maxbits) return;
65 		if (bit&1)
66 			bits[bptr>>3] |= 1 << (bptr & 7);
67 		else
68 			bits[bptr>>3] &= ~(1 << (bptr & 7));
69 		if (bptr++ >= bend) bend = bptr;
70 	}
71 };
72 
73 }
74 
75 #endif
76