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