xref: /reactos/sdk/tools/hhpcomp/chmc/encint.h (revision 40462c92)
1 /*
2 
3   Copyright (C) 2010 Alex Andreotti <alex.andreotti@gmail.com>
4 
5   This file is part of chmc.
6 
7   chmc is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11 
12   chmc is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16 
17   You should have received a copy of the GNU General Public License
18   along with chmc.  If not, see <http://www.gnu.org/licenses/>.
19 
20 */
21 #ifndef CHMC_ENCINT_H
22 #define CHMC_ENCINT_H
23 
24 // 0x7f 127
25 // 0x3fff 16383
26 // 0x1fffff 2097151
27 // 0xfffffff 268435455
28 static inline int chmc_encint_len ( const UInt32 val ) {
29 	int len;
30 
31 	// FIXME should support 64 bit?
32 	if ( val > 0xfffffffUL )
33 		len = 0; // overflow
34 	else if ( val > 0x1fffffUL )
35 		len = 4;
36 	else if ( val > 0x3fffUL )
37 		len = 3;
38 	else if ( val > 0x7fUL )
39 		len = 2;
40 	else
41 		len = 1;
42 
43 	return len;
44 }
45 
46 static inline int chmc_encint ( const UInt32 val, UChar *out ) {
47 	int len;
48 	UInt32 a;
49 	UChar *p, *l;
50 
51 	// FIXME should support 64 bit?
52 	if ( ! out || val > 0xfffffffUL )
53 		return 0; // FIXME can't handle, overflow
54 
55 	if ( val > 0x1fffffUL )
56 		len = 4;
57 	else if ( val > 0x3fffUL )
58 		len = 3;
59 	else if ( val > 0x7fUL )
60 		len = 2;
61 	else
62 		len = 1;
63 
64 	a = val;
65 	l = p = out + (len - 1);
66 
67 	while ( p >= out ) {
68 		*p = (a & 0x7fUL);
69 		if ( p < l )
70 			*p |= 0x80UL;
71 		p--;
72 		a >>= 7;
73 	}
74 
75 	return len;
76 }
77 
78 static inline int chmc_decint ( const UChar *in, UInt32 *value ) {
79 	int len;
80 
81 	len = 0;
82 	*value = 0;
83 
84 	while ( (in[len] & 0x80) && (len < 3) ) {
85 		*value <<= 7;
86 		*value |= in[len] & 0x7f;
87 		len++;
88 	}
89 	*value <<= 7;
90 	*value |= in[len] & 0x7f;
91 	len++;
92 
93 	return len;
94 }
95 
96 #endif /* CHMC_ENCINT_H */
97