mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-22 21:48:02 +00:00
feat(ser): Add ser::Error trait; avoid panic when serializing Paths
The only way to safely serialize a `Path` is to use `.to_string_lossy()`, which replaces invalid UTF-8 characters with the U+FFFD replacement character. Unfortunately this would lose information, so for our default implementations, it'd be better to punt and report an error, and leave it up to the user to decide if they want to use the lossy encoding. Unfortunately, we had no way for `Serializer`s to require some methods on `Serializer::Error`, so there was no way before this patch for the `Path` implementation to generically report that it cannot encode this value. This adds that implementation. breaking-change Closes #57.
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str;
|
||||
|
||||
use num::FromPrimitive;
|
||||
use num::bigint::{BigInt, BigUint};
|
||||
use num::complex::Complex;
|
||||
use num::rational::Ratio;
|
||||
|
||||
use token::Token;
|
||||
use token::{self, Token};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -305,3 +306,22 @@ declare_ser_tests! {
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cannot_serialize_paths() {
|
||||
let path = unsafe {
|
||||
str::from_utf8_unchecked(b"Hello \xF0\x90\x80World")
|
||||
};
|
||||
token::assert_ser_tokens_error(
|
||||
&Path::new(path),
|
||||
&[Token::Str("Hello �World")],
|
||||
token::Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
|
||||
|
||||
let mut path_buf = PathBuf::new();
|
||||
path_buf.push(path);
|
||||
|
||||
token::assert_ser_tokens_error(
|
||||
&path_buf,
|
||||
&[Token::Str("Hello �World")],
|
||||
token::Error::InvalidValue("Path contains invalid UTF-8 characters".to_owned()));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user