devela/num/int/
gcd.rs

1// devela::num::gcd
2//
3//! (Extended) Greatest Common Divisor return type.
4//
5
6use ::core::fmt;
7
8#[doc = crate::TAG_RESULT!()]
9/// A return type for the calculated
10/// <abbr title="Greatest Common Divisor">GCD</abbr> and the Bézout coeficients.
11///
12/// The coefficients are the solutions to the equation $ \text{gcd}(a, b) = a*x + b*y $.
13#[must_use]
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
15pub struct GcdReturn<G, C> {
16    /// The greatest common divisor.
17    pub gcd: G,
18    /// The first Bézout's coefficient `x`.
19    pub x: C,
20    /// The second Bézout's coefficient `y`.
21    pub y: C,
22}
23
24impl<G, C> GcdReturn<G, C> {
25    /// Constructs a new `GcdReturn`.
26    pub const fn new(gcd: G, x: C, y: C) -> Self {
27        GcdReturn { gcd, x, y }
28    }
29
30    /// Returns the values as a tuple.
31    #[must_use]
32    pub fn as_tuple(self) -> (G, C, C) {
33        (self.gcd, self.x, self.y)
34    }
35}
36impl<G: Copy, C: Copy> GcdReturn<G, C> {
37    /// Returns the values as a tuple, in compile-time.
38    #[must_use]
39    pub const fn as_tuple_copy(self) -> (G, C, C) {
40        (self.gcd, self.x, self.y)
41    }
42}
43
44impl<T> GcdReturn<T, T> {
45    /// Returns the values as an array, if all are of the same type.
46    #[must_use]
47    pub fn as_array(self) -> [T; 3] {
48        [self.gcd, self.x, self.y]
49    }
50}
51impl<T: Copy> GcdReturn<T, T> {
52    /// Returns the values as an array, if all are of the same type.
53    #[must_use]
54    pub const fn as_array_copy(self) -> [T; 3] {
55        [self.gcd, self.x, self.y]
56    }
57}
58
59impl<G: fmt::Display, C: fmt::Display> fmt::Display for GcdReturn<G, C> {
60    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61        write!(f, "gcd: {}, x: {}, y: {}", self.gcd, self.x, self.y)
62    }
63}