简体   繁体   中英

Rust custom deserialize to BigInt

I'm new in rust, and have a hard time with deserialize and i am not fully understand how it is work. I trying to warp BigInt and make my own serialize/deserialize.

i want is to serialize BigNum to string with the fully number and desrialzie back to bigNum

this is my code:

use num_bigint::BigInt;
use serde::{Deserialize, Deserializer, Serialize};
use std::ops::Deref;

#[derive(Debug)]
struct BigNum(BigInt);

impl Deref for BigNum {
    type Target = BigInt;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Serialize for BigNum {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.deref().to_string())
    }
}

impl<'de> Deserialize<'de> for BigNum {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let num = String::deserialize(deserializer)?
            .parse::<BigInt>()
            .unwrap();
        Ok(BigNum(num))
    }
}

#[cfg(test)]
#[test]
fn test_bignum() {
    let element = "1333333333333333333333333326766666666666666663124";
    let tuple: BigNum = serde_json::from_str(element).unwrap();
}

i don't understand why when i running the test i getting this error:

Error("invalid type: floating point `1333333333333333300000000000000000000000000000000`, expected a string", line: 1, column: 49)'

Your serde implementations deal with strings, which is correct because JSON floats don't have the precision necessary to exactly store such a large number. However, the input you have in element is a JSON numeric literal, not a JSON string. You need to alter this input so that it's a JSON string:

let element = "\"1333333333333333333333333326766666666666666663124\"";

With this change, the test passes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM