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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
//! A (de)serializer for anything that has implemented `FromStr` / `Display` (as `ToString`) but does not have `Serialize`/`Deserialize`, and is wrapped in an `Option` type, and may be represented as an empty string. //! //! # Example //! //! ```rust //! # #[macro_use] extern crate serde_derive; //! use std::net::IpAddr; //! //! /// A structure with an optional IP address. //! #[derive(Serialize, Deserialize)] //! # #[derive(PartialEq, Debug)] //! struct WithIp { //! #[serde(with = "serde_strz::emp")] //! ip: Option<IpAddr>, //! } //! //! use serde_json::{ //! from_str, //! to_string, //! }; //! # fn main() -> serde_json::Result<()> { //! let with_ip: WithIp = from_str(r#"{"ip": "127.0.0.1"}"#)?; //! assert_eq!(with_ip, WithIp { ip: Some([127, 0, 0, 1].into()) }); //! assert_eq!(to_string(&with_ip)?, r#"{"ip":"127.0.0.1"}"#); //! let with_ip: WithIp = from_str(r#"{"ip": ""}"#)?; //! assert_eq!(with_ip, WithIp { ip: None }); //! assert_eq!(to_string(&with_ip)?, r#"{"ip":""}"#); //! # Ok(()) //! # } //! ``` //! //! Combined with `#[serde(default)]`, it allows fields to be omitted from input entirely. //! //! ```rust //! # #[macro_use] extern crate serde_derive; //! # use std::net::IpAddr; //! # use serde_json::{from_str, to_string}; //! /// A structure with an optional IP address that might not exist in the input. //! #[derive(Serialize, Deserialize)] //! # #[derive(PartialEq, Debug)] //! struct WithIp { //! #[serde(with = "serde_strz::emp", default)] //! ip: Option<IpAddr>, //! } //! //! # fn main() -> serde_json::Result<()> { //! let with_ip: WithIp = from_str("{}")?; //! assert_eq!(with_ip, WithIp { ip: None }); //! assert_eq!(to_string(&with_ip)?, r#"{"ip":""}"#); //! //! let with_ip_some: WithIp = from_str(r#"{"ip": "127.0.0.1"}"#)?; //! assert_eq!(with_ip_some, WithIp { ip: Some([127, 0, 0, 1].into()) }); //! assert_eq!(to_string(&with_ip_some)?, r#"{"ip":"127.0.0.1"}"#); //! # Ok(()) //! # } //! ``` //! //! Excess output can be avoided with `skip_serializing_if` //! //! ```rust //! # #[macro_use] extern crate serde_derive; //! # use serde::{Serialize, Deserialize}; //! # use std::net::IpAddr; //! # use serde_json::{from_str, to_string}; //! /// A structure with an optional IP address that might not exist in the input, and won't exist //! /// in the output if it's empty. //! #[derive(Serialize, Deserialize)] //! # #[derive(PartialEq, Debug)] //! struct WithIp { //! #[serde(with = "serde_strz::emp", skip_serializing_if = "Option::is_none")] //! ip: Option<IpAddr>, //! } //! //! # fn main() -> serde_json::Result<()> { //! let with_ip_empty: WithIp = from_str(r#"{"ip": ""}"#)?; //! assert_eq!(with_ip_empty, WithIp { ip: None }); //! assert_eq!(to_string(&with_ip_empty)?, "{}"); //! # Ok(()) //! # } //! ``` //! //! Consistently inconsistent input can be normalized by combining `skip_serializing_if` and //! `default`. //! //! ```rust //! # #[macro_use] extern crate serde_derive; //! # use serde::{Serialize, Deserialize}; //! # use std::net::IpAddr; //! # use serde_json::{from_str, to_string}; //! /// A structure with an optional IP address that might not exist in the input, and won't exist //! /// in the output if it's empty. //! #[derive(Serialize, Deserialize)] //! # #[derive(PartialEq, Debug)] //! struct WithIp { //! #[serde(default, with = "serde_strz::emp", skip_serializing_if = "Option::is_none")] //! ip: Option<IpAddr>, //! } //! //! # fn main() -> serde_json::Result<()> { //! let with_ip_empty: WithIp = from_str(r#"{"ip": ""}"#)?; //! assert_eq!(with_ip_empty, WithIp { ip: None }); //! assert_eq!(to_string(&with_ip_empty)?, "{}"); //! //! let with_ip_empty: WithIp = from_str(r#"{}"#)?; //! assert_eq!(with_ip_empty, WithIp { ip: None }); //! assert_eq!(to_string(&with_ip_empty)?, "{}"); //! # Ok(()) //! # } //! ``` use serde::{ de, Deserialize, Deserializer, Serializer, }; use std::{ fmt::Display, str::FromStr, }; /// Deserialize function, see [mod docs examples](https://docs.rs/serde_strz/*/serde_strz/emp/index.html) to see how to use it pub fn deserialize<'de, T, D>(deserializer: D) -> Result<Option<T>, D::Error> where T: FromStr, T::Err: Display, D: Deserializer<'de>, { if let Some(s) = Option::deserialize(deserializer)? { if str::is_empty(s) { Ok(None) } else { T::from_str(s).map_err(de::Error::custom).map(|s| Some(s)) } } else { Ok(None) } } /// Serialize function, see [mod docs examples](https://docs.rs/serde_strz/*/serde_strz/emp/index.html) to see how to use it pub fn serialize<T, S>( value: &Option<T>, serializer: S, ) -> Result<S::Ok, S::Error> where T: Display, S: Serializer, { if let Some(val) = value.as_ref() { serializer.collect_str(val) } else { serializer.serialize_str("") } }