【问题标题】:Convert a vector of u8 bytes into a rust_decimal将 u8 字节的向量转换为 rust_decimal
【发布时间】:2023-02-05 03:59:17
【问题描述】:

我正在从另一种语言加载数据。数字可以非常大,它们被序列化为 u8 的字节数组。

这些作为 u8s 的 vec 加载到 rust 中:

vec![1, 0, 0]

这表示 100。我还有一个 u32 来表示刻度。

我正在尝试将其加载到 rust_decimal 中,但卡住了。

measure_value.value -> u8 的 vec measure_value.scale -> u32

let r_dec = rust_Decimal::????

【问题讨论】:

    标签: rust decimal


    【解决方案1】:

    这是我目前的实现,但感觉不够优雅!

    
    pub fn proto_to_decimal(input: &DecimalValueProto) -> Result<Decimal, String> {
        let mut num = 0;
        let mut power: i32 = (input.value.len() - 1)
            .try_into()
            .map_err(|_| "Failed to convert proto to decimal")?; //casting down from usize to i32 is failable
    
        let mut expansion: i128;
    
        for digit in input.value.iter() {
            if power == 0 {
                expansion = *digit as i128;
            } else {
                expansion = (*digit as i128) * 10_i128.pow(power as u32) as i128;
            }
            num += expansion;
            power -= 1;
        }
        Ok(Decimal::from_i128_with_scale(num as i128, input.scale))
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 2013-10-05
      • 2019-09-09
      • 1970-01-01
      • 2013-12-11
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多