|
| 1 | +use alloc::{ |
| 2 | + borrow::{Cow, ToOwned as _}, |
| 3 | + str, |
| 4 | + string::String, |
| 5 | + vec::Vec, |
| 6 | +}; |
| 7 | +use core::fmt; |
| 8 | + |
| 9 | +use serde::{de, Deserializer}; |
| 10 | + |
| 11 | +/// Trims a CoW string during deserialization. |
| 12 | +pub fn cow_str<'a, 'de: 'a, D: Deserializer<'de>>(de: D) -> Result<Cow<'a, str>, D::Error> { |
| 13 | + struct CowStrVisitor; |
| 14 | + |
| 15 | + impl<'a> de::Visitor<'a> for CowStrVisitor { |
| 16 | + type Value = Cow<'a, str>; |
| 17 | + |
| 18 | + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 19 | + formatter.write_str("a string") |
| 20 | + } |
| 21 | + |
| 22 | + fn visit_str<E: de::Error>(self, val: &str) -> Result<Self::Value, E> { |
| 23 | + Ok(Cow::Owned(val.trim().to_owned())) |
| 24 | + } |
| 25 | + |
| 26 | + fn visit_borrowed_str<E: de::Error>(self, val: &'a str) -> Result<Self::Value, E> { |
| 27 | + Ok(Cow::Borrowed(val.trim())) |
| 28 | + } |
| 29 | + |
| 30 | + fn visit_string<E: de::Error>(self, val: String) -> Result<Self::Value, E> { |
| 31 | + Ok(Cow::Owned(val.trim().to_owned())) |
| 32 | + } |
| 33 | + |
| 34 | + fn visit_bytes<E: de::Error>(self, val: &[u8]) -> Result<Self::Value, E> { |
| 35 | + match str::from_utf8(val) { |
| 36 | + Ok(val) => Ok(Cow::Owned(val.trim().to_owned())), |
| 37 | + Err(_) => Err(de::Error::invalid_value(de::Unexpected::Bytes(val), &self)), |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + fn visit_borrowed_bytes<E: de::Error>(self, val: &'a [u8]) -> Result<Self::Value, E> { |
| 42 | + match str::from_utf8(val) { |
| 43 | + Ok(val) => Ok(Cow::Borrowed(val.trim())), |
| 44 | + Err(_) => Err(de::Error::invalid_value(de::Unexpected::Bytes(val), &self)), |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + fn visit_byte_buf<E: de::Error>(self, val: Vec<u8>) -> Result<Self::Value, E> { |
| 49 | + match String::from_utf8(val) { |
| 50 | + Ok(val) => Ok(Cow::Owned(val.trim().to_owned())), |
| 51 | + Err(err) => Err(de::Error::invalid_value( |
| 52 | + de::Unexpected::Bytes(&err.into_bytes()), |
| 53 | + &self, |
| 54 | + )), |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + de.deserialize_str(CowStrVisitor) |
| 60 | +} |
| 61 | + |
| 62 | +#[cfg(test)] |
| 63 | +mod tests { |
| 64 | + use serde::Deserialize; |
| 65 | + |
| 66 | + use super::*; |
| 67 | + |
| 68 | + #[test] |
| 69 | + fn cow_str() { |
| 70 | + #[derive(Debug, Deserialize, PartialEq, Eq)] |
| 71 | + struct Foo<'a> { |
| 72 | + #[serde(borrow, deserialize_with = "super::cow_str")] |
| 73 | + foo: Cow<'a, str>, |
| 74 | + } |
| 75 | + |
| 76 | + impl<'a> Foo<'a> { |
| 77 | + fn new(foo: impl Into<Cow<'a, str>>) -> Self { |
| 78 | + Self { foo: foo.into() } |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + serde_json::from_str::<Foo<'static>>(r#"{ "foo": 1 }"#).unwrap_err(); |
| 83 | + serde_json::from_str::<Foo<'static>>(r#"{ "foo": true }"#).unwrap_err(); |
| 84 | + |
| 85 | + assert_eq!( |
| 86 | + Foo::new(""), |
| 87 | + serde_json::from_str(r#"{ "foo": "" }"#).unwrap(), |
| 88 | + ); |
| 89 | + assert_eq!( |
| 90 | + Foo::new(""), |
| 91 | + serde_json::from_str(r#"{ "foo": " " }"#).unwrap(), |
| 92 | + ); |
| 93 | + assert_eq!( |
| 94 | + Foo::new("bar"), |
| 95 | + serde_json::from_str(r#"{ "foo": "bar" }"#).unwrap(), |
| 96 | + ); |
| 97 | + assert_eq!( |
| 98 | + Foo::new("bar"), |
| 99 | + serde_json::from_str(r#"{ "foo": " bar" }"#).unwrap(), |
| 100 | + ); |
| 101 | + assert_eq!( |
| 102 | + Foo::new("bar"), |
| 103 | + serde_json::from_str(r#"{ "foo": " bar" }"#).unwrap(), |
| 104 | + ); |
| 105 | + assert_eq!( |
| 106 | + Foo::new("bar"), |
| 107 | + serde_json::from_str(r#"{ "foo": "bar " }"#).unwrap(), |
| 108 | + ); |
| 109 | + assert_eq!( |
| 110 | + Foo::new("bar"), |
| 111 | + serde_json::from_str(r#"{ "foo": " bar " }"#).unwrap(), |
| 112 | + ); |
| 113 | + } |
| 114 | + |
| 115 | + #[test] |
| 116 | + fn cow_str_allows_borrows() { |
| 117 | + #[derive(Debug, Deserialize, PartialEq, Eq)] |
| 118 | + struct Foo<'a> { |
| 119 | + #[serde(borrow, deserialize_with = "super::cow_str")] |
| 120 | + foo: Cow<'a, str>, |
| 121 | + } |
| 122 | + |
| 123 | + // borrowed when no trimming is needed |
| 124 | + let source = br#"{ "foo": "bar" }"#.to_vec(); |
| 125 | + let json = serde_json::from_slice::<Foo<'_>>(&source).unwrap(); |
| 126 | + assert!(matches!(&json.foo, Cow::Borrowed(_))); |
| 127 | + assert_eq!(json.foo, "bar"); |
| 128 | + |
| 129 | + // borrowed and trimmed |
| 130 | + let source = br#"{ "foo": " bar " }"#.to_vec(); |
| 131 | + let json = serde_json::from_slice::<Foo<'_>>(&source).unwrap(); |
| 132 | + assert!(matches!(&json.foo, Cow::Borrowed(_))); |
| 133 | + assert_eq!(json.foo, "bar"); |
| 134 | + |
| 135 | + // owned and trimmed when escape sequences need processing |
| 136 | + let source = br#"{ "foo": " b\\ar " }"#.to_vec(); |
| 137 | + let json = serde_json::from_slice::<Foo<'_>>(&source).unwrap(); |
| 138 | + assert!(matches!(&json.foo, Cow::Owned(_))); |
| 139 | + assert_eq!(json.foo, "b\\ar"); |
| 140 | + } |
| 141 | +} |
0 commit comments