Overte C++ Documentation
Radix2IntegerScanner.h
1 //
2 // Radix2IntegerScanner.h
3 // libraries/shared/src
4 //
5 // Created by Tobias Schwinger on 3/23/13.
6 // Copyright 2013 High Fidelity, Inc.
7 //
8 // Distributed under the Apache License, Version 2.0.
9 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10 //
11 
12 #ifndef hifi_Radix2IntegerScanner_h
13 #define hifi_Radix2IntegerScanner_h
14 
15 #include <stddef.h>
16 #include <stdint.h>
17 
18 namespace type_traits { // those are needed for the declaration, see below
19 
20  // Note: There are better / more generally appicable implementations
21  // in C++11, make_signed is missing in TR1 too - so I just use C++98
22  // hacks that get the job done...
23 
24  template< typename T > struct is_signed
25  { static bool const value = T(-1) < T(0); };
26 
27  template< typename T, size_t S = sizeof(T) > struct make_unsigned;
28  template< typename T > struct make_unsigned< T, 1 > { typedef uint8_t type; };
29  template< typename T > struct make_unsigned< T, 2 > { typedef uint16_t type; };
30  template< typename T > struct make_unsigned< T, 4 > { typedef uint32_t type; };
31  template< typename T > struct make_unsigned< T, 8 > { typedef quint64 type; };
32 }
33 
34 
38 template< typename T,
39  bool _Signed = type_traits::is_signed<T>::value >
41 
42 
43 
44 template< typename UInt >
45 class Radix2IntegerScanner< UInt, false > {
46 
47  UInt valMsb;
48  public:
49 
51  : valMsb(~UInt(0) &~ (~UInt(0) >> 1)) { }
52 
53  explicit Radix2IntegerScanner(int bits)
54  : valMsb(UInt(1u) << (bits - 1)) {
55  }
56 
57  typedef UInt state_type;
58 
59  state_type initial_state() const { return valMsb; }
60  bool advance(state_type& s) const { return (s >>= 1) != 0u; }
61 
62  bool bit(UInt const& v, state_type const& s) const { return !!(v & s); }
63 };
64 
65 template< typename Int >
66 class Radix2IntegerScanner< Int, true >
67 {
68  typename type_traits::make_unsigned<Int>::type valMsb;
69  public:
70 
72  : valMsb(~state_type(0u) &~ (~state_type(0u) >> 1)) {
73  }
74 
75  explicit Radix2IntegerScanner(int bits)
76  : valMsb(state_type(1u) << (bits - 1)) {
77  }
78 
79 
80  typedef typename type_traits::make_unsigned<Int>::type state_type;
81 
82  state_type initial_state() const { return valMsb; }
83  bool advance(state_type& s) const { return (s >>= 1) != 0u; }
84 
85  bool bit(Int const& v, state_type const& s) const { return !!((v-valMsb) & s); }
86 };
87 
88 #endif // hifi_Radix2IntegerScanner_h
Definition: Radix2IntegerScanner.h:40