| 1 | // NOTE: This file should be kept in sync with README.md |
| 2 | |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use std::{error::Error, fs::File}; |
| 5 | |
| 6 | // Types annotated with `Serialize` can be stored as CBOR. |
| 7 | // To be able to load them again add `Deserialize`. |
| 8 | #[derive(Debug, Serialize, Deserialize)] |
| 9 | struct Mascot { |
| 10 | name: String, |
| 11 | species: String, |
| 12 | year_of_birth: u32, |
| 13 | } |
| 14 | |
| 15 | fn main() -> Result<(), Box<dyn Error>> { |
| 16 | let ferris = Mascot { |
| 17 | name: "Ferris".to_owned(), |
| 18 | species: "crab".to_owned(), |
| 19 | year_of_birth: 2015, |
| 20 | }; |
| 21 | |
| 22 | let ferris_file = File::create("examples/ferris.cbor")?; |
| 23 | // Write Ferris to the given file. |
| 24 | // Instead of a file you can use any type that implements `io::Write` |
| 25 | // like a HTTP body, database connection etc. |
| 26 | serde_cbor_2::to_writer(ferris_file, &ferris)?; |
| 27 | |
| 28 | let tux_file = File::open("examples/tux.cbor")?; |
| 29 | // Load Tux from a file. |
| 30 | // Serde CBOR performs roundtrip serialization meaning that |
| 31 | // the data will not change in any way. |
| 32 | let tux: Mascot = serde_cbor_2::from_reader(tux_file)?; |
| 33 | |
| 34 | println!("{tux:?}"); |
| 35 | // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 } |
| 36 | |
| 37 | Ok(()) |
| 38 | } |