crate::ix!();
pub fn fuzzy_vec_u8<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let val: JsonValue = Deserialize::deserialize(deserializer)?;
match val {
JsonValue::Null => {
debug!("Received null for fuzzy_vec_u8 => returning empty Vec<u8>.");
Ok(Vec::new())
}
JsonValue::Array(arr) => {
let mut result = Vec::with_capacity(arr.len());
for elem in arr {
let fuzzed = match elem {
JsonValue::Number(num) => {
if let Some(u) = num.as_u64() {
if u <= 255 {
u as u8
} else {
warn!("JsonValue {} out of u8 range => clamping to 255", u);
255
}
}
else if let Some(f) = num.as_f64() {
if f < 0.0 {
warn!("Float {} < 0 => clamping to 0", f);
0
} else if f > 255.0 {
warn!("Float {} > 255 => clamping to 255", f);
255
} else {
let truncated = f.trunc();
if (f - truncated).abs() > f64::EPSILON {
warn!("Truncating float {} => {}", f, truncated);
}
truncated as u8
}
} else {
let msg = format!("Number not convertible to u64/f64 => {:?}", num);
return Err(de::Error::custom(msg));
}
}
other => {
let msg = format!("Expected numeric in array, got {:?}", other);
return Err(de::Error::custom(msg));
}
};
result.push(fuzzed);
}
Ok(result)
}
other => {
let msg = format!("Expected array or null for fuzzy_vec_u8, got {:?}", other);
Err(de::Error::custom(msg))
}
}
}