Expand description
Encode a value through Display and decode it through FromStr.
This module can be used as a field adapter with
#[musli(with = musli::display)], which makes a field a string on
the wire. Its option submodule does the same for an Option<T> field.
For a type which should always be a string on the wire, the derives also
accept #[musli(display)] on the type itself.
Decoding fails with the FromStr error, formatted through its
Display implementation, if the string can not be parsed.
§Examples
use std::net::Ipv4Addr;
use musli::{Decode, Encode};
#[derive(Debug, PartialEq, Encode, Decode)]
struct Host {
#[musli(with = musli::display)]
address: Ipv4Addr,
#[musli(with = musli::display::option)]
gateway: Option<Ipv4Addr>,
}
let host = Host {
address: Ipv4Addr::new(10, 0, 0, 2),
gateway: None,
};
let json = musli::json::to_string(&host)?;
assert_eq!(json, r#"{"address":"10.0.0.2","gateway":null}"#);
assert_eq!(musli::json::from_str::<Host>(&json)?, host);
let error = musli::json::from_str::<Host>(r#"{"address":"10.0.0","gateway":null}"#);
assert!(error.is_err());