debot_utils/
lib.rs

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
pub mod datetime_utils;
pub mod kws_decrypt;
pub mod limitied_size_map;
pub mod math;

pub use datetime_utils::*;
pub use kws_decrypt::decrypt_data_with_kms;
pub use limitied_size_map::DynamicLimitedSizeMap;
pub use limitied_size_map::LimitedSizeMap;
pub use limitied_size_map::ValuePair;
pub use math::*;
use serde::Serializer;
use std::num::ParseFloatError;
use std::str::FromStr;

use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use rust_decimal::Error as DecimalParseError;

#[derive(Debug)]
pub enum ParseDecimalError {
    FloatError(ParseFloatError),
    DecimalError(DecimalParseError),
}

impl From<ParseFloatError> for ParseDecimalError {
    fn from(err: ParseFloatError) -> Self {
        ParseDecimalError::FloatError(err)
    }
}

impl From<DecimalParseError> for ParseDecimalError {
    fn from(err: DecimalParseError) -> Self {
        ParseDecimalError::DecimalError(err)
    }
}

pub fn parse_to_decimal(input: &str) -> Result<Decimal, ParseDecimalError> {
    Decimal::from_str(input).map_err(Into::into)
}

pub fn parse_to_f64(input: &str) -> Result<f64, ParseFloatError> {
    input.parse::<f64>()
}

pub fn serialize_decimal_as_f64<S>(decimal: &Decimal, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let f64_value = decimal.to_f64().ok_or(serde::ser::Error::custom(
        "Decimal to f64 conversion failed",
    ))?;
    serializer.serialize_f64(f64_value)
}

pub trait HasId {
    fn id(&self) -> Option<u32>;
}