mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-22 11:28:02 +00:00
Serialize to binary if the serde format is not human readable
This implements the KISS suggested in https://github.com/serde-rs/serde/issues/790. It is possible that one of the other approaches may be better but this seemed like the simplest one to reignite som discussion. Personally I find the original suggestion of adding two traits perhaps slightly cleaner in theory but I think it ends up more complicated in the end since the added traits also need to be duplicated to to the `Seed` traits. Closes #790
This commit is contained in:
@@ -23,7 +23,8 @@ use std::str;
|
||||
extern crate serde;
|
||||
|
||||
extern crate serde_test;
|
||||
use self::serde_test::{Token, assert_ser_tokens, assert_ser_tokens_error};
|
||||
use self::serde_test::{Token, assert_ser_tokens, assert_ser_tokens_error,
|
||||
assert_ser_tokens_readable};
|
||||
|
||||
extern crate fnv;
|
||||
use self::fnv::FnvHasher;
|
||||
@@ -474,3 +475,26 @@ fn test_enum_skipped() {
|
||||
"the enum variant Enum::SkippedMap cannot be serialized",
|
||||
);
|
||||
}
|
||||
|
||||
struct CompactBinary(String);
|
||||
|
||||
impl serde::Serialize for CompactBinary {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer
|
||||
{
|
||||
if serializer.is_human_readable() {
|
||||
serializer.serialize_str(&self.0)
|
||||
} else {
|
||||
serializer.serialize_bytes(self.0.as_bytes())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_readable() {
|
||||
let value = CompactBinary("test".to_string());
|
||||
assert_ser_tokens(&value, &[Token::String("test")]);
|
||||
|
||||
assert_ser_tokens_readable(&value, &[Token::Bytes(b"test")], false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user