libttl 0.1.1

A library for simulating TTL logic chips
Documentation
//! Defines the logic levels used in the TTL simulation.

use std::ops::Not;

/// Represents the logic level of a pin.
/// For simplicity, we only model HIGH and LOW, not floating or undefined states.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogicLevel {
    Low,
    High,
}

impl Default for LogicLevel {
    fn default() -> Self {
        LogicLevel::Low
    }
}

impl Not for LogicLevel {
    type Output = Self;

    /// Implements the NOT logic operation.
    fn not(self) -> Self::Output {
        match self {
            LogicLevel::Low => LogicLevel::High,
            LogicLevel::High => LogicLevel::Low,
        }
    }
}

impl From<bool> for LogicLevel {
    /// Converts a boolean to a LogicLevel (true -> High, false -> Low).
    fn from(value: bool) -> Self {
        if value {
            LogicLevel::High
        } else {
            LogicLevel::Low
        }
    }
}

impl From<LogicLevel> for bool {
    /// Converts a LogicLevel to a boolean (High -> true, Low -> false).
    fn from(value: LogicLevel) -> Self {
        match value {
            LogicLevel::High => true,
            LogicLevel::Low => false,
        }
    }
}

// Helper functions for clarity in gate logic
pub fn and(a: LogicLevel, b: LogicLevel) -> LogicLevel {
    match (a, b) {
        (LogicLevel::High, LogicLevel::High) => LogicLevel::High,
        _ => LogicLevel::Low,
    }
}

pub fn or(a: LogicLevel, b: LogicLevel) -> LogicLevel {
    match (a, b) {
        (LogicLevel::Low, LogicLevel::Low) => LogicLevel::Low,
        _ => LogicLevel::High,
    }
}

pub fn nand(a: LogicLevel, b: LogicLevel) -> LogicLevel {
    !and(a, b)
}

pub fn nor(a: LogicLevel, b: LogicLevel) -> LogicLevel {
    !or(a, b)
}

pub fn xor(a: LogicLevel, b: LogicLevel) -> LogicLevel {
    match (a, b) {
        (LogicLevel::Low, LogicLevel::High) | (LogicLevel::High, LogicLevel::Low) => {
            LogicLevel::High
        }
        _ => LogicLevel::Low,
    }
}