logicsim/circuits/
constant.rs

1use crate::data_structures::BitIter;
2use crate::graph::*;
3
4/// Returns a [Vec] of [ON] or [OFF] values representing the bits of any
5/// [Copy] + [Sized] + ['static](https://doc.rust-lang.org/rust-by-example/scope/lifetime/static_lifetime.html) `value`.
6///
7/// # Example
8/// ```
9/// # use logicsim::{GateGraphBuilder,constant};
10/// # let mut g = GateGraphBuilder::new();
11/// let c = constant(54u8);
12///
13/// let output = g.output(&c, "const");
14/// let gi = &mut g.init();
15///
16/// assert_eq!(output.u8(gi), 54);
17/// ```
18pub fn constant<T: Copy + Sized + 'static>(value: T) -> Vec<GateIndex> {
19    let width = std::mem::size_of::<T>() * 8;
20    let mut out = Vec::new();
21    out.reserve(width);
22
23    for bit in BitIter::new(value) {
24        if bit {
25            out.push(ON);
26        } else {
27            out.push(OFF)
28        };
29    }
30
31    out
32}
33
34/// Returns a [Vec] of size `n` full of [OFF].
35pub fn zeros(n: usize) -> Vec<GateIndex> {
36    (0..n).map(|_| OFF).collect()
37}
38/// Returns a [Vec] of size `n` full of [ON].
39pub fn ones(n: usize) -> Vec<GateIndex> {
40    (0..n).map(|_| ON).collect()
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn test_constant() {
49        let constants = [0, 0b1u8, 0b10010010];
50        let results = [
51            [false, false, false, false, false, false, false, false],
52            [true, false, false, false, false, false, false, false],
53            [false, true, false, false, true, false, false, true],
54        ];
55        for (c, result) in constants.iter().zip(results.iter()) {
56            let mut graph = GateGraphBuilder::new();
57            let g = &mut graph;
58            let output: Vec<_> = constant(*c);
59            let out = g.output(&output, "out");
60
61            let g = &mut graph.init();
62
63            for (i, result) in result.iter().enumerate() {
64                assert_eq!(out.bx(g, i), *result)
65            }
66        }
67    }
68}