libttl/
logic_level.rs

1//! Defines the logic levels used in the TTL simulation.
2
3use std::ops::Not;
4
5/// Represents the logic level of a pin.
6/// For simplicity, we only model HIGH and LOW, not floating or undefined states.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum LogicLevel {
9    Low,
10    High,
11}
12
13impl Default for LogicLevel {
14    fn default() -> Self {
15        LogicLevel::Low
16    }
17}
18
19impl Not for LogicLevel {
20    type Output = Self;
21
22    /// Implements the NOT logic operation.
23    fn not(self) -> Self::Output {
24        match self {
25            LogicLevel::Low => LogicLevel::High,
26            LogicLevel::High => LogicLevel::Low,
27        }
28    }
29}
30
31impl From<bool> for LogicLevel {
32    /// Converts a boolean to a LogicLevel (true -> High, false -> Low).
33    fn from(value: bool) -> Self {
34        if value {
35            LogicLevel::High
36        } else {
37            LogicLevel::Low
38        }
39    }
40}
41
42impl From<LogicLevel> for bool {
43    /// Converts a LogicLevel to a boolean (High -> true, Low -> false).
44    fn from(value: LogicLevel) -> Self {
45        match value {
46            LogicLevel::High => true,
47            LogicLevel::Low => false,
48        }
49    }
50}
51
52// Helper functions for clarity in gate logic
53pub fn and(a: LogicLevel, b: LogicLevel) -> LogicLevel {
54    match (a, b) {
55        (LogicLevel::High, LogicLevel::High) => LogicLevel::High,
56        _ => LogicLevel::Low,
57    }
58}
59
60pub fn or(a: LogicLevel, b: LogicLevel) -> LogicLevel {
61    match (a, b) {
62        (LogicLevel::Low, LogicLevel::Low) => LogicLevel::Low,
63        _ => LogicLevel::High,
64    }
65}
66
67pub fn nand(a: LogicLevel, b: LogicLevel) -> LogicLevel {
68    !and(a, b)
69}
70
71pub fn nor(a: LogicLevel, b: LogicLevel) -> LogicLevel {
72    !or(a, b)
73}
74
75pub fn xor(a: LogicLevel, b: LogicLevel) -> LogicLevel {
76    match (a, b) {
77        (LogicLevel::Low, LogicLevel::High) | (LogicLevel::High, LogicLevel::Low) => {
78            LogicLevel::High
79        }
80        _ => LogicLevel::Low,
81    }
82}