newnum/lib.rs
1use std::ops::*;
2
3mod api;
4mod initialization;
5mod primitive;
6pub use api::*;
7pub use initialization::*;
8pub use primitive::*;
9
10pub use newnum_proc_macros::{num, num_approx};
11
12/// Derive macros for crate traits.
13pub mod derive {
14 pub use newnum_proc_macros::{
15 AHyper, ATrig, AbsDiff, Hyper, MinMax, Num, Root, Round, Sign, Trig, TruncRoot, TypeMax,
16 TypeMin, Whole,
17 };
18}
19
20#[allow(unused_imports)]
21use newnum_proc_macros::{internal_num, internal_num_approx};
22
23/// Trait for types that represent numbers.
24///
25/// This includes support for the common arithmetic and comparison operators:
26/// `+`, `-`, `*`, `/`, `%`, `=`, `<`, `>`, as well as traits for absolute
27/// difference, min/max, rounding, and sign detection.
28///
29/// This trait can be implemented by non-primitive types, such as unit-based
30/// numbers (`Meters`, `Seconds`, etc). For a trait limited to primitive types,
31/// see [`Prim`].
32///
33/// Note: For unit-aware types, the return types of operations like
34/// multiplication, division, and square root must still be `Self`.
35/// This is mathematically incorrect (e.g. `Meters * Meters` should result in
36/// `MetersSquared`, and `Sqrt<MetersSquared>` should result in `Meters`),
37/// but Rust's type system is not expressive enough to encode such behavior.
38///
39/// If you want to initialize a `Num` type with a specific numeric literal, use the [`num!`] macro.
40///
41/// Note that implementors of `Num` are not required to support common values like `0`, `1`, etc.
42/// For example, a type might only represent values in the range `100..=356`. In that case,
43/// trying to construct `0` or `1` using the [`num!`] macro would fail at compile time.
44/// This allows `Num` to be used for restricted or domain-specific number types with full
45/// compile-time validation of literal values.
46pub trait Num:
47 FromIntLiteral
48 + AbsDiff<Output = Self>
49 + MinMax
50 + TruncRoot
51 + Round
52 + Sign<BoolMapped = bool>
53 + PartialEq
54 + PartialOrd
55 + Add<Output = Self>
56 + Sub<Output = Self>
57 + Mul<Output = Self>
58 + Div<Output = Self>
59 + Rem<Output = Self>
60 + AddAssign
61 + SubAssign
62 + MulAssign
63 + DivAssign
64 + RemAssign
65{
66}
67
68impl Num for u8 {}
69impl Num for u16 {}
70impl Num for u32 {}
71impl Num for u64 {}
72impl Num for u128 {}
73impl Num for usize {}
74
75impl Num for i8 {}
76impl Num for i16 {}
77impl Num for i32 {}
78impl Num for i64 {}
79impl Num for i128 {}
80impl Num for isize {}
81
82impl Num for f32 {}
83impl Num for f64 {}