1#![feature(array_methods)]
3#![feature(array_map)]
4
5#![cfg_attr(not(feature = "std"), no_std)]
6
7#![allow(dead_code)]
8
9mod dimutils;
10pub mod broadcast;
11
12
13#[cfg(test)]
14mod tests {
15 use crate::dimutils::*;
16 use crate::broadcast::*;
17
18
19 fn linear_iter_test<const N : usize>(size:[usize;N]) {
20 let index_coeffs = linearization_coeffs(size);
21 let indices = ndim_iterator(size);
22 for (i,index) in indices.enumerate() {
23 let lin_index = linearize_index(index,index_coeffs);
24 assert_eq!(i,lin_index);
25 assert_eq!(delinearize_index(lin_index,size),index);
26 }
27
28 }
29
30 #[test]
31 fn linearization() {
32 linear_iter_test([3,3]);
33 linear_iter_test([3,4]);
34 linear_iter_test([3,2,4,2]);
35 assert_eq!(linearization_coeffs([4]), [1]);
36 assert_eq!(linearization_coeffs([4,3]), [1,4]);
37 let mut a = ndim_iterator([3,4]);
38 let mut b = ndim_iterator([3,4]);
39 b.next();
40 b.next();
41 assert_eq!(a.nth(2),b.next())
42 }
43
44
45 fn game_of_life_rule(cell : u8, nbsum : u8) -> u8 {
46 match (cell,nbsum) {
47 (0,3) | (1,3) | (1,2)=> 1,
48 _ => 0
49 }
50 }
51
52
53 fn game_of_life_update<'a>(bc : &impl Broadcastable<2,Element=u8>,bc_target : &mut impl BroadcastReceiver<2,Element=u8> ) {
54 const NBOFFSETS : [[isize;2];8] = [[1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]];
55 let nbcells_separate = NBOFFSETS.map(|offset| bc.offset_mod(offset));
56 let nbcells = broadcast_k(nbcells_separate.each_ref());
57 let nb_sum = nbcells.bmap(|[a,b,c,d,e,f,g,h] : [u8;8]| a + b + c + d + e + f + g + h);
58 let nbsum_cell = nb_sum.broadcast2(bc);
59 let newcells = nbsum_cell.bmap(|(nbsum,cell) : (u8,u8)| game_of_life_rule(cell, nbsum));
60 newcells.feedto(bc_target);
61 }
62
63 #[test]
64 fn game_of_life_test() {
65 let mut gliderboard = [0, 1, 0, 0, 0,
66 0, 0, 1, 0, 0,
67 1, 1, 1, 0, 0,
68 0, 0, 0, 0, 0,
69 0, 0, 0, 0, 0].reshaped([5,5]);
70 let mut scratchpad = [0;5*5].reshaped([5,5]);
71
72 for _ in 0..8 {
73 game_of_life_update(&gliderboard, &mut scratchpad);
74 let tmp = gliderboard;
75 gliderboard = scratchpad;
76 scratchpad = tmp;
77 }
78
79 let glider_8th_gen = [0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0,
81 0, 0, 0, 1, 0,
82 0, 0, 0, 0, 1,
83 0, 0, 1, 1, 1].reshaped([5,5]);
84 assert_eq!(gliderboard,glider_8th_gen);
85 }
86
87 #[test]
88 fn it_works() {
89 let v = vec![1,2,3];
90 let u = vec![2,2,2];
91 let bv = (v).lazy_updim([3,4]).into_iter().collect::<Vec<i64>>();
92 let vdotu : i64 = u.broadcast2(&v).bmap(|(x,y)|x*y).iter().sum();
93 assert_eq!(vdotu,1*2 + 2*2 + 3*2);
94
95 println!("The elems of bv are {:?}",bv);
96 for x in &bv {
97 println!("{}",x);
98 }
99
100 assert_eq!(2 + 2, 4);
101 }
102}