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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! This crate extends how `num_rational::Ratio<T>` can be converted
//! from a string specifically by allowing decimal notation with the
//! ability to constrain the minimum and maximum number of fractional
//! digits allowed.
#![no_std]
#![no_implicit_prelude]
#![deny(
    unsafe_code,
    unused,
    warnings,
    clippy::all,
    clippy::cargo,
    clippy::nursery,
    clippy::pedantic
)]
#![allow(
    clippy::implicit_return,
    clippy::missing_trait_methods,
    clippy::question_mark_used,
    clippy::unseparated_literal_suffix
)]
extern crate alloc;
#[allow(unused_extern_crates)]
extern crate core;
#[allow(unused_extern_crates)]
extern crate num_integer;
#[allow(unused_extern_crates)]
extern crate num_rational;
#[allow(unused_extern_crates)]
extern crate num_traits;
#[allow(unused_extern_crates)]
extern crate serde;
use crate::FromDecStrErr::{IntParseErr, TooFewFractionalDigits, TooManyFractionalDigits};
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::clone::Clone;
use core::cmp::PartialOrd;
use core::convert::From;
use core::fmt::{self, Debug, Display, Formatter};
use core::marker::PhantomData;
use core::ops::Mul;
use core::option::Option;
use core::result::Result::{self, Err, Ok};
use core::str::FromStr;
use core::{unreachable, write};
use num_integer::Integer;
use num_rational::Ratio;
use num_traits::Pow;
/// An ordered pair whose first value is <= to the second.
pub struct MinMax<T> {
    /// The first value which is <= the second.
    min: T,
    /// The second value which is >= the first.
    max: T,
}
impl<T> MinMax<T> {
    /// Returns a reference to the first value.
    #[inline]
    pub const fn min(&self) -> &T {
        &self.min
    }
    /// Returns a reference to the second value.
    #[inline]
    pub const fn max(&self) -> &T {
        &self.max
    }
}
impl<T> MinMax<T>
where
    T: PartialOrd<T>,
{
    /// Returns `Some(T)` iff `min` `<=` `max`.
    #[inline]
    pub fn new(min: T, max: T) -> Option<Self> {
        (min <= max).then_some(Self { min, max })
    }
    /// Returns `MinMax` without verifying `min` `<=` `max`.

    /// # Safety
    ///
    /// `min` `<=` `max`.
    #[allow(unsafe_code)]
    #[inline]
    pub const unsafe fn new_unchecked(min: T, max: T) -> Self {
        Self { min, max }
    }
}
/// The error returned when parsing a string in decimal notation into
/// a `num_rational::Ratio<T>`.
#[allow(clippy::exhaustive_enums)]
pub enum FromDecStrErr<T> {
    /// Contains the error returned when parsing a string into a `T`.
    IntParseErr(T),
    /// The variant returned when a decimal string has fewer rational
    /// digits than allowed.
    TooFewFractionalDigits(usize),
    /// The variant returned when a decimal string has more rational
    /// digits than allowed.
    TooManyFractionalDigits(usize),
}
impl<T> Display for FromDecStrErr<T>
where
    T: Display,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match *self {
            IntParseErr(ref x) => x.fmt(f),
            TooFewFractionalDigits(ref x) => write!(
                f,
                "There were only {x} fractional digits which is fewer than the minimum required."
            ),
            TooManyFractionalDigits(ref x) => write!(
                f,
                "There were {x} fractional digits which is more than the maximum required."
            ),
        }
    }
}
impl<T> Debug for FromDecStrErr<T>
where
    T: Display,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        <Self as Display>::fmt(self, f)
    }
}
impl<T> From<T> for FromDecStrErr<T> {
    #[inline]
    fn from(x: T) -> Self {
        IntParseErr(x)
    }
}
/// Converts a string in decimal notation into a `Ratio<T>`.

/// # Errors
///
/// Will return `FromDecStrErr` iff `val` is not a valid rational
/// number in decimal notation with number of fractional digits
/// inclusively between `frac_digit_count.min()` and
/// `frac_digit_count.max()`.
#[allow(
    clippy::arithmetic_side_effects,
    clippy::indexing_slicing,
    clippy::single_char_lifetime_names,
    clippy::string_slice
)]
#[inline]
pub fn try_from_dec_str<T>(
    val: &str,
    frac_digit_count: &MinMax<usize>,
) -> Result<Ratio<T>, FromDecStrErr<<T as FromStr>::Err>>
where
    T: Clone
        + From<u8>
        + FromStr
        + Integer
        + for<'a> Mul<&'a T, Output = T>
        + Pow<usize, Output = T>,
{
    val.split_once('.').map_or_else(
        || {
            if *frac_digit_count.min() == 0 {
                Ok(Ratio::from(T::from_str(val)?))
            } else {
                Err(TooFewFractionalDigits(val.len()))
            }
        },
        |(l, r)| {
            if r.len() >= *frac_digit_count.min() {
                if r.len() <= *frac_digit_count.max() {
                    let mult = T::from(10).pow(r.len());
                    let numer = T::from_str(l)? * &mult;
                    let addend = T::from_str(r)?;
                    let zero = T::from(0);
                    Ok(Ratio::new(
                        if numer < zero || (numer == zero && &l[..1] == "-") {
                            numer - addend
                        } else {
                            numer + addend
                        },
                        mult,
                    ))
                } else {
                    Err(TooManyFractionalDigits(r.len()))
                }
            } else {
                Err(TooFewFractionalDigits(r.len()))
            }
        },
    )
}
/// The error returned when parsing a string in decimal or
/// rational notation into a `num_rational::Ratio<T>`.
#[allow(clippy::exhaustive_enums)]
pub enum FromStrErr<T> {
    /// Contains the error when a string fails to parse into a `T`.
    IntParseErr(T),
    /// The variant that is returned when a string in rational
    /// notation has a denominator that is zero.
    DenominatorIsZero,
}
impl<T> Display for FromStrErr<T>
where
    T: Display,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match *self {
            Self::IntParseErr(ref x) => x.fmt(f),
            Self::DenominatorIsZero => f.write_str("denominator is zero"),
        }
    }
}
impl<T> Debug for FromStrErr<T>
where
    T: Display,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        <Self as Display>::fmt(self, f)
    }
}
impl<T> From<T> for FromStrErr<T> {
    #[inline]
    fn from(x: T) -> Self {
        Self::IntParseErr(x)
    }
}
/// Converts a string in rational or decimal notation into a `Ratio<T>`.

/// # Errors
///
/// Will return `FromStrErr` iff `val` is not a rational number in
/// rational or decimal notation.
#[allow(
    unsafe_code,
    clippy::arithmetic_side_effects,
    clippy::single_char_lifetime_names,
    clippy::unreachable
)]
#[inline]
pub fn try_from_str<T>(val: &str) -> Result<Ratio<T>, FromStrErr<<T as FromStr>::Err>>
where
    T: Clone
        + From<u8>
        + FromStr
        + Integer
        + for<'a> Mul<&'a T, Output = T>
        + Pow<usize, Output = T>,
{
    /// Used as the closure that transforms a `FromDecStrErr` into a `FromStrErr`.
    #[inline]
    fn dec_err<S>(err: FromDecStrErr<<S as FromStr>::Err>) -> FromStrErr<<S as FromStr>::Err>
    where
        S: FromStr,
    {
        match err {
            IntParseErr(x) => FromStrErr::IntParseErr(x),
            TooFewFractionalDigits(_) | TooManyFractionalDigits(_) => unreachable!("There is a bug in rational::try_from_dec_str. 0 and usize::MAX were passed as the minimum and maximum number of fractional digits allowed respectively, but it still errored due to too few or too many fractional digits"),
        }
    }
    /// Used as the closure that attempts to transform a `String` split from a `/`
    /// into a `Ratio<S>`.
    #[inline]
    fn frac_split<S>(split: (&str, &str)) -> Result<Ratio<S>, FromStrErr<<S as FromStr>::Err>>
    where
        S: Clone + From<u8> + FromStr + Integer + for<'a> Mul<&'a S, Output = S>,
    {
        let denom = S::from_str(split.1)?;
        let zero = S::from(0);
        if denom == zero {
            Err(FromStrErr::DenominatorIsZero)
        } else {
            split.0.split_once(' ').map_or_else(
                || Ok(Ratio::new(S::from_str(split.0)?, denom.clone())),
                |(l2, r2)| {
                    let numer = S::from_str(l2)? * &denom;
                    let addend = S::from_str(r2)?;
                    Ok(Ratio::new(
                        if numer < zero {
                            numer - addend
                        } else {
                            numer + addend
                        },
                        denom.clone(),
                    ))
                },
            )
        }
    }
    val.split_once('/').map_or_else(
        || {
            // SAFETY:
            // usize::MAX >= 0
            try_from_dec_str(val, &unsafe { MinMax::new_unchecked(0, usize::MAX) })
                .map_err(dec_err::<T>)
        },
        frac_split,
    )
}
/// Returns a `String` representing `val` in decimal notation with
/// `frac_digit_count` fractional digits using normal rounding rules.
#[allow(
    unsafe_code,
    clippy::arithmetic_side_effects,
    clippy::as_conversions,
    clippy::cast_lossless,
    clippy::indexing_slicing,
    clippy::integer_arithmetic,
    clippy::string_slice
)]
#[inline]
pub fn to_dec_string<T>(val: &Ratio<T>, frac_digit_count: usize) -> String
where
    T: Clone + Display + From<u8> + Integer + Pow<usize, Output = T>,
{
    /// Returns 1 iff `start` is `"-"`; otherwise returns 0.
    /// This function is used as the closure passed to `map_or` when checking
    /// if the first "character" of the fraction string is a negative sign.
    #[inline]
    fn neg_sign(start: &str) -> usize {
        (start == "-") as usize
    }
    let mult = T::from(10).pow(frac_digit_count);
    let (int, frac) = (val * &mult).round().numer().div_rem(&mult);
    let int_str = int.to_string();
    let mut v = Vec::with_capacity(int_str.len() + frac_digit_count + 2);
    let zero = T::from(0);
    if int >= zero && frac < zero {
        v.push(b'-');
    }
    v.extend_from_slice(int.to_string().as_bytes());
    if frac_digit_count > 0 {
        v.push(b'.');
        let len = v.len();
        let frac_str = frac.to_string();
        let frac_val = &frac_str[frac_str.get(..1).map_or(0, neg_sign)..];
        while v.len() < len + (frac_digit_count - frac_val.len()) {
            v.push(b'0');
        }
        v.extend_from_slice(frac_val.as_bytes());
    }
    // SAFETY:
    // v contains precisely the UTF-8 code units returned from Strings
    // returned from the to_string function on the integer and fraction part of
    // the passed value plus optionally the single byte encodings of ".", "-", and "0".
    unsafe { String::from_utf8_unchecked(v) }
}
use serde::de::{self, Deserialize, Deserializer, Unexpected, Visitor};
/// Wrapper around a `num_rational::Ratio` that
/// deserializes a JSON string representing a rational number in
/// rational or decimal notation to a Ratio&lt;T&gt;.
#[allow(clippy::exhaustive_structs)]
pub struct Rational<T>(pub Ratio<T>);
#[allow(clippy::single_char_lifetime_names)]
impl<'de, T> Deserialize<'de> for Rational<T>
where
    T: Clone
        + From<u8>
        + FromStr
        + Integer
        + for<'a> Mul<&'a T, Output = T>
        + Pow<usize, Output = T>,
{
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        /// Visitor used to deserialize a JSON string into a Rational.
        struct RationalVisitor<T> {
            /// Does not own nor drop a `T`.
            _x: PhantomData<fn() -> T>,
        }
        #[allow(clippy::single_char_lifetime_names)]
        impl<'de, T> Visitor<'de> for RationalVisitor<T>
        where
            T: Clone
                + From<u8>
                + FromStr
                + Integer
                + for<'a> Mul<&'a T, Output = T>
                + Pow<usize, Output = T>,
        {
            type Value = Rational<T>;
            fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
                formatter.write_str("struct Rational")
            }
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                #[allow(clippy::unnecessary_wraps)]
                /// Used as the closure that maps a `Ratio<R>`into an `Ok(Rational<R>)`.
                #[inline]
                const fn to_rational<R, E2>(val: Ratio<R>) -> Result<Rational<R>, E2> {
                    Ok(Rational(val))
                }
                try_from_str(v).map_or_else(
                    |_| {
                        Err(E::invalid_value(
                            Unexpected::Str(v),
                            &"a rational number in fraction or decimal notation",
                        ))
                    },
                    to_rational,
                )
            }
        }
        deserializer.deserialize_str(RationalVisitor { _x: PhantomData })
    }
}
#[cfg(test)]
mod tests {
    #[allow(unused_extern_crates)]
    extern crate serde_json;
    use super::*;
    use alloc::format;
    use core::assert_eq;
    use core::num::ParseIntError;

    #[test]
    fn test_min_max() -> Result<(), String> {
        let mut m: MinMax<u32>;
        for i in 0..1000 {
            for j in 0..1000 {
                m = MinMax::new(i, i + j)
                    .ok_or_else(|| format!("Failed for {} and {}.", i, i + j))?;
                assert_eq!(*m.min(), i);
                assert_eq!(*m.max(), i + j);
            }
        }
        Ok(())
    }
    #[test]
    #[should_panic]
    fn test_min_max_err() {
        MinMax::new(f64::NAN, 0.0).unwrap();
    }
    #[test]
    fn test_dec_string() -> Result<(), String> {
        assert_eq!("0", &to_dec_string(&Ratio::<u32>::new(0, 1), 0));
        assert_eq!("-1.33", &to_dec_string(&Ratio::<i32>::new(-4, 3), 2));
        assert_eq!("-0.33", &to_dec_string(&Ratio::<i32>::new(-1, 3), 2));
        assert_eq!("5.000", &to_dec_string(&Ratio::<u32>::new(5, 1), 3));
        assert_eq!("0.66667", &to_dec_string(&Ratio::<u32>::new(2, 3), 5));
        Ok(())
    }
    #[test]
    fn test_from_str() -> Result<(), FromStrErr<ParseIntError>> {
        assert_eq!(try_from_str::<u32>("4")?, Ratio::new(4, 1));
        assert_eq!(try_from_str::<u32>("4/8")?, Ratio::new(1, 2));
        assert_eq!(try_from_str::<u32>("5 9/8")?, Ratio::new(49, 8));
        assert_eq!(try_from_str::<i32>("-2 7/6")?, Ratio::new(-19, 6));
        assert_eq!(try_from_str::<i32>("-5/6")?, Ratio::new(-5, 6));
        assert_eq!(try_from_str::<u32>("0.1249")?, Ratio::new(1249, 10000));
        assert_eq!(try_from_str::<i32>("-1.33")?, Ratio::new(-133, 100));
        assert_eq!(try_from_str::<i32>("-0.33")?, Ratio::new(-33, 100));
        assert_eq!(try_from_str::<u32>("0.0")?, Ratio::new(0, 1));
        try_from_str::<u32>("1/0").map_or_else(
            |e| match e {
                FromStrErr::DenominatorIsZero => (),
                _ => assert_eq!(false, true),
            },
            |_| assert_eq!(false, true),
        );
        Ok(())
    }
    #[test]
    fn test_serde() -> Result<(), serde_json::Error> {
        assert_eq!(
            Ratio::new(2u8, 3u8),
            serde_json::from_str::<Rational::<u8>>(r#""2/3""#)?.0
        );
        assert_eq!(
            Ratio::new(67u8, 100u8),
            serde_json::from_str::<Rational::<u8>>(r#""0.67""#)?.0
        );
        Ok(())
    }
}