Render 128-bit integer value into Visitor errors

This commit is contained in:
David Tolnay 2022-01-25 12:04:24 -08:00
parent 82c3eb7ba4
commit 0d71ac84b5
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
3 changed files with 42 additions and 6 deletions

30
serde/src/de/format.rs Normal file
View File

@ -0,0 +1,30 @@
use lib::fmt::{self, Write};
use lib::str;
pub struct Buf<'a> {
bytes: &'a mut [u8],
offset: usize,
}
impl<'a> Buf<'a> {
pub fn new(bytes: &'a mut [u8]) -> Self {
Buf { bytes, offset: 0 }
}
pub fn as_str(&self) -> &str {
let slice = &self.bytes[..self.offset];
unsafe { str::from_utf8_unchecked(slice) }
}
}
impl<'a> Write for Buf<'a> {
fn write_str(&mut self, s: &str) -> fmt::Result {
if self.offset + s.len() > self.bytes.len() {
Err(fmt::Error)
} else {
self.bytes[self.offset..self.offset + s.len()].copy_from_slice(s.as_bytes());
self.offset += s.len();
Ok(())
}
}
}

View File

@ -118,6 +118,8 @@ use lib::*;
pub mod value; pub mod value;
#[cfg(not(no_integer128))]
mod format;
mod ignored_any; mod ignored_any;
mod impls; mod impls;
mod utf8; mod utf8;
@ -1366,8 +1368,10 @@ pub trait Visitor<'de>: Sized {
where where
E: Error, E: Error,
{ {
let _ = v; let mut buf = [0u8; 58];
Err(Error::invalid_type(Unexpected::Other("i128"), &self)) let mut writer = format::Buf::new(&mut buf);
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap();
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
} }
} }
@ -1426,8 +1430,10 @@ pub trait Visitor<'de>: Sized {
where where
E: Error, E: Error,
{ {
let _ = v; let mut buf = [0u8; 57];
Err(Error::invalid_type(Unexpected::Other("u128"), &self)) let mut writer = format::Buf::new(&mut buf);
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap();
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
} }
} }

View File

@ -192,7 +192,7 @@ fn test_i128() {
let error = <&str>::deserialize(deserializer).unwrap_err(); let error = <&str>::deserialize(deserializer).unwrap_err();
assert_eq!( assert_eq!(
error.to_string(), error.to_string(),
"invalid type: i128, expected a borrowed string", "invalid type: integer `1` as i128, expected a borrowed string",
); );
} }
@ -372,7 +372,7 @@ fn test_u128() {
let error = <&str>::deserialize(deserializer).unwrap_err(); let error = <&str>::deserialize(deserializer).unwrap_err();
assert_eq!( assert_eq!(
error.to_string(), error.to_string(),
"invalid type: u128, expected a borrowed string", "invalid type: integer `1` as u128, expected a borrowed string",
); );
} }