|
| 1 | +use core::str; |
| 2 | + |
1 | 3 | use serde::{de::Visitor, Deserialize, Serialize}; |
2 | 4 |
|
3 | | -use crate::serde_helpers::HumanReadable; |
| 5 | +use crate::{ |
| 6 | + from_slice, |
| 7 | + serde_helpers::{HumanReadable, Utf8LossyDeserialization}, |
| 8 | +}; |
4 | 9 |
|
5 | 10 | #[test] |
6 | 11 | fn human_readable_wrapper() { |
@@ -135,3 +140,50 @@ fn human_readable_wrapper() { |
135 | 140 | let raw_tripped: Data = crate::from_slice(&bytes).unwrap(); |
136 | 141 | assert_eq!(&raw_tripped, &expected); |
137 | 142 | } |
| 143 | + |
| 144 | +#[test] |
| 145 | +#[allow(dead_code)] // suppress warning for unread fields |
| 146 | +fn utf8_lossy_wrapper() { |
| 147 | + let invalid_bytes = b"\x80\xae".to_vec(); |
| 148 | + let invalid_string = unsafe { String::from_utf8_unchecked(invalid_bytes) }; |
| 149 | + |
| 150 | + let both_strings_invalid_bytes = |
| 151 | + rawdoc! { "s1": invalid_string.clone(), "s2": invalid_string.clone() }.into_bytes(); |
| 152 | + let first_string_invalid_bytes = |
| 153 | + rawdoc! { "s1": invalid_string.clone(), "s2": ":)" }.into_bytes(); |
| 154 | + |
| 155 | + let expected_replacement = "��".to_string(); |
| 156 | + |
| 157 | + #[derive(Debug, Deserialize)] |
| 158 | + struct NoUtf8Lossy { |
| 159 | + s1: String, |
| 160 | + s2: String, |
| 161 | + } |
| 162 | + |
| 163 | + from_slice::<NoUtf8Lossy>(&both_strings_invalid_bytes).unwrap_err(); |
| 164 | + |
| 165 | + let s = from_slice::<Utf8LossyDeserialization<NoUtf8Lossy>>(&both_strings_invalid_bytes) |
| 166 | + .unwrap() |
| 167 | + .0; |
| 168 | + assert_eq!(s.s1, expected_replacement); |
| 169 | + assert_eq!(s.s2, expected_replacement); |
| 170 | + |
| 171 | + #[derive(Debug, Deserialize)] |
| 172 | + struct FirstStringUtf8Lossy { |
| 173 | + s1: Utf8LossyDeserialization<String>, |
| 174 | + s2: String, |
| 175 | + } |
| 176 | + |
| 177 | + let s = from_slice::<FirstStringUtf8Lossy>(&first_string_invalid_bytes).unwrap(); |
| 178 | + assert_eq!(s.s1.0, expected_replacement); |
| 179 | + assert_eq!(&s.s2, ":)"); |
| 180 | + |
| 181 | + from_slice::<FirstStringUtf8Lossy>(&both_strings_invalid_bytes).unwrap_err(); |
| 182 | + |
| 183 | + let s = |
| 184 | + from_slice::<Utf8LossyDeserialization<FirstStringUtf8Lossy>>(&both_strings_invalid_bytes) |
| 185 | + .unwrap() |
| 186 | + .0; |
| 187 | + assert_eq!(s.s1.0, expected_replacement); |
| 188 | + assert_eq!(s.s2, expected_replacement); |
| 189 | +} |
0 commit comments