1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use num::basic::unsigneds::PrimitiveUnsigned;
use num::conversion::traits::{CheckedFrom, PowerOf2Digits, WrappingFrom};

fn to_power_of_2_digits_asc<T: PrimitiveUnsigned, U: PrimitiveUnsigned + WrappingFrom<T>>(
    x: &T,
    log_base: u64,
) -> Vec<U> {
    assert_ne!(log_base, 0);
    if log_base > U::WIDTH {
        panic!(
            "type {:?} is too small for a digit of width {}",
            U::NAME,
            log_base
        );
    }
    let mut digits = Vec::new();
    if *x == T::ZERO {
    } else if x.significant_bits() <= log_base {
        digits.push(U::wrapping_from(*x));
    } else {
        let mut x = *x;
        let mask = U::low_mask(log_base);
        while x != T::ZERO {
            digits.push(U::wrapping_from(x) & mask);
            x >>= log_base;
        }
    }
    digits
}

fn to_power_of_2_digits_desc<T: PrimitiveUnsigned, U: PrimitiveUnsigned + WrappingFrom<T>>(
    x: &T,
    log_base: u64,
) -> Vec<U> {
    let mut digits = to_power_of_2_digits_asc(x, log_base);
    digits.reverse();
    digits
}

fn from_power_of_2_digits_asc<
    T: CheckedFrom<U> + PrimitiveUnsigned + WrappingFrom<U>,
    U: PrimitiveUnsigned,
    I: Iterator<Item = U>,
>(
    log_base: u64,
    digits: I,
) -> Option<T> {
    assert_ne!(log_base, 0);
    if log_base > U::WIDTH {
        panic!(
            "type {:?} is too small for a digit of width {}",
            U::NAME,
            log_base
        );
    }
    let mut n = T::ZERO;
    let mut shift = 0;
    for digit in digits {
        if digit.significant_bits() > log_base {
            return None;
        }
        n |= T::checked_from(digit).and_then(|d| d.arithmetic_checked_shl(shift))?;
        shift += log_base;
    }
    Some(n)
}

fn from_power_of_2_digits_desc<
    T: PrimitiveUnsigned + WrappingFrom<U>,
    U: PrimitiveUnsigned,
    I: Iterator<Item = U>,
>(
    log_base: u64,
    digits: I,
) -> Option<T> {
    assert_ne!(log_base, 0);
    if log_base > U::WIDTH {
        panic!(
            "type {:?} is too small for a digit of width {}",
            U::NAME,
            log_base
        );
    }
    let mut n = T::ZERO;
    for digit in digits {
        if digit.significant_bits() > log_base {
            return None;
        }
        let shifted = n.arithmetic_checked_shl(log_base)?;
        n = shifted | T::wrapping_from(digit);
    }
    Some(n)
}

macro_rules! impl_power_of_2_digits {
    ($t:ident) => {
        macro_rules! impl_power_of_2_digits_inner {
            ($u:ident) => {
                impl PowerOf2Digits<$u> for $t {
                    /// Returns a [`Vec`] containing the base-$2^k$ digits of a number in ascending
                    /// order (least- to most-significant).
                    ///
                    /// The base-2 logarithm of the base is specified. `log_base` must be no larger
                    /// than the width of the digit type. If `self` is 0, the [`Vec`] is empty;
                    /// otherwise, it ends with a nonzero digit.
                    ///
                    /// $f(x, k) = (d_i)_ {i=0}^{n-1}$, where $0 \leq d_i < 2^k$ for all $i$,
                    /// $n=0$ or $d_{n-1} \neq 0$, and
                    ///
                    /// $$
                    /// \sum_{i=0}^{n-1}2^{ki}d_i = x.
                    /// $$
                    ///
                    /// # Worst-case complexity
                    /// $T(n) = O(n)$
                    ///
                    /// $M(n) = O(n)$
                    ///
                    /// where $T$ is time, $M$ is additional memory, and $n$ is
                    /// `self.significant_bits()`.
                    ///
                    /// # Panics
                    /// Panics if `log_base` is greater than the width of the output type, or if
                    /// `log_base` is zero.
                    ///
                    /// # Examples
                    /// See [here](super::power_of_2_digits#to_power_of_2_digits_asc).
                    #[inline]
                    fn to_power_of_2_digits_asc(&self, log_base: u64) -> Vec<$u> {
                        to_power_of_2_digits_asc(self, log_base)
                    }

                    /// Returns a [`Vec`] containing the base-$2^k$ digits of a number in
                    /// descending order (most- to least-significant).
                    ///
                    /// The base-2 logarithm of the base is specified. `log_base` must be no larger
                    /// than the width of the digit type. If `self` is 0, the [`Vec`] is empty;
                    /// otherwise, it begins with a nonzero digit.
                    ///
                    /// $f(x, k) = (d_i)_ {i=0}^{n-1}$, where $0 \leq d_i < 2^k$ for all $i$,
                    /// $n=0$ or $d_0 \neq 0$, and
                    ///
                    /// $$
                    /// \sum_{i=0}^{n-1}2^{k (n-i-1)}d_i = x.
                    /// $$
                    ///
                    /// # Worst-case complexity
                    /// $T(n) = O(n)$
                    ///
                    /// $M(n) = O(n)$
                    ///
                    /// where $T$ is time, $M$ is additional memory, and $n$ is
                    /// `self.significant_bits()`.
                    ///
                    /// # Panics
                    /// Panics if `log_base` is greater than the width of the output type, or if
                    /// `log_base` is zero.
                    ///
                    /// # Examples
                    /// See [here](super::power_of_2_digits#to_power_of_2_digits_desc).
                    #[inline]
                    fn to_power_of_2_digits_desc(&self, log_base: u64) -> Vec<$u> {
                        to_power_of_2_digits_desc(self, log_base)
                    }

                    /// Converts an iterator of base-$2^k$ digits into a value.
                    ///
                    /// The base-2 logarithm of the base is specified. The input digits are in
                    /// ascending order (least- to most-significant). `log_base` must be no larger
                    /// than the width of the digit type. The function returns `None` if the input
                    /// represents a number that can't fit in the output type.
                    ///
                    /// $$
                    /// f((d_i)_ {i=0}^{n-1}, k) = \sum_{i=0}^{n-1}2^{ki}d_i.
                    /// $$
                    ///
                    /// # Worst-case complexity
                    /// $T(n) = O(n)$
                    ///
                    /// $M(n) = O(1)$
                    ///
                    /// where $T$ is time, $M$ is additional memory, and $n$ is `digits.count()`.
                    ///
                    /// # Panics
                    /// Panics if `log_base` is greater than the width of the digit type, or if
                    /// `log_base` is zero.
                    ///
                    /// # Examples
                    /// See [here](super::power_of_2_digits#from_power_of_2_digits_asc).
                    #[inline]
                    fn from_power_of_2_digits_asc<I: Iterator<Item = $u>>(
                        log_base: u64,
                        digits: I,
                    ) -> Option<$t> {
                        from_power_of_2_digits_asc(log_base, digits)
                    }

                    /// Converts an iterator of base-$2^k$ digits into a value.
                    ///
                    /// The base-2 logarithm of the base is specified. The input digits are in
                    /// descending order (most- to least-significant). `log_base` must be no larger
                    /// than the width of the digit type. The function returns `None` if the input
                    /// represents a number that can't fit in the output type.
                    ///
                    /// $$
                    /// f((d_i)_ {i=0}^{n-1}, k) = \sum_{i=0}^{n-1}2^{k (n-i-1)}d_i.
                    /// $$
                    ///
                    /// # Worst-case complexity
                    /// $T(n) = O(n)$
                    ///
                    /// $M(n) = O(1)$
                    ///
                    /// where $T$ is time, $M$ is additional memory, and $n$ is `digits.count()`.
                    ///
                    /// # Panics
                    /// Panics if `log_base` is greater than the width of the digit type, or if
                    /// `log_base` is zero.
                    ///
                    /// # Examples
                    /// See [here](super::power_of_2_digits#from_power_of_2_digits_desc).
                    fn from_power_of_2_digits_desc<I: Iterator<Item = $u>>(
                        log_base: u64,
                        digits: I,
                    ) -> Option<$t> {
                        from_power_of_2_digits_desc(log_base, digits)
                    }
                }
            };
        }
        apply_to_unsigneds!(impl_power_of_2_digits_inner);
    };
}
apply_to_unsigneds!(impl_power_of_2_digits);