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