Skip to main content

deserialize_bounded

Function deserialize_bounded 

Source
pub fn deserialize_bounded<'de, const MAX: usize, D, T>(
    deserializer: D,
) -> Result<T, D::Error>
where D: Deserializer<'de>, T: FromIterator<u8>,
Available on crate feature serde only.
Expand description

Deserializes at most MAX decoded bytes from a 0x-prefixed hex string.

Available with serde. The prefix, case and collection behavior is the same as deserialize. MAX counts decoded bytes, so at most twice that many hex digits are accepted. A zero limit accepts "0x".

The limit is checked before allocating decoded output or invoking the collector. It does not limit input text storage used by the format, error-message storage, or allocations performed by a custom collector. It also does not constrain serialization; pair this function with the ordinary serialize function. Allocation failure follows the allocator’s error handling.

§Errors

Propagates deserializer errors. After obtaining text, checks the prefix, even payload length, the decoded-byte limit, then characters/case, in that order. An over-limit value is rejected even if it also contains invalid hex digits.

§Panics

A custom collector can still panic when full; the acceptance limit does not change its capacity or collection implementation.

§Examples

#[derive(serde::Serialize, serde::Deserialize)]
struct Packet {
    #[serde(
        serialize_with = "faster_hex::serialize",
        deserialize_with = "faster_hex::deserialize_bounded::<2, _, _>"
    )]
    bytes: Vec<u8>,
}

let packet: Packet = serde_json::from_str(r#"{"bytes":"0xab01"}"#)?;
assert_eq!(packet.bytes, [0xab, 1]);
assert!(serde_json::from_str::<Packet>(r#"{"bytes":"0x000102"}"#).is_err());