sashite-sin 1.1.0

Style Identifier Notation (SIN): a compact, ASCII-only, no_std token encoding a player's side and style in abstract strategy board games.
Documentation
//! Player-style abbreviation: a single ASCII letter, side-agnostic.

use crate::error::ParseError;
use crate::side::Side;

/// The single-letter abbreviation of a player style.
///
/// A `Letter` is the *identity* part of a SIN token, independent of side. Per
/// the specification the abbreviation is case-insensitive (`C` and `c` denote
/// the same style), so a `Letter` is always stored uppercase; the case of the
/// original token is carried separately by [`Side`].
///
/// # Invariant
///
/// The wrapped byte is always an uppercase ASCII letter (`b'A'..=b'Z'`). The
/// field is private and every constructor enforces the range, so the invariant
/// cannot be violated from outside the crate.
///
/// It is what makes the crate's arithmetic total. Three places shift a byte by
/// 32 to change case, and each would panic on overflow in a debug build; the
/// invariant keeps every one of them inside `65..=122`, far from either end of
/// a `u8`. Nothing in the type system enforces that, so the tests sweep every
/// public constructor to prove it.
///
/// Ordering is alphabetical (`A < B < … < Z`).
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Letter(u8);

impl Letter {
    /// Every abbreviation, in alphabetical order (`A` through `Z`).
    pub const ALL: [Self; 26] = [
        Self(b'A'),
        Self(b'B'),
        Self(b'C'),
        Self(b'D'),
        Self(b'E'),
        Self(b'F'),
        Self(b'G'),
        Self(b'H'),
        Self(b'I'),
        Self(b'J'),
        Self(b'K'),
        Self(b'L'),
        Self(b'M'),
        Self(b'N'),
        Self(b'O'),
        Self(b'P'),
        Self(b'Q'),
        Self(b'R'),
        Self(b'S'),
        Self(b'T'),
        Self(b'U'),
        Self(b'V'),
        Self(b'W'),
        Self(b'X'),
        Self(b'Y'),
        Self(b'Z'),
    ];

    /// Decodes a raw ASCII byte into a [`Letter`] and the [`Side`] its case
    /// implies.
    ///
    /// Returns `None` for any byte that is not an ASCII letter. This is the
    /// lossless decoder used by the token parser: the byte it was given can
    /// always be rebuilt from the pair it returns.
    ///
    /// Note this takes a *byte*. Reaching for it with `c as u8` on a `char`
    /// silently truncates to the low eight bits and can turn a non-ASCII
    /// character into a letter that was never there — `'Ł'` (`U+0141`) becomes
    /// `0x41`, the byte `b'A'`. Use [`Letter::try_from_char`] for a `char`; it
    /// matches on the character before casting and so cannot be fooled.
    ///
    /// # Examples
    ///
    /// ```
    /// use sashite_sin::{Letter, Side};
    ///
    /// let (letter, side) = Letter::from_ascii(b'c').unwrap();
    /// assert_eq!(letter.as_char(), 'C');
    /// assert_eq!(side, Side::Second);
    ///
    /// assert!(Letter::from_ascii(b'1').is_none());
    ///
    /// // The `char` door is the safe one for non-ASCII input.
    /// assert!(Letter::try_from_char('\u{0141}').is_err());
    /// ```
    #[must_use]
    pub const fn from_ascii(byte: u8) -> Option<(Self, Side)> {
        match byte {
            b'A'..=b'Z' => Some((Self(byte), Side::First)),
            // `byte` is at least `b'a'` (97) in this arm, so the subtraction
            // cannot underflow and lands back inside `b'A'..=b'Z'`.
            b'a'..=b'z' => Some((Self(byte - 32), Side::Second)),
            _ => None,
        }
    }

    /// Builds a [`Letter`] from a `char`, folding case.
    ///
    /// Both `'C'` and `'c'` yield the same `Letter`; the case (which encodes
    /// side) is not retained.
    ///
    /// Case folding here is ASCII-only and deliberately so: the range patterns
    /// compare Unicode scalar values, so characters that *case-fold* to an
    /// ASCII letter — `'ſ'` (`U+017F`), `'K'` (`U+212A`) — are still rejected.
    /// Only the 52 characters the grammar names are abbreviations.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidLetter`] if `c` is not an ASCII letter.
    /// This is the only variant this function can produce: a `char` has no
    /// length to be wrong about.
    ///
    /// # Examples
    ///
    /// ```
    /// use sashite_sin::Letter;
    ///
    /// assert_eq!(Letter::try_from_char('j').unwrap().as_char(), 'J');
    /// assert!(Letter::try_from_char('+').is_err());
    /// assert!(Letter::try_from_char('\u{017F}').is_err()); // folds to 's'
    /// ```
    #[allow(clippy::cast_possible_truncation)] // guarded: `c` is ASCII here
    pub const fn try_from_char(c: char) -> Result<Self, ParseError> {
        match c {
            'A'..='Z' => Ok(Self(c as u8)),
            // The arm bounds `c` at `'a'` (97), so the cast is exact and the
            // subtraction cannot underflow.
            'a'..='z' => Ok(Self(c as u8 - 32)),
            _ => Err(ParseError::InvalidLetter),
        }
    }

    /// Returns the abbreviation as an uppercase `char`.
    #[must_use]
    pub const fn as_char(self) -> char {
        self.0 as char
    }

    /// Returns the abbreviation as its raw uppercase ASCII byte.
    #[must_use]
    pub const fn as_ascii(self) -> u8 {
        self.0
    }

    /// Returns the ASCII byte as it appears in a token for the given side:
    /// uppercase for [`Side::First`], lowercase for [`Side::Second`].
    ///
    /// The type invariant bounds the byte at `b'Z'` (90), so adding 32 reaches
    /// at most `b'z'` (122) and cannot overflow a `u8` — which matters because
    /// that overflow would be a panic in a debug build.
    #[must_use]
    pub(crate) const fn to_ascii(self, side: Side) -> u8 {
        match side {
            Side::First => self.0,
            Side::Second => self.0 + 32,
        }
    }
}

impl TryFrom<char> for Letter {
    type Error = ParseError;

    fn try_from(c: char) -> Result<Self, Self::Error> {
        Self::try_from_char(c)
    }
}

impl core::fmt::Debug for Letter {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Letter({:?})", self.as_char())
    }
}