aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorJakub Kotur <qtr@google.com>2020-12-21 17:28:16 +0100
committerJakub Kotur <qtr@google.com>2021-02-26 18:29:35 +0100
commit2af68aa7030eb84a616affd35aa581a94b1d71a8 (patch)
tree9b0abbbd1058f4519287ab8e735764bbb6fb95b1 /examples
parent137e88ed29967b3f098b4d91988afc90f6a2ead9 (diff)
downloadserde_cbor-2af68aa7030eb84a616affd35aa581a94b1d71a8.tar.gz
Initial import of serde_cbor-0.11.1
Bug: 155309706 Change-Id: I76f4c8f21175d62b941d8a6fc6d80d86f93e84f3
Diffstat (limited to 'examples')
-rw-r--r--examples/readme.rs39
-rw-r--r--examples/tags.rs84
-rw-r--r--examples/tux.cbor1
3 files changed, 124 insertions, 0 deletions
diff --git a/examples/readme.rs b/examples/readme.rs
new file mode 100644
index 0000000..7689394
--- /dev/null
+++ b/examples/readme.rs
@@ -0,0 +1,39 @@
+// NOTE: This file should be kept in sync with README.md
+
+use serde_derive::{Deserialize, Serialize};
+use std::error::Error;
+use std::fs::File;
+
+// Types annotated with `Serialize` can be stored as CBOR.
+// To be able to load them again add `Deserialize`.
+#[derive(Debug, Serialize, Deserialize)]
+struct Mascot {
+ name: String,
+ species: String,
+ year_of_birth: u32,
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let ferris = Mascot {
+ name: "Ferris".to_owned(),
+ species: "crab".to_owned(),
+ year_of_birth: 2015,
+ };
+
+ let ferris_file = File::create("examples/ferris.cbor")?;
+ // Write Ferris to the given file.
+ // Instead of a file you can use any type that implements `io::Write`
+ // like a HTTP body, database connection etc.
+ serde_cbor::to_writer(ferris_file, &ferris)?;
+
+ let tux_file = File::open("examples/tux.cbor")?;
+ // Load Tux from a file.
+ // Serde CBOR performs roundtrip serialization meaning that
+ // the data will not change in any way.
+ let tux: Mascot = serde_cbor::from_reader(tux_file)?;
+
+ println!("{:?}", tux);
+ // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 }
+
+ Ok(())
+}
diff --git a/examples/tags.rs b/examples/tags.rs
new file mode 100644
index 0000000..9281b9b
--- /dev/null
+++ b/examples/tags.rs
@@ -0,0 +1,84 @@
+use serde::de::{Deserialize, Deserializer};
+use serde::ser::{Serialize, Serializer};
+use serde_cbor::tags::Tagged;
+use serde_cbor::Value;
+use serde_derive::{Deserialize, Serialize};
+use std::error::Error;
+
+/// https://tools.ietf.org/html/rfc7049#section-2.4.1
+#[derive(Debug, PartialEq)]
+struct Date(String);
+
+impl Serialize for Date {
+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
+ Tagged::new(Some(0), &self.0).serialize(s)
+ }
+}
+
+impl<'de> Deserialize<'de> for Date {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let tagged = Tagged::<String>::deserialize(deserializer)?;
+ match tagged.tag {
+ Some(0) | None => Ok(Date(tagged.value)),
+ Some(_) => Err(serde::de::Error::custom("unexpected tag")),
+ }
+ }
+}
+
+/// https://tools.ietf.org/html/rfc7049#section-2.4.4.3
+#[derive(Debug, PartialEq)]
+struct Uri(String);
+
+impl Serialize for Uri {
+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
+ Tagged::new(Some(32), &self.0).serialize(s)
+ }
+}
+impl<'de> Deserialize<'de> for Uri {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let tagged = Tagged::<String>::deserialize(deserializer)?;
+ match tagged.tag {
+ // allow deserialization even if there is no tag. Allows roundtrip via other formats such as json
+ Some(0) | None => Ok(Uri(tagged.value)),
+ Some(_) => Err(serde::de::Error::custom("unexpected tag")),
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+struct Bookmark {
+ title: String,
+ link: Uri,
+ created: Date,
+}
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let bookmark = Bookmark {
+ title: "The Example Domain".into(),
+ link: Uri("http://example.org/".into()),
+ created: Date("2003-12-13T18:30:02Z".into()),
+ };
+
+ // serialize the struct to bytes
+ let bytes1 = serde_cbor::to_vec(&bookmark)?;
+ // deserialize to a serde_cbor::Value
+ let value1: Value = serde_cbor::from_slice(&bytes1)?;
+ println!("{:?}", value1);
+ // serialize the value to bytes
+ let bytes2 = serde_cbor::to_vec(&value1)?;
+ // deserialize to a serde_cbor::Value
+ let value2: Value = serde_cbor::from_slice(&bytes2)?;
+ println!("{:?}", value2);
+ // deserialize to a Bookmark
+ let result: Bookmark = serde_cbor::from_slice(&bytes2)?;
+
+ // check that the roundtrip was successful
+ assert_eq!(value1, value2);
+ assert_eq!(bookmark, result);
+
+ // check that going via a format that does not support tags does work
+ // let json = serde_json::to_vec(&bookmark)?;
+ // let result: Bookmark = serde_json::from_slice(&json)?;
+ // assert_eq!(bookmark, result);
+ Ok(())
+}
diff --git a/examples/tux.cbor b/examples/tux.cbor
new file mode 100644
index 0000000..c3331aa
--- /dev/null
+++ b/examples/tux.cbor
@@ -0,0 +1 @@
+£dnamecTuxgspeciesgpenguinmyear_of_birthÌ \ No newline at end of file