1 #ifndef __bin_utils_h__
2 #define __bin_utils_h__
3 
4 #include "bin.h"
5 #include "compat.h"
6 
7 
8 /**
9  * Generating a list of peak bins for corresponding length
10  */
gen_peaks(uint64_t length,bin_t * peaks)11 inline int gen_peaks(uint64_t length, bin_t * peaks)
12 {
13     int pp = 0;
14     uint8_t layer = 0;
15 
16     while (length) {
17         if (length & 1)
18             peaks[pp++] = bin_t(((2 * length - 1) << layer) - 1);
19         length >>= 1;
20         layer++;
21     }
22 
23     for (int i = 0; i < (pp >> 1); ++i) {
24         bin_t memo = peaks[pp - 1 - i];
25         peaks[pp - 1 - i] = peaks[i];
26         peaks[i] = memo;
27     }
28 
29     peaks[pp] = bin_t::NONE;
30     return pp;
31 }
32 
33 
34 /**
35  * Checking for that the bin value is fit to uint32_t
36  */
bin_isUInt32(const bin_t & bin)37 inline bool bin_isUInt32(const bin_t & bin)
38 {
39     if (bin.is_all())
40         return true;
41     if (bin.is_none())
42         return true;
43 
44     const uint64_t v = bin.toUInt();
45 
46     return static_cast<uint32_t>(v) == v && v != 0xffffffff && v != 0x7fffffff;
47 }
48 
49 
50 /**
51  * Convert the bin value to uint32_t
52  */
bin_toUInt32(const bin_t & bin)53 inline uint32_t bin_toUInt32(const bin_t & bin)
54 {
55     if (bin.is_all())
56         return 0x7fffffff;
57     if (bin.is_none())
58         return 0xffffffff;
59     return static_cast<uint32_t>(bin.toUInt());
60 }
61 
62 
63 /**
64  * Convert the bin value to uint64_t
65  */
bin_toUInt64(const bin_t & bin)66 inline uint64_t bin_toUInt64(const bin_t & bin)
67 {
68     return bin.toUInt();
69 }
70 
71 
72 /**
73  * Restore the bin from an uint32_t value
74  */
bin_fromUInt32(uint32_t v)75 inline bin_t bin_fromUInt32(uint32_t v)
76 {
77     if (v == 0x7fffffff)
78         return bin_t::ALL;
79     if (v == 0xffffffff)
80         return bin_t::NONE;
81     return bin_t(static_cast<uint64_t>(v));
82 }
83 
84 
85 /**
86  * Restore the bin from an uint64_t value
87  */
bin_fromUInt64(uint64_t v)88 inline bin_t bin_fromUInt64(uint64_t v)
89 {
90     return bin_t(static_cast<uint64_t>(v));
91 }
92 
93 
94 #endif /*_bin_utils_h__*/
95