Skip to main content

deep_causality_num/num/
num_ops.rs

1/*
2 * SPDX-License-Identifier: MIT
3 * Copyright (c) 2023 - 2026. The DeepCausality Authors and Contributors. All Rights Reserved.
4 */
5use crate::Num;
6use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign};
7
8/// Generic trait for types implementing basic numeric operations
9///
10/// This is automatically implemented for types which implement the operators.
11pub trait NumOps<Rhs = Self, Output = Self>:
12    Add<Rhs, Output = Output>
13    + Sub<Rhs, Output = Output>
14    + Mul<Rhs, Output = Output>
15    + Div<Rhs, Output = Output>
16    + Rem<Rhs, Output = Output>
17{
18}
19
20impl<T, Rhs, Output> NumOps<Rhs, Output> for T where
21    T: Add<Rhs, Output = Output>
22        + Sub<Rhs, Output = Output>
23        + Mul<Rhs, Output = Output>
24        + Div<Rhs, Output = Output>
25        + Rem<Rhs, Output = Output>
26{
27}
28
29/// The trait for `Num` types which also implement numeric operations taking
30/// the second operand by reference.
31///
32/// This is automatically implemented for types which implement the operators.
33pub trait NumRef: Num + for<'r> NumOps<&'r Self> {}
34impl<T> NumRef for T where T: Num + for<'r> NumOps<&'r T> {}
35
36/// The trait for `Num` references which implement numeric operations, taking the
37/// second operand either by value or by reference.
38///
39/// This is automatically implemented for all types which implement the operators. It covers
40/// every type implementing the operations though, regardless of it being a reference or
41/// related to `Num`.
42pub trait RefNum<Base>: NumOps<Base, Base> + for<'r> NumOps<&'r Base, Base> {}
43impl<T, Base> RefNum<Base> for T where T: NumOps<Base, Base> + for<'r> NumOps<&'r Base, Base> {}
44
45/// Generic trait for types implementing numeric assignment operators (like `+=`).
46///
47/// This is automatically implemented for types which implement the operators.
48pub trait NumAssignOps<Rhs = Self>:
49    AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs> + RemAssign<Rhs>
50{
51}
52
53impl<T, Rhs> NumAssignOps<Rhs> for T where
54    T: AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs> + RemAssign<Rhs>
55{
56}
57
58/// The trait for `Num` types which also implement assignment operators.
59///
60/// This is automatically implemented for types which implement the operators.
61pub trait NumAssign: Num + NumAssignOps {}
62impl<T> NumAssign for T where T: Num + NumAssignOps {}
63
64/// The trait for `NumAssign` types which also implement assignment operations
65/// taking the second operand by reference.
66///
67/// This is automatically implemented for types which implement the operators.
68pub trait NumAssignRef: NumAssign + for<'r> NumAssignOps<&'r Self> {}
69impl<T> NumAssignRef for T where T: NumAssign + for<'r> NumAssignOps<&'r T> {}