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
use crate::FPDecimal;
use cosmwasm_std::StdError;
use std::{fmt::Display, str::FromStr};

pub enum RangeEnds {
    BothInclusive,
    MinInclusive,
    MaxInclusive,
    Exclusive,
}

impl Default for RangeEnds {
    fn default() -> Self {
        RangeEnds::BothInclusive
    }
}

pub fn parse_dec(vs: &str, min: Option<&FPDecimal>, max: Option<&FPDecimal>, range_ends: RangeEnds) -> Result<FPDecimal, StdError> {
    let v = FPDecimal::from_str(vs)?;
    ensure_band(&v, min, max, range_ends)?;
    Ok(v)
}

pub fn parse_int<T: FromStr + Ord + Display>(vs: &str, min: Option<&T>, max: Option<&T>, range_ends: RangeEnds) -> Result<T, StdError>
where
    <T as FromStr>::Err: ToString,
{
    match vs.parse::<T>() {
        Ok(v) => {
            ensure_band(&v, min, max, range_ends)?;
            Ok(v)
        }
        Err(e) => Err(StdError::generic_err(e.to_string())),
    }
}

pub fn ensure_band<T: Ord + Display>(v: &T, min: Option<&T>, max: Option<&T>, range_ends: RangeEnds) -> Result<(), StdError> {
    if let Some(minv) = min {
        match range_ends {
            RangeEnds::BothInclusive | RangeEnds::MinInclusive => {
                if v < minv {
                    return Err(StdError::generic_err(format!("value {} must be >= {}", v, minv)));
                }
            }
            RangeEnds::MaxInclusive | RangeEnds::Exclusive => {
                if v <= minv {
                    return Err(StdError::generic_err(format!("value {} must be > {}", v, minv)));
                }
            }
        }
    }
    if let Some(maxv) = max {
        match range_ends {
            RangeEnds::BothInclusive | RangeEnds::MaxInclusive => {
                if v > maxv {
                    return Err(StdError::generic_err(format!("value {} must be <= {}", v, maxv)));
                }
            }
            RangeEnds::MinInclusive | RangeEnds::Exclusive => {
                if v >= maxv {
                    return Err(StdError::generic_err(format!("value {} must be < {}", v, maxv)));
                }
            }
        }
    }
    Ok(())
}