Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Allow #[serde(rename=str|bool|int)] for enum variants. #973

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion serde/src/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub use lib::marker::PhantomData;
pub use lib::option::Option::{self, None, Some};
pub use lib::result::Result::{self, Ok, Err};

pub use self::string::from_utf8_lossy;
pub use self::string::{from_utf8_lossy, from_int, from_bool};

mod string {
use lib::*;
Expand All @@ -38,4 +38,49 @@ mod string {
// UTF-8.
str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}")
}

pub fn from_bool(b : bool) -> &'static str {
if b {
"true"
} else {
"false"
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
pub fn from_int(i: u64) -> Vec<u8> {
use lib::fmt::Write;
let mut buf = String::with_capacity(20);
write!(&mut buf, "{}", i).ok();
buf.into_bytes()
}

#[cfg(not(any(feature = "std", feature = "alloc")))]
pub fn from_int(i: u64) -> [u8; 20] {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the int/bool to string is needed for fn deserialize_identifier(..., fallthrough_arm : Option<Tokens>) where the fallthrough arm expects a local '&str' value, so writing to stdout is not possible.
It feels a bit too hacky :D

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems fine. Nicely done.

use lib::fmt::Write;
// len(str(1<<64)) = 20
let mut buf = [0; 20];
{
let mut wrap = Wrapper { buf: &mut buf };
write!(wrap, "{}", i).ok();
}
buf
}

#[cfg(not(any(feature = "std", feature = "alloc")))]
struct Wrapper<'a> {
buf: &'a mut [u8],
}

#[cfg(not(any(feature = "std", feature = "alloc")))]
impl<'a> fmt::Write for Wrapper<'a> {
// Could panic if buf is too small.
fn write_str(&mut self, s: &str) -> fmt::Result {
let bytes = s.as_bytes();
self.buf[..bytes.len()].copy_from_slice(bytes);
let this : &mut[u8] = mem::replace(&mut self.buf, &mut []);
self.buf = &mut this[bytes.len()..];
Ok(())
}
}
}
58 changes: 48 additions & 10 deletions serde/src/private/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,63 @@ pub fn constrain<T: ?Sized>(t: &T) -> &T {
t
}

pub enum VariantName {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: This enum is defined three times. The other two times it is named StrBoolInt.
Should it be named after its purpose or after its content?

In the serde_derive_internals crate, the name VariantName is already occupied by the struct VariantName { deserialize: StrBoolInt, serialize: StrBoolInt }. Maybe rename the VariantName into SerDeVariantName and StrBoolInt into VariantName?

Str(&'static str),
Bool(bool),
Int(u64),
}

impl From<&'static str> for VariantName {
fn from(src: &'static str) -> VariantName {
VariantName::Str(src)
}
}

impl<'a> From<&'a bool> for VariantName {
fn from(src: &bool) -> VariantName {
VariantName::Bool(*src)
}
}

impl<'a> From<&'a u64> for VariantName {
fn from(src: &u64) -> VariantName {
VariantName::Int(*src)
}
}

impl Serialize for VariantName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer
{
match *self {
VariantName::Str(s) => serializer.serialize_str(s),
VariantName::Bool(b) => serializer.serialize_bool(b),
VariantName::Int(i) => serializer.serialize_u64(i),
}
}
}

/// Not public API.
pub fn serialize_tagged_newtype<S, T>(
pub fn serialize_tagged_newtype<S, T, U>(
serializer: S,
type_ident: &'static str,
variant_ident: &'static str,
tag: &'static str,
variant_name: &'static str,
variant_name: U,
value: &T,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: Serialize,
U: Into<VariantName>
{
value.serialize(
TaggedSerializer {
type_ident: type_ident,
variant_ident: variant_ident,
tag: tag,
variant_name: variant_name,
variant_name: variant_name.into(),
delegate: serializer,
},
)
Expand All @@ -47,7 +85,7 @@ struct TaggedSerializer<S> {
type_ident: &'static str,
variant_ident: &'static str,
tag: &'static str,
variant_name: &'static str,
variant_name: VariantName,
delegate: S,
}

Expand Down Expand Up @@ -209,7 +247,7 @@ where
inner_variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
let mut map = try!(self.delegate.serialize_map(Some(2)));
try!(map.serialize_entry(self.tag, self.variant_name));
try!(map.serialize_entry(self.tag, &self.variant_name));
try!(map.serialize_entry(inner_variant, &()));
map.end()
}
Expand All @@ -236,7 +274,7 @@ where
T: Serialize,
{
let mut map = try!(self.delegate.serialize_map(Some(2)));
try!(map.serialize_entry(self.tag, self.variant_name));
try!(map.serialize_entry(self.tag, &self.variant_name));
try!(map.serialize_entry(inner_variant, inner_value));
map.end()
}
Expand Down Expand Up @@ -279,14 +317,14 @@ where
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
let mut map = try!(self.delegate.serialize_map(Some(2)));
try!(map.serialize_entry(self.tag, self.variant_name));
try!(map.serialize_entry(self.tag, &self.variant_name));
try!(map.serialize_key(inner_variant));
Ok(SerializeTupleVariantAsMapValue::new(map, inner_variant, len),)
}

fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1)));
try!(map.serialize_entry(self.tag, self.variant_name));
try!(map.serialize_entry(self.tag, &self.variant_name));
Ok(map)
}

Expand All @@ -296,7 +334,7 @@ where
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
let mut state = try!(self.delegate.serialize_struct(name, len + 1));
try!(state.serialize_field(self.tag, self.variant_name));
try!(state.serialize_field(self.tag, &self.variant_name));
Ok(state)
}

Expand All @@ -322,7 +360,7 @@ where
len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
let mut map = try!(self.delegate.serialize_map(Some(2)));
try!(map.serialize_entry(self.tag, self.variant_name));
try!(map.serialize_entry(self.tag, &self.variant_name));
try!(map.serialize_key(inner_variant));
Ok(SerializeStructVariantAsMapValue::new(map, inner_variant, len),)
}
Expand Down
Loading