vildrose_core/word/mod.rs
1//! Fixed-width balanced ternary word types.
2//!
3//! Trit storage is little-endian: trit zero is the least-significant trit.
4//!
5//! # Common types
6//!
7//! - [`Tribble`] — 3 trits, range -13 through +13
8//! - [`Tryte`] / [`Word9`] — 9 trits, range -9,841 through +9,841
9//! - [`Word27`] — 27 trits
10//! - [`Word54`] — 54 trits, used for extended-width arithmetic
11//!
12//! [`Word`] is generic over its trit count, allowing ISA crates to use
13//! widths such as `Word<24>` and `Word<32>` without adding more core types.
14
15mod arithmetic;
16mod basic;
17mod conversion;
18mod cross_width;
19mod logic;
20
21use crate::trit::Trit;
22
23/// A fixed-width balanced ternary integer containing `N` trits.
24///
25/// Trits are stored in little-endian order: index zero is the
26/// least-significant trit.
27// Add hash in the future, requires it to be added to trit
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub struct Word<const N: usize>(pub(crate) [Trit; N]);
30
31/// A 3-trit balanced ternary integer.
32///
33/// Range: -13 through +13.
34pub type Tribble = Word<3>;
35
36/// A 9-trit balanced ternary integer.
37///
38/// Range: -9,841 through +9,841.
39pub type Tryte = Word<9>;
40
41/// Alias for [`Tryte`].
42pub type Word9 = Tryte;
43
44/// A 27-trit balanced ternary integer.
45pub type Word27 = Word<27>;
46
47/// A 54-trit balanced ternary integer.
48pub type Word54 = Word<54>;
49
50/// Errors returned by fixed-width ternary-word operations.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum WordError {
53 /// The supplied value cannot be represented by this word width.
54 OutOfRange,
55}
56
57impl core::fmt::Display for WordError {
58 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
59 match self {
60 Self::OutOfRange => {
61 f.write_str("value is outside the representable balanced ternary range")
62 }
63 }
64 }
65}
66
67impl std::error::Error for WordError {}
68
69/// Checked division supporting potentially different operand widths.
70///
71/// Division returns `None` when the divisor is zero.
72pub trait CheckedDiv<Rhs = Self> {
73 /// The type produced by a successful division.
74 type Output;
75
76 /// Divides `self` by `rhs`, returning `None` when `rhs` is zero.
77 #[must_use]
78 fn checked_div(self, rhs: Rhs) -> Option<Self::Output>;
79}