Skip to content

Commit

Permalink
trait Serialize uses reference to self instead of move.
Browse files Browse the repository at this point in the history
  • Loading branch information
Grinkers committed Dec 23, 2023
1 parent d64f20c commit f39709c
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 45 deletions.
3 changes: 2 additions & 1 deletion benches/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ mod edn {
use std::collections::{BTreeMap, BTreeSet};

pub fn criterion_benchmark(c: &mut Criterion) {
c.bench_function("edn", |b| b.iter(|| edn_rs::to_string(val())));
let val = val();
c.bench_function("edn", |b| b.iter(|| edn_rs::to_string(&val)));
}

fn val() -> ValEdn {
Expand Down
2 changes: 1 addition & 1 deletion examples/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn serialize() -> String {
nothing: (),
};

edn_rs::to_string(edn)
edn_rs::to_string(&edn)
}

fn main() {
Expand Down
6 changes: 3 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub mod edn;
/// set: set!{3i64, 4i64, 5i64},
/// tuples: (3i32, true, 'd')
/// };
/// println!("{}", edn_rs::to_string(edn));
/// println!("{}", edn_rs::to_string(&edn));
/// // { :map {:this-is-a-key ["with", "many", "keys"]}, :set #{3, 4, 5}, :tuples (3, true, \d), }
/// }
///```
Expand Down Expand Up @@ -129,11 +129,11 @@ pub use serialize::Serialize;
/// set: set!{3i64, 4i64, 5i64},
/// tuples: (3i32, true, 'd')
/// };
/// println!("{}", edn_rs::to_string(edn));
/// println!("{}", edn_rs::to_string(&edn));
/// // { :map {:this-is-a-key ["with", "many", "keys"]}, :set #{3, 4, 5}, :tuples (3, true, \d), }
/// }
///```
#[allow(clippy::needless_doctest_main)]
pub fn to_string<T: Serialize>(t: T) -> String {
pub fn to_string<T: Serialize>(t: &T) -> String {
t.serialize()
}
70 changes: 32 additions & 38 deletions src/serialize/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ use alloc::vec::Vec;
/// struct YourType;
///
/// impl Serialize for YourType {
/// fn serialize(self) -> String {
/// fn serialize(&self) -> String {
/// format!("{:?}", self)
/// }
/// }
/// ```
///
/// Implemented for all generic types.
pub trait Serialize {
fn serialize(self) -> String;
fn serialize(&self) -> String;
}

macro_rules! ser_primitives {
( $( $name:ty ),+ ) => {
$(
impl Serialize for $name
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!("{:?}", self)
}
}
Expand All @@ -40,9 +40,9 @@ impl<T> Serialize for Vec<T>
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(Serialize::serialize)
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -58,9 +58,9 @@ impl<T, H: std::hash::BuildHasher> Serialize for std::collections::HashSet<T, H>
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(Serialize::serialize)
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -76,9 +76,9 @@ impl<T> Serialize for BTreeSet<T>
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(Serialize::serialize)
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -94,9 +94,9 @@ impl<T> Serialize for LinkedList<T>
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(Serialize::serialize)
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -112,9 +112,9 @@ impl<T, H: std::hash::BuildHasher> Serialize for std::collections::HashMap<Strin
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(|(k, v)| format!(":{} {}", k.replace([' ', '_'], "-"), v.serialize()))
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -130,9 +130,9 @@ impl<T, H: ::std::hash::BuildHasher> Serialize for std::collections::HashMap<&st
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(|(k, v)| format!(":{} {}", k.replace([' ', '_'], "-"), v.serialize()))
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -147,9 +147,9 @@ impl<T> Serialize for BTreeMap<String, T>
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.iter()
.map(|(k, v)| format!(":{} {}", k.replace([' ', '_'], "-"), v.serialize()))
.collect::<Vec<String>>();
let mut s = String::new();
Expand All @@ -164,16 +164,10 @@ impl<T> Serialize for BTreeMap<&str, T>
where
T: Serialize,
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
let aux_vec = self
.into_iter()
.map(|(k, v)| {
format!(
":{} {}",
k.to_string().replace([' ', '_'], "-"),
v.serialize()
)
})
.iter()
.map(|(k, v)| format!(":{} {}", k.replace([' ', '_'], "-"), v.serialize()))
.collect::<Vec<String>>();
let mut s = String::new();
s.push('{');
Expand All @@ -187,25 +181,25 @@ where
ser_primitives![i8, i16, i32, i64, u8, u16, u32, u64, f32, f64, bool];

impl Serialize for () {
fn serialize(self) -> String {
fn serialize(&self) -> String {
"nil".to_string()
}
}

impl Serialize for String {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!("{self:?}")
}
}

impl Serialize for &str {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!("{self:?}")
}
}

impl Serialize for char {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!("\\{self}")
}
}
Expand All @@ -214,8 +208,8 @@ impl<T> Serialize for Option<T>
where
T: Serialize,
{
fn serialize(self) -> String {
self.map_or_else(
fn serialize(&self) -> String {
self.as_ref().map_or_else(
|| String::from("nil"),
crate::serialize::Serialize::serialize,
)
Expand All @@ -224,19 +218,19 @@ where

// Complex types
impl<A: Serialize> Serialize for (A,) {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!("({})", self.0.serialize())
}
}

impl<A: Serialize, B: Serialize> Serialize for (A, B) {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!("({}, {})", self.0.serialize(), self.1.serialize())
}
}

impl<A: Serialize, B: Serialize, C: Serialize> Serialize for (A, B, C) {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!(
"({}, {}, {})",
self.0.serialize(),
Expand All @@ -247,7 +241,7 @@ impl<A: Serialize, B: Serialize, C: Serialize> Serialize for (A, B, C) {
}

impl<A: Serialize, B: Serialize, C: Serialize, D: Serialize> Serialize for (A, B, C, D) {
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!(
"({}, {}, {}, {})",
self.0.serialize(),
Expand All @@ -261,7 +255,7 @@ impl<A: Serialize, B: Serialize, C: Serialize, D: Serialize> Serialize for (A, B
impl<A: Serialize, B: Serialize, C: Serialize, D: Serialize, E: Serialize> Serialize
for (A, B, C, D, E)
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!(
"({}, {}, {}, {}, {})",
self.0.serialize(),
Expand All @@ -276,7 +270,7 @@ impl<A: Serialize, B: Serialize, C: Serialize, D: Serialize, E: Serialize> Seria
impl<A: Serialize, B: Serialize, C: Serialize, D: Serialize, E: Serialize, F: Serialize> Serialize
for (A, B, C, D, E, F)
{
fn serialize(self) -> String {
fn serialize(&self) -> String {
format!(
"({}, {}, {}, {}, {}, {})",
self.0.serialize(),
Expand Down
4 changes: 2 additions & 2 deletions tests/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod tests {
tuples: (3i32, true, 'd'),
};

assert_eq!(edn_rs::to_string(edn), "{ :btreemap {:this-is-a-key [\"with\", \"many\", \"keys\"]}, :btreeset #{3, 4, 5}, :hashmap {:this-is-a-key [\"with\", \"many\", \"keys\"]}, :hashset #{3}, :tuples (3, true, \\d), }");
assert_eq!(edn_rs::to_string(&edn), "{ :btreemap {:this-is-a-key [\"with\", \"many\", \"keys\"]}, :btreeset #{3, 4, 5}, :hashmap {:this-is-a-key [\"with\", \"many\", \"keys\"]}, :hashset #{3}, :tuples (3, true, \\d), }");
}

#[test]
Expand Down Expand Up @@ -54,7 +54,7 @@ mod tests {
},
};

assert_eq!(edn_rs::to_string(edn), "{ :value 3.4, :bar { :value \"data\", :foo-vec [{ :value false, }, { :value true, }], }, }");
assert_eq!(edn_rs::to_string(&edn), "{ :value 3.4, :bar { :value \"data\", :foo-vec [{ :value false, }, { :value true, }], }, }");
}
}

Expand Down

0 comments on commit f39709c

Please sign in to comment.