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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#[allow(unused_imports)]
#[macro_use]
extern crate proptest;

pub mod constants;
pub mod math;

use constants::*;
use math::*;

const PANIC_OUT_OF_BOUNDS: &str = "Requested bits are out of bounds!";

#[derive(Default, Debug)]
pub struct Genestring {
    pieces: Vec<u64>,
}

/// Helper to write sequential bits in a gene string.
pub struct Writer<'a> {
    parent: &'a mut Genestring,
    offset: u64
}

/// Helper to read sequential bits from a gene string.
pub struct Reader<'a> {
    parent: &'a mut Genestring,
    offset: u64
}

impl Genestring {
    /// Creates a gene string capable of holding at least `count` bits.
    pub fn with_bits(count: u64) -> Genestring {
        let mut result = Genestring {
            pieces: Vec::with_capacity(count as usize),
        };
        result.pieces.resize(part_count_for_bits(count) as usize, 0);
        result
    }

    /// Returns a helper for writing values in to the genestring.
    pub fn writer(&mut self) -> Writer {
        Writer { parent: self, offset: 0 }
    }

    /// Returns a helper for reading values from the genestring.
    pub fn reader(&mut self) -> Reader {
        Reader { parent: self, offset: 0 }
    }

    /// Returns the number of bits in the gene string.
    pub fn bit_len(&self) -> usize {
        self.pieces.len() * PIECE_SIZE_IN_BITS as usize
    }

    /// Returns the number of bytes in the gene string.
    pub fn byte_len(&self) -> usize {
        self.pieces.len() * PIECE_SIZE_IN_BYTES as usize
    }

    /// Returns the number of integer parts of the gene string.
    pub fn len(&self) -> usize {
        self.pieces.len()
    }

    pub fn is_empty(&self) -> bool {
        self.pieces.is_empty()
    }

    /// Retrieves `bits` number of bits from the string, starting at a given `offset`. Panics if
    /// `bits` is larger than 64 or would otherwise go outside the bounds of the string.
    pub fn get(&self, offset: u64, bits: u64) -> u64 {
        if bits == 0 {
            return 0;
        }

        // safety dance
        if bits > 64 {
            panic!("Can only obtain 64 bits at a time!");
        }

        if bits + offset > self.bit_len() as u64 {
            panic!(PANIC_OUT_OF_BOUNDS);
        }

        // safety dance complete, now figure out which pieces have our bits
        let first_half_idx = part_for_bit(offset) as usize;
        let second_half_idx = part_for_bit(offset + (bits - 1)) as usize;

        let offset_modulo = offset % PIECE_SIZE_IN_BITS;

        let mut result: u64 = 0;

        if first_half_idx != second_half_idx {
            // accumulator
            let mut acc: u64 = 0;

            // calculate bit mask to use against value for first part
            let p1_bits = PIECE_SIZE_IN_BITS - offset_modulo;
            for i in 0..p1_bits {
                acc += 1 << i;
            }
            let value_mask1 = acc;

            // calculate bit mask to use against value for second part
            let p2_bits = bits - p1_bits;
            acc = 0;
            for i in 0..p2_bits {
                acc += 1 << i;
            }
            let piece_mask2 = acc;

            let piece_mask1 = value_mask1 << offset_modulo;

            result = (self.pieces[first_half_idx] & piece_mask1) >> offset_modulo;
            result += (self.pieces[second_half_idx] & piece_mask2) << p1_bits;
        } else {
            let first_half = self.pieces[first_half_idx];

            let piece = first_half;
            for i in offset_modulo..(offset_modulo + bits) {
                let mask = 1 << i;
                result += piece & mask;
            }

            result >>= offset_modulo;
        }

        result
    }

    /// Provides an immutable iterator for the gene string's internal bank of integers.
    pub fn piece_iter(&self) -> std::slice::Iter<'_, u64> {
        self.pieces.iter()
    }

    /// Provides a mutable iterator for the gene string's internal bank of integers.
    pub fn piece_iter_mut(&mut self) -> std::slice::IterMut<'_, u64> {
        self.pieces.iter_mut()
    }

    /// Assigns a value at the given bit offset and bit length.
    pub fn set(&mut self, offset: u64, bits: u64, value: u64) {
        if bits == 0 {
            return;
        }

        // safety dance
        if bits > 64 {
            panic!("Can only write 64 bits at a time!");
        }

        if bits + offset > self.bit_len() as u64 {
            panic!(PANIC_OUT_OF_BOUNDS);
        }

        let first_half_idx = part_for_bit(offset) as usize;
        let second_half_idx = part_for_bit(offset + (bits - 1)) as usize;

        let mut source_mask = 0;

        let offset_modulo = offset % PIECE_SIZE_IN_BITS;

        if first_half_idx == second_half_idx {
            // in this path, we are just writing to bits inside the same integer
            for i in 0..bits {
                source_mask += 1 << i;
            }

            let destination_mask = source_mask << offset_modulo;

            self.pieces[first_half_idx] = (self.pieces[first_half_idx] & !destination_mask)
                + ((value as u64 & source_mask) << offset_modulo);
        } else {
            // accumulator
            let mut acc: u64 = 0;

            // calculate bit mask to use against value for first part
            let p1_bits = PIECE_SIZE_IN_BITS - offset_modulo;
            for i in 0..p1_bits {
                acc += 1 << i;
            }
            let value_mask1 = acc;

            // calculate bit mask to use against value for second part
            let p2_bits = bits - p1_bits;
            acc = 0;
            for i in 0..p2_bits {
                acc += 1 << i;
            }
            let piece_mask2 = acc;
            acc <<= p1_bits;
            let value_mask2 = acc;

            let piece_mask1 = value_mask1 << offset_modulo;

            self.pieces[first_half_idx] = (self.pieces[first_half_idx] & !piece_mask1)
                + ((value & value_mask1) << offset_modulo);
            self.pieces[second_half_idx] =
                (self.pieces[second_half_idx] & !piece_mask2) + ((value & value_mask2) >> p1_bits);
        }
    }

    /// Copies bits from a given offset and bit length from a donor to self.
    /// Both strings do not need to be the same total length, but the range being copied must
    /// be valid and the same for both donor and self.
    /// Used to implement crossover.
    pub fn transplant(&mut self, donor: &Genestring, offset: u64, bits: u64) {
        let end = bits + offset;

        if end > self.bit_len() as u64 || end > donor.bit_len() as u64 {
            panic!(PANIC_OUT_OF_BOUNDS);
        }

        if bits <= 64 {
            self.set(offset, bits, donor.get(offset, bits));
        } else {
            let mut offset = offset;
            let bit_windows = bits / PIECE_SIZE_IN_BITS;
            for _ in 0..bit_windows {
                self.set(
                    offset,
                    PIECE_SIZE_IN_BITS,
                    donor.get(offset, PIECE_SIZE_IN_BITS),
                );
                offset += PIECE_SIZE_IN_BITS;
            }
            self.set(
                offset,
                bits % PIECE_SIZE_IN_BITS,
                donor.get(offset, bits % PIECE_SIZE_IN_BITS),
            );
        }
    }
}

impl<'a> Writer<'a> {
    /// Pushes a value in to the bit string, then increments the writer's offset by the number
    /// of bits written.
    pub fn push(&mut self, bits: u64, value: u64) {
        self.parent.set(self.offset, bits, value);
        self.offset += bits;
    }
}

impl<'a> Reader<'a> {
    /// Reads the next `bits` bits from the string, then increments the reader's offset by the
    /// number of bits read.
    pub fn next(&mut self, bits: u64) -> u64 {
        let result = self.parent.get(self.offset, bits);
        self.offset += bits;
        result
    }
}

#[cfg(test)]
mod tests {
    use *;

    #[test]
    fn assume_intdiv_rounds_down() {
        assert_eq!(4 / 5, 0);
        assert_eq!(7 / 5, 1);
    }

    #[test]
    fn calculating_bi_offsets() {
        // just making sure the way we do bit offsets is correct
        let offset = 50;
        let bits = 32;
        let mut total = 0;

        let start = offset % PIECE_SIZE_IN_BITS;
        let stop = PIECE_SIZE_IN_BITS;

        for _ in start..stop {
            total += 1;
        }

        let stop = bits - (stop - start);
        let start = 0;

        for _ in start..stop {
            total += 1;
        }

        assert_eq!(total, bits);
    }

    // These two tests are very basic idiot tests, but are no means exhaustive.

    #[test]
    fn get_set_same_chunk() {
        assert_eq!(PIECE_SIZE_IN_BITS, 64);
        let mut gs = Genestring::with_bits(32);

        eprintln!("{:?}", gs);
        gs.set(8, 12, 842);
        eprintln!("{:?}", gs);
        assert_eq!(gs.get(8, 12), 842);
    }

    #[test]
    fn get_set_different_chunk() {
        assert_eq!(PIECE_SIZE_IN_BITS, 64);
        let mut gs = Genestring::with_bits(128);

        eprintln!("{:?}", gs);
        gs.set(60, 8, 0xFF);
        eprintln!("{:?}", gs);
        assert_eq!(gs.pieces[0], 0xF000000000000000);
        assert_eq!(gs.pieces[1], 0x000000000000000F);
        assert_eq!(gs.get(60, 8), 0xFF);
    }

    #[test]
    fn string_size_minimum() {
        // just making sure this bit of math works as we expect it to
        assert_eq!(PIECE_SIZE_IN_BITS, 64);
        assert_eq!(part_count_for_bits(0), 1);
    }

    // proptest does some more intensive checks to ensure things like split numbers always work
    // or we don't trample non-overlapping numbers doing arithmetic.

    proptest! {
        #[test]
        fn string_size_blocks(blocks in 1..10) {
            // just making sure this bit of math works as we expect it to
            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            assert_eq!(part_count_for_bits(blocks as u64 * PIECE_SIZE_IN_BITS), blocks as u64);
        }

        #[test]
        fn string_size_subblocks(blocks in 1..10, subblock in 1..32) {
            // just making sure this bit of math works as we expect it to
            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            assert_eq!(part_count_for_bits((blocks as u64 * PIECE_SIZE_IN_BITS) + subblock as u64), blocks as u64 + 1);
        }

        #[test]
        fn get_set_single(start in 0..256, len in 1..64, value: u64) {
            // we're going to get and set values at various offsets and make sure we always get
            // back the thing we wanted to start with

            prop_assume!((start + len) < 256, "Value must be within bit string boundaries.");

            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            let mut gs = Genestring::with_bits(256);

            let mut band: u64 = 0;
            for i in 0..len {
                band += 1 << i;
            }

            let banded_value = value as u64 & band;
            gs.set(start as u64, len as u64, banded_value);
            prop_assert_eq!(gs.get(start as u64, len as u64), banded_value);
        }

        #[test]
        fn get_set_1piece_duo(a in 0..16, b in 32..48, value_a: u16, value_b: u16) {
            // We are going to store two values within the same piece, guaranteed not to overlap,
            // and ensure they do not trample one another.

            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            let mut gs = Genestring::with_bits(64);

            gs.set(a as u64, 16, value_a as u64);
            gs.set(b as u64, 16, value_b as u64);

            prop_assert_eq!(gs.get(a as u64, 16), value_a as u64);
            prop_assert_eq!(gs.get(b as u64, 16), value_b as u64);
        }

        #[test]
        fn get_set_multibinning(a in 0..16, b in 32..100, value_a: u16, value_b: u16) {
            // We have one value which is always in the first piece, and a second value which
            // can span any non-overlap location in either piece. Ensures our single and double
            // piece logics don't conflict.

            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            let mut gs = Genestring::with_bits(128);

            gs.set(a as u64, 16, value_a as u64);
            gs.set(b as u64, 16, value_b as u64);

            prop_assert_eq!(gs.get(a as u64, 16), value_a as u64);
            prop_assert_eq!(gs.get(b as u64, 16), value_b as u64);
        }

        #[test]
        fn transplanting_small_ranges(a in 0..32, b in 64..100, value_a: u16, value_b: u16) {
            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            let mut gs  = Genestring::with_bits(128);
            let mut gs2 = Genestring::with_bits(128);

            gs.set(a as u64, 16, value_a as u64);
            gs.set(b as u64, 16, value_b as u64);

            gs2.transplant(&gs, a as u64, 16);
            gs2.transplant(&gs, b as u64, 16);

            prop_assert_eq!(gs2.get(a as u64, 16), value_a as u64);
            prop_assert_eq!(gs2.get(b as u64, 16), value_b as u64);
        }

        #[test]
        fn transplanting_small_ranges_blocked(a in 0..8, b in 0..8, value_a: u16, value_b: u16) {
            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            prop_assume!(a != b, "Blocks cannot overlap.");

            let mut gs  = Genestring::with_bits(8 * 16);
            let mut gs2 = Genestring::with_bits(8 * 16);

            gs.set(a as u64 * 16, 16, value_a as u64);
            gs.set(b as u64 * 16, 16, value_b as u64);

            gs2.transplant(&gs, a as u64 * 16, 16);
            gs2.transplant(&gs, b as u64 * 16, 16);

            prop_assert_eq!(gs2.get(a as u64 * 16, 16), value_a as u64);
            prop_assert_eq!(gs2.get(b as u64 * 16, 16), value_b as u64);
        }

        #[test]
        fn transplanting_large_ranges(a in 0..16, b in 0..16, value_a: u16, value_b: u16) {
            prop_assume!(a != b, "Overlapping is not allowed.");

            assert_eq!(PIECE_SIZE_IN_BITS, 64);
            let mut gs  = Genestring::with_bits(16 * 16);
            let mut gs2 = Genestring::with_bits(16 * 16);

            gs.set((a * 16) as u64, 16, value_a as u64);
            prop_assert_eq!(gs.get(a as u64 * 16, 16), value_a as u64);
            gs.set((b * 16) as u64, 16, value_b as u64);
            prop_assert_eq!(gs.get(a as u64 * 16, 16), value_a as u64);
            prop_assert_eq!(gs.get(b as u64 * 16, 16), value_b as u64);

            //gs2.transplant(&gs, (a * 16) as u64, ((b * 16) as u64 + 16) - (a * 16) as u64);
            gs2.transplant(&gs, 0, 16 * 16);

            prop_assert_eq!(gs.get(a as u64 * 16, 16), value_a as u64);
            prop_assert_eq!(gs.get(b as u64 * 16, 16), value_b as u64);

            prop_assert_eq!(gs2.get(a as u64 * 16, 16), value_a as u64);
            prop_assert_eq!(gs2.get(b as u64 * 16, 16), value_b as u64);
        }
    }
}