Rust serde_json序列化程序,用于[u8; 32]

时间:2018-07-24 09:56:25

标签: rust serde

我想在[u8; 32]中用serde_json在Rust中获得漂亮的打印效果,但是不能使其正常工作。我知道以下结构是否为(Vec<u8>),可以像this playground code那样工作。但是我必须保留[[u8; 32])结构,因为它在现有项目中无处不在。有人可以帮助使它代替Vec用于数组吗?

#[derive(Serialize, Deserialize)]
struct OneFactor(
    #[serde(
        serialize_with = "buffer_to_hex",
        deserialize_with = "hex_to_buffer"
    )]
    [u8; 32],
);

/// Serializes `buffer` to a lowercase hex string.
pub fn buffer_to_hex<T, S>(buffer: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    T: AsRef<[u8]>,
    S: Serializer,
{
    serializer.serialize_str(&buffer.as_ref().to_hex())
}

/// Deserializes a lowercase hex string to a `Vec<u8>`.
pub fn hex_to_buffer<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    String::deserialize(deserializer)
        .and_then(|string| Vec::from_hex(&string).map_err(|err| Error::custom(err.to_string())))
}

fn print_an_factor() -> Result<(), Error> {
    let factor = OneFactor([
        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,
    ]);

    // Serialize it to a JSON string.
    let j = serde_json::to_string_pretty(&factor)?;

    // Print, write to a file, or send to an HTTP server.
    println!("{}", j);

    Ok(())
}

fn main() {
    print_an_factor().unwrap();
}

为了便于检查,我将完整的代码放入Rust Playground中。

[更新]

我制定了一个适用于to_hex()方向的版本,代码为here。但是反向from_hex()仍需要帮助〜

0 个答案:

没有答案