1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use bitops::set_bit;
use num_traits::PrimInt;
use std::mem::size_of;

/// Bits representation.
pub struct Bits {
    bits: Vec<Option<bool>>,
    size: usize,
}

impl Bits {
    /// Create a new representation of Bits.
    /// # Examples
    /// ```
    /// extern crate xor_distance_exercise;
    /// use xor_distance_exercise::bits::Bits;
    ///
    /// Bits::new::<u64>;
    /// ```
    pub fn new<T: PrimInt>() -> Self {
        // Initialize the vector with known size.
        let size = Self::bit_size::<T>();
        let mut bits: Vec<Option<bool>> = Vec::with_capacity(size);

        // Initialize the vector with default values of None (undecided bit yet).
        for _ in 0..size {
            bits.push(None);
        }

        Bits { bits, size }
    }

    /// Return bit size of the type being represent in bits.
    /// # Examples
    /// ```
    /// extern crate xor_distance_exercise;
    ///
    /// use xor_distance_exercise::bits::Bits;
    ///
    /// assert_eq!(8, Bits::bit_size::<u8>());
    /// assert_eq!(32, Bits::bit_size::<u32>());
    /// assert_eq!(64, Bits::bit_size::<u64>());
    /// assert_eq!(64, Bits::bit_size::<i64>());
    /// ```
    pub fn bit_size<T: PrimInt>() -> usize {
        let byte_size = size_of::<T>();
        let bit_size = byte_size * 8;

        bit_size
    }

    /// Get bit value for the index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    pub fn get_bit(&self, index: usize) -> Option<bool> {
        self.bits[index]
    }

    /// Set new bit value for the index.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    pub fn set_bit(&mut self, index: usize, val: bool) {
        self.bits[index] = Some(val);
    }

    /// Set new bit value complying with constrains, already decided bit value can not be changed.
    ///
    /// Returns `Ok(())` in case constrains were not violated, `Err(&str)` otherwise.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    pub fn set_bit_within_constrains(
        &mut self,
        index: usize,
        val: bool,
    ) -> Result<(), &'static str> {
        match self.bits[index] {
            // Existing bit with a different value is a breach of constrains.
            Some(bit) if bit != val => return Err("Already decided bit value can not be changed!"),
            // The value is already present, nothing to do here.
            Some(_) => {}
            // No value set as yet so just assign it.
            None => self.bits[index] = Some(val),
        }

        Ok(())
    }

    /// Is bit decided already?
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    pub fn is_bit_decided(&self, index: usize) -> bool {
        let bit = self.bits[index];

        bit.is_some()
    }

    /// Form and return a number based on bits representation, pad/fill undecided bits by zeros.
    pub fn form_zero_padded_number<T: PrimInt>(&self) -> Result<T, &str> {
        if Self::bit_size::<T>() < self.size {
            return Err("Requested number type has not enough bits to represent the whole number!");
        }

        // Initialize the number with "0".
        let mut number: T = T::zero();

        // Construct the number by incorporating in all bits.
        for (index, _) in self.bits.iter().enumerate() {
            self.incorporate_bit(index, &mut number);
        }

        Ok(number)
    }

    /// Incorporate bit into the provided number.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of range.
    fn incorporate_bit<T: PrimInt>(&self, index: usize, number: &mut T) {
        let bit = self.bits[index];

        // Set only "1" bit as the "0" bit is there by default.
        match bit {
            Some(bit) if bit == true => {
                set_bit::<T>(number, index);
            }
            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use bits::Bits;

    #[test]
    fn bit_size() {
        assert_eq!(8, Bits::bit_size::<u8>());
        assert_eq!(16, Bits::bit_size::<u16>());
        assert_eq!(32, Bits::bit_size::<u32>());
        assert_eq!(64, Bits::bit_size::<u64>());
        assert_eq!(128, Bits::bit_size::<u128>());
    }

    #[test]
    fn new_bits_by_default_none() {
        let bit_rep = Bits::new::<u64>();

        for i in 0..Bits::bit_size::<u64>() {
            assert_eq!(
                None,
                bit_rep.get_bit(i),
                "Every bit should be empty in this phase, but the bit with index {} is not!",
                i
            );
        }
    }

    #[test]
    fn get_set_bit() {
        let mut bit_rep = Bits::new::<u64>();

        // By default all bits are None before being set otherwise.
        assert_eq!(None, bit_rep.get_bit(0));
        assert_eq!(None, bit_rep.get_bit(8));
        assert_eq!(None, bit_rep.get_bit(63));

        // Set 0-th bit to true.
        let index = 0;
        let val = true;
        bit_rep.set_bit(index, val);
        assert_eq!(Some(val), bit_rep.get_bit(index));

        // Set 22-nd bit to true.
        let index = 22;
        let val = false;
        bit_rep.set_bit(index, val);
        assert_eq!(Some(val), bit_rep.get_bit(index));

        // Set 63-rd bit to false.
        let index = 63;
        let val = false;
        bit_rep.set_bit(index, val);
        assert_eq!(Some(val), bit_rep.get_bit(index));

        // Override 63-rd bit to true.
        let index = 63;
        let val = true;
        bit_rep.set_bit(index, val);
        assert_eq!(Some(val), bit_rep.get_bit(index));
    }

    #[test]
    #[should_panic]
    fn get_bit_index_out_of_range() {
        let bit_rep = Bits::new::<u64>();

        let index_out_of_range = 64;
        bit_rep.get_bit(index_out_of_range);
    }

    #[test]
    #[should_panic]
    fn set_bit_index_out_of_range() {
        let mut bit_rep = Bits::new::<u64>();

        let index_out_of_range = 64;
        bit_rep.set_bit(index_out_of_range, true);
    }

    #[test]
    fn set_bit_within_constrains() {
        let mut bit_rep = Bits::new::<u64>();

        let index = 2;
        // Setting the bit value for the first time is OK as it wasn't decided yet.
        assert_eq!(Ok(()), bit_rep.set_bit_within_constrains(index, true));
        // Setting the same bit value for the second time is OK, as the value stays the same.
        assert_eq!(Ok(()), bit_rep.set_bit_within_constrains(index, true));
        // Setting the bit value with a different value then in previous step violates constrains.
        assert_eq!(
            Err("Already decided bit value can not be changed!"),
            bit_rep.set_bit_within_constrains(index, false)
        );
    }
}