cellular_lib 0.1.1

A library for simulation of cellular automata
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
use std::fmt;
use std::ops::Add;

/// Trait Newable are all objects that have a new method
pub trait Newable {
    fn new() -> Self;
}

/// Trait Parseable are all objects that have a parse method (string to object)
pub trait Parseable {
    fn parse(_: &str) -> Self;
}

/// Trait Encodeable are all objects that have an encode method (object to string)
pub trait Encodeable {
    fn encode(&self) -> String;
}

/// Trait Equalable are all objects that can be compared to themselves
pub trait Equalable {
    fn equals(&self, _: &Self) -> bool;
}

/// Trait Hashable are all objects that a hash can be extracted from (a hash is a unique identifier for the object)
pub trait Hashable {
    fn hash(&self) -> usize;
}

/// `debug_passed` is a macro that takes an input (preferably a string) as the checkpoint name and prints "passed checkpoint <name> in file <file> line <line>"
#[macro_export]
macro_rules! debug_passed {
    ($x:expr) => {
        #[cfg(debug_assertions)]
        {
            println!(
                "Program execution passed checkpoint <{}>, in file <{}> line <{}>",
                $x,
                file!(),
                line!()
            )
        }
    };
}

/// `debug_val` is a macro that prints out a value (for debugging purposes)
#[macro_export]
macro_rules! debug_val {
    ($val:expr) => {
        #[cfg(debug_assertions)]
        {
            match $val {
                tmp => {
                    println!(
                        "<{}> <{}> {} = {:#?}",
                        file!(),
                        line!(),
                        stringify!($val),
                        &tmp
                    );
                    tmp
                }
            }
        }
    };
}

/// `debug_emit` is a macro that prints to stderr
#[macro_export]
macro_rules! debug_emit {
    ($val:expr) => {
        #[cfg(debug_assertions)]
        {
            println!("<{}> <{}>, {}", file!(), line!(), $val)
        };
    };
}

/// `TwoTuple` is a 2 element tuple
#[derive(Clone, Copy, Debug)]
pub struct TwoTuple<DataTypeA: Clone, DataTypeB: Clone> {
    a: DataTypeA,
    b: DataTypeB,
}

impl<DataTypeA: Clone, DataTypeB: Clone> TwoTuple<DataTypeA, DataTypeB> {
    pub fn new(input1: DataTypeA, input2: DataTypeB) -> Self {
        Self {
            a: input1,
            b: input2,
        }
    }
    pub fn car(&self) -> DataTypeA {
        self.a.clone()
    }
    pub fn cdr(&self) -> DataTypeB {
        self.b.clone()
    }
}

/// `UsizeWrapper` is a wrapper for usize satisfying various traits
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct UsizeWrapper {
    data: usize,
}

/// `SmallNumberWrapper` is a wrapper for a small number (u16)
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SmallNumberWrapper {
    data: u16,
}

/// `StringWrapper` is a wrapper for string satisfying various traits
#[derive(Clone, Debug, PartialEq)]
pub struct StringWrapper {
    data: String,
}

pub const NANO_VEC_BUFFER_SIZE: usize = 16;

/// `NanoVec` is an inlined small vector that can hold `NANO_VEC_BUFFER_SIZE` elements, at most
#[derive(Clone)]
pub struct NanoVec<T: Clone + Encodeable> {
    data: [T; NANO_VEC_BUFFER_SIZE],
    len: usize,
}

impl<'a, T: Clone + Encodeable + Newable + fmt::Debug> IntoIterator for &'a NanoVec<T> {
    type Item = &'a T;
    type IntoIter = NanoVecRefIntoIter<'a, T>;
    fn into_iter(self) -> Self::IntoIter {
        NanoVecRefIntoIter {
            data: &self.data,
            index: 0,
            len: self.len,
        }
    }
}

impl<T: Clone + Encodeable + Newable + PartialEq> PartialEq for NanoVec<T> {
    fn eq(&self, other: &Self) -> bool {
        let mut to_return = true;
        if self.len != other.len {
            to_return = false;
        } else {
            for j in 0..self.len {
                if self.at(j) != other.at(j) {
                    to_return = false;
                    break;
                }
            }
        }
        to_return
    }
}

impl<T: Clone + Encodeable + Newable> IntoIterator for NanoVec<T> {
    type Item = T;
    type IntoIter = NanoVecIntoIter<T>;
    fn into_iter(self) -> Self::IntoIter {
        NanoVecIntoIter {
            data: self.data,
            index: 0,
            len: self.len,
        }
    }
}

pub struct NanoVecIntoIter<T: Clone + Encodeable + Newable> {
    data: [T; NANO_VEC_BUFFER_SIZE],
    index: usize,
    len: usize,
}

pub struct NanoVecRefIntoIter<'a, T: Clone + Encodeable + Newable> {
    data: &'a [T; NANO_VEC_BUFFER_SIZE],
    index: usize,
    len: usize,
}

impl<T: Clone + Encodeable + Newable> Iterator for NanoVecIntoIter<T> {
    type Item = T;
    #[inline(always)]
    fn next(&mut self) -> Option<T> {
        if self.index >= self.len {
            None
        } else {
            self.index += 1;
            Some(self.data[self.index - 1].clone())
        }
    }
}

impl<'a, T: Clone + Encodeable + Newable + fmt::Debug> Iterator for NanoVecRefIntoIter<'a, T> {
    type Item = &'a T;
    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.len {
            None
        } else {
            self.index += 1;
            Some(&self.data[self.index - 1])
        }
    }
}

impl<T: Clone + Encodeable + Newable> NanoVec<T> {
    /// Function `new` creates a new `NanoVec` with given size, with every element set to a clone of `init_val`
    pub fn new(size: usize, init_val: T) -> NanoVec<T> {
        if size > NANO_VEC_BUFFER_SIZE {
            panic!("NanoVec can only hold up to NANO_VEC_BUFFER_SIZE elements");
        }
        Self {
            data: [
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
                init_val.clone(),
            ],
            len: size,
        }
    }
    /// Function `new_default` creates a blank `NanoVec`, assuming a `Newable` data type.
    /// The data of the resulting `NanoVec` is filled with the default value, returned by Newable::new()
    pub fn new_default(size: usize) -> NanoVec<T> {
        if size > NANO_VEC_BUFFER_SIZE {
            panic!("NanoVec can only hold up to NANO_VEC_BUFFER_SIZE elements");
        }
        Self {
            data: [
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
                Newable::new(),
            ],
            len: size,
        }
    }
    /// Function `len` returns the length of the NanoVec
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len
    }
    /// Function `at` returns a reference to the data at a given address
    #[inline(always)]
    pub fn at(&self, idx: usize) -> &T {
        if idx < self.len {
            &self.data[idx]
        } else {
            panic!("Index out of bounds");
        }
    }
    /// Function `set_at` sets the data at a given address
    #[inline(always)]
    pub fn set_at(&mut self, idx: usize, data_1: T) {
        if idx < self.len {
            self.data[idx] = data_1;
        } else {
            panic!("Index out of bounds");
        }
    }
    /// Function `to_slice` returns the data of the `NanoVec` as a slice
    pub fn to_slice(&self) -> &[T] {
        &self.data
    }
    /// Function `from_slice` constructs a NanoVec from a slice
    pub fn from_slice(input: &[T]) -> Self {
        if input.len() > 16 {
            panic!("NanoVec can only hold 16 elements");
        }
        let mut tmp = [
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
            input[0].clone(),
        ];
        for (j, item) in input.iter().enumerate() {
            tmp[j] = item.clone();
        }
        Self {
            data: tmp,
            len: input.len(),
        }
    }
    /// Function `push` appends a value to the `NanoVec`, and increases the size
    pub fn push(&mut self, elem: T) {
        if self.len + 1 >= 16 {
            panic!("NanoVec is full");
        }
        self.len += 1;
        self.data[self.len - 1] = elem;
    }
}

impl<T: Clone + Encodeable> fmt::Debug for NanoVec<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut temp = String::new();
        temp += "NanoVec [";
        for j in 0..self.len {
            temp += &Encodeable::encode(&self.data[j]);
            if j != self.len - 1 {
                temp += ", ";
            }
        }
        temp += "]";
        write!(f, "{}", temp)
    }
}

impl<T: Clone + Encodeable> Encodeable for NanoVec<T> {
    /// Function `encode` returns the string representation of the object (encodes it as a string)
    fn encode(&self) -> String {
        let mut to_return = String::new();
        for j in 0..16 {
            to_return += &Encodeable::encode(&self.data[j]);
        }
        to_return
    }
}

impl UsizeWrapper {
    /// Function `from` returns an `UsizeWrapper` with the same value as `data_1`
    pub fn from(data_1: usize) -> Self {
        Self { data: data_1 }
    }
    /// Function `get_data` returns the data from an `UsizeWrapper`
    pub fn get_data(&self) -> usize {
        self.data
    }
}
impl Add for UsizeWrapper {
    type Output = UsizeWrapper;
    fn add(self, other: UsizeWrapper) -> Self {
        Self {
            data: self.get_data() + other.get_data(),
        }
    }
}
impl Add<u16> for UsizeWrapper {
    type Output = UsizeWrapper;
    fn add(self, other: u16) -> Self {
        Self {
            data: self.get_data() + (other as usize),
        }
    }
}
impl Add<u32> for UsizeWrapper {
    type Output = UsizeWrapper;
    fn add(self, other: u32) -> Self {
        Self {
            data: self.get_data() + (other as usize),
        }
    }
}

impl Add<u64> for UsizeWrapper {
    type Output = UsizeWrapper;
    fn add(self, other: u64) -> Self {
        Self {
            data: self.get_data() + (other as usize),
        }
    }
}

impl Newable for UsizeWrapper {
    /// Function `new` creates an `UsizeWrapper` with 0 as the data
    fn new() -> Self {
        Self { data: 0 }
    }
}
impl Parseable for UsizeWrapper {
    /// Function `parse` converts a string into an `UsizeWrapper`
    fn parse(data: &str) -> Self {
        Self {
            data: data.parse::<usize>().unwrap(),
        }
    }
}
impl Encodeable for UsizeWrapper {
    /// Function `encode` returns the string representation of the `UsizeWrapper` (encodes it)
    fn encode(&self) -> String {
        self.data.to_string()
    }
}

impl SmallNumberWrapper {
    /// Function `from` returns a `SmallNumberWrapper` with the same value as `data_1`
    pub fn from(data_1: u16) -> Self {
        Self { data: data_1 }
    }
    /// Function `get_data` returns the data from an `SmallNumberWrapper`
    pub fn get_data(&self) -> u16 {
        self.data
    }
}
impl Newable for SmallNumberWrapper {
    /// Function `new` creates an `SmallNumberWrapper` with 0 as the data
    fn new() -> Self {
        Self { data: 0 }
    }
}
impl Parseable for SmallNumberWrapper {
    /// Function `parse` converts a string into an `SmallNumberWrapper`
    fn parse(data: &str) -> Self {
        Self {
            data: data.parse::<u16>().unwrap(),
        }
    }
}
impl Encodeable for SmallNumberWrapper {
    /// Function `encode` returns the string representation of the `SmallNumberWrapper` (encodes it)
    fn encode(&self) -> String {
        self.data.to_string()
    }
}

impl Newable for StringWrapper {
    /// Function `new` creates a blank `StringWrapper` (empty data)
    fn new() -> Self {
        Self {
            data: String::new(),
        }
    }
}
impl Parseable for StringWrapper {
    /// Function `parse` turns a str into a `StringWrapper` (parses the string)
    fn parse(data: &str) -> Self {
        Self {
            data: data.parse::<String>().unwrap(),
        }
    }
}
impl Encodeable for StringWrapper {
    /// Function `encode` turns the StringWrapper into a String (encodes it)
    fn encode(&self) -> String {
        self.data.clone()
    }
}

/// Function `parse_csv_list` parses a comma seperated list
pub fn parse_csv_list<DataType: Parseable + Clone>(input: &str, character: char) -> Vec<DataType> {
    let mut to_return: Vec<DataType> = Vec::new();
    for elem in input.split(character) {
        to_return.push(Parseable::parse(elem));
    }
    to_return
}
pub fn parse_csv_list_native<DataType: std::str::FromStr>(
    input: &str,
    character: char,
) -> Vec<DataType> {
    let mut to_return: Vec<DataType> = Vec::new();
    for elem in input.split(character) {
        to_return.push(if let Ok(a) = elem.parse::<DataType>() {
            a
        } else {
            panic!("Invalid token found");
        });
    }
    to_return
}
/// Function `parse_list` parses a list
pub fn parse_list_multi<DataType: Parseable + Clone>(
    input: &str,
    vocab: &str,
    level: usize,
) -> Vec<DataType> {
    if level >= vocab.len() {
        panic!("Out of tokens");
    }
    let token = {
        if let Some(a) = vocab.chars().nth(level) {
            a
        } else {
            panic!("Out of tokens");
        }
    };
    let mut to_return: Vec<DataType> = Vec::new();
    for elem in input.split(token) {
        to_return.push(Parseable::parse(elem));
    }
    to_return
}

/// Function `split_str` splits a &str
pub fn split_str(input: &str, token: char) -> Vec<&str> {
    input.split(token).collect::<Vec<&str>>()
}

/// Function `parse_table` parses a table and returns the sections
pub fn parse_table_sections(input: &str) -> Vec<String> {
    let the_string = input.to_string();
    let fst = {
        if let Some(a) = the_string.split(';').nth(0) {
            a
        } else {
            panic!("Symbol table is invalid");
        }
    };
    let header_len = {
        if let Ok(a) = fst.to_string().parse::<usize>() {
            a
        } else {
            panic!("Header length is not an integer");
        }
    };
    let header_start = fst.chars().count() + 1;
    let header_end = header_start + header_len;
    let body_start = header_end + 1;
    let body_end = the_string.chars().count();
    let header = (&the_string[header_start..header_end]).to_string();
    let body = (&the_string[body_start..body_end]).to_string();
    if the_string.chars().collect::<Vec<char>>()[body_start - 1] != ';' {
        panic!("Symbol table is invalid");
    }

    let tokenized_header = {
        let mut to_return: Vec<usize> = Vec::new();
        let tmp = header.split(',').collect::<Vec<&str>>();
        for item in tmp {
            if let Ok(a) = item.to_string().parse::<usize>() {
                to_return.push(a);
            } else {
                panic!("Symbol table is invalid");
            }
        }
        to_return
    };
    let mut to_return: Vec<String> = Vec::new();
    let mut old_offset = 0;
    for item in tokenized_header {
        to_return.push((&body[(old_offset)..(old_offset + item)]).to_string());
        old_offset += item + 1;
    }
    to_return
}

/// Function `encode_table_sections` takes a vector of Strings and makes a table from them
pub fn encode_table_sections(input: &[String]) -> String {
    let mut to_return = String::new();
    let lengths: Vec<usize> = input.iter().map(|x| x.len()).collect();
    let header_length = {
        let mut to_ret = 0;
        for item in &lengths {
            to_ret += item.to_string().len();
            to_ret += 1; // because after each entry in the lengths table, there is a comma
                         // (if the lengths vector is [2, 3], the string representation of that would be
                         // "2,3", so a the header length has to be increased to account for that
        }
        to_ret -= 1; // There is a comma only BETWEEN 2 lengths, not AFTER each length
        to_ret
    };
    to_return += &header_length.to_string();
    to_return += ";";
    for (j, item) in lengths.iter().enumerate() {
        to_return += &item.to_string();
        to_return += {
            if j == lengths.len() - 1 {
                ";"
            } else {
                ","
            }
        };
    }
    for item in input {
        to_return += item;
        to_return += ",";
    }
    to_return
}

/// Function `addr_normal_to_flattened` converts the normal address to flattened address
#[inline(always)]
pub fn addr_normal_to_flattened(coords: &[isize], sizes: &[usize]) -> usize {
    let mut addr: usize = 0;
    for j in 0..sizes.len() {
        addr += (coords[j] * (sizes[j] as isize)) as usize;
    }
    addr
}

/// Function `addr_normal_to_flattened_usize` does the same as `addr_normal_to_flattened`, just
/// with coords and sizes both as usize slices
#[inline(always)]
pub fn addr_normal_to_flattened_usize(coords: &[usize], sizes: &[usize]) -> usize {
    let mut addr: usize = 0;
    for j in 0..sizes.len() {
        addr += coords[j] * sizes[j];
    }
    addr
}

/// Function `addr_normal_to_flattened_usize_wrapper_ref` does the same as
/// `addr_normal_to_flattened`, just with coords as `usizeWrapper` reference
/// slices
#[inline(always)]
pub fn addr_normal_to_flattened_usize_wrapper_ref(
    coords: &[&UsizeWrapper],
    sizes: &[usize],
) -> usize {
    let mut addr: usize = 0;
    for j in 0..sizes.len() {
        addr += coords[j].get_data() * sizes[j];
    }
    addr
}

/// Function `compute_sizes` computes the size of each dimension from the number of each dimension
#[inline(always)]
pub fn compute_sizes(dimensions: &[usize], len: usize) -> Vec<usize> {
    let mut old_len = len;
    dimensions
        .iter()
        .map(|&x| {
            old_len /= x;
            old_len
        })
        .collect::<Vec<usize>>()
}

/// Function `addr_flattened_to_normal` converts the index of an element in a flattened vector to
/// the index in a normal vector
#[inline(always)]
pub fn addr_flattened_to_normal(addr: usize, sizes: &[usize]) -> Vec<usize> {
    let mut to_return: Vec<usize> = Vec::new();
    let mut old: usize = addr;
    for item in sizes {
        let mut count = 0;
        while old >= *item {
            // to prevent subtracting off too much
            old -= *item;
            count += 1;
        }
        to_return.push(count);
    }
    to_return
}

/// Function `access_flattened_vec` gets the data out of a flattened vector (for example, the vector [[2, 1], [2, 3]] would be flattened to [2,1,2,3] with dimensions [2,2])
#[inline(always)]
pub fn access_flattened_vec<'a, T>(
    list: &'a [T],
    coords: &[isize],
    dimensions: &[usize],
    offset: usize,
    edge_val: &'a T,
) -> &'a T {
    if coords.len() != dimensions.len() {
        panic!("Dimensions do not match");
    }
    let sizes = compute_sizes(dimensions, list.len());
    /*
    let mut old_len = list.len();
    let sizes = dimensions
        .iter()
        .map(|&x| {
            old_len /= x;
            old_len
        })
        .collect::<Vec<usize>>();
    let mut addr: usize = 0;
    for j in 0..sizes.len() {
        addr += (coords[j] * (sizes[j] as isize)) as usize;
    }
    */
    let mut addr = addr_normal_to_flattened(&coords, &sizes);
    if is_flattened_address_off_grid(offset, coords, &sizes, dimensions) {
        return edge_val;
    } else {
        addr += offset;
    }
    &list[addr]
}

/// Function `is_flattened_address_off_grid` returns whether the flattened address + offset is off the grid or not
#[inline(always)]
pub fn is_flattened_address_off_grid(
    offset: usize,
    coords: &[isize],
    sizes: &[usize],
    dimensions: &[usize],
) -> bool {
    let actual_addr = addr_flattened_to_normal(offset, sizes);
    for (j, item) in actual_addr.iter().enumerate() {
        let tmp = (*item as isize) + coords[j];
        if tmp < 0 || tmp > dimensions[j] as isize {
            return true;
        }
    }
    false
    /*
    let mut old: isize = offset as isize;
    for (j, item) in sizes.iter().enumerate() {
        let mut count = 0;
        while old >= *item as isize {
            // to prevent subtracting off too much
            old -= *item as isize;
            count += 1;
        }
        count += coords[j];
        if count < 0 || count > dimensions[j] as isize {
            return true;
        }
    }
    false
    */
}