Skip to content

Commit 9aba45e

Browse files
committed
added support for miniserde
1 parent 60bc0a3 commit 9aba45e

3 files changed

Lines changed: 51 additions & 0 deletions

File tree

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ repository = "https://github.com/Synphonyte/codee"
1414
[dependencies]
1515
base64 = { version = "0.21", optional = true }
1616
bincode = { version = "1", optional = true }
17+
miniserde = { version = "0.1", optional = true }
1718
prost = { version = "0.12", optional = true }
1819
rkyv = { version = "0.7", optional = true, features = ["validation", "strict"] }
1920
rmp-serde = { version = "1.1", optional = true }

src/string/miniserde.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
use crate::{Decoder, Encoder};
2+
use miniserde::{json, Deserialize, Serialize};
3+
4+
/// A codec that relies on `miniserde` to encode data in the json format.
5+
///
6+
/// This is only available with the **`miniserde` feature** enabled.
7+
pub struct MiniserdeCodec;
8+
9+
impl<T: Serialize> Encoder<T> for MiniserdeCodec {
10+
type Error = ();
11+
type Encoded = String;
12+
13+
fn encode(val: &T) -> Result<Self::Encoded, Self::Error> {
14+
Ok(json::to_string(val))
15+
}
16+
}
17+
18+
impl<T: Deserialize> Decoder<T> for MiniserdeCodec {
19+
type Error = miniserde::Error;
20+
type Encoded = str;
21+
22+
fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
23+
json::from_str(val)
24+
}
25+
}
26+
27+
#[cfg(test)]
28+
mod tests {
29+
use super::*;
30+
31+
#[test]
32+
fn test_json_codec() {
33+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
34+
struct Test {
35+
s: String,
36+
i: i32,
37+
}
38+
let t = Test {
39+
s: String::from("party time 🎉"),
40+
i: 42,
41+
};
42+
let enc = MiniserdeCodec::encode(&t).unwrap();
43+
let dec: Test = MiniserdeCodec::decode(&enc).unwrap();
44+
assert_eq!(dec, t);
45+
}
46+
}

src/string/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,15 @@ mod base64;
33
mod from_to_string;
44
#[cfg(feature = "json_serde")]
55
mod json_serde;
6+
#[cfg(feature = "miniserde")]
7+
mod miniserde;
68
mod option;
79

810
#[cfg(feature = "base64")]
911
pub use base64::*;
1012
pub use from_to_string::*;
1113
#[cfg(feature = "json_serde")]
1214
pub use json_serde::*;
15+
#[cfg(feature = "miniserde")]
16+
pub use miniserde::*;
1317
pub use option::*;

0 commit comments

Comments
 (0)