[go: up one dir, main page]

tora/
lib.rs

1//! # tora
2//!
3//! Tora is a byte-based serialization and deserialization library.
4//!
5//! ```
6//! use std::io;
7//! use std::io::Cursor;
8//!
9//! use tora::{ReadEnum, ReadStruct, WriteEnum, WriteStruct};
10//! use tora::read::ToraRead;
11//! use tora::write::ToraWrite;
12//!
13//! #[derive(Debug, PartialEq, ReadEnum, WriteEnum)]
14//! #[type_variant_id(i64)]
15//! enum Packet {
16//!     Ping,
17//!     PlayerJoin(PlayerJoin),
18//!     PlayerMove {
19//!         id: u8,
20//!         destination: [f64; 3],
21//!     },
22//! }
23//!
24//! #[derive(Debug, PartialEq, ReadStruct, WriteStruct)]
25//! struct PlayerJoin {
26//!     id: u8,
27//!     username: Option<String>
28//! }
29//!
30//! fn main() -> io::Result<()> {
31//!     let se = Packet::PlayerMove { id: 5, destination: [1.1, 2.4, 3.1] };
32//!
33//!     let mut bytes = Vec::new();
34//!     bytes.writes(&se)?;
35//!
36//!     let mut cursor = Cursor::new(bytes);
37//!     let de = cursor.reads()?;
38//!
39//!     assert_eq!(se, de);
40//!     Ok(())
41//! }
42//! ```
43
44use std::fs::File;
45use std::io;
46use std::path::Path;
47
48#[cfg(feature = "tora_derive")]
49pub use tora_derive::*;
50
51use crate::read::{FromReader, ToraRead};
52use crate::write::{SerializeIo, ToraWrite};
53
54pub mod read;
55pub mod write;
56
57/// Serialize the content and write it to the file at the given path.
58pub fn write_to_file<P, C>(path: P, content: &C) -> io::Result<()>
59where
60    P: AsRef<Path>,
61    C: SerializeIo,
62{
63    let mut file = File::create(path)?;
64    file.writes(content)
65}
66
67/// Try to deserialize [T] from the file at the given path.
68pub fn read_from_file<T, P>(path: P) -> io::Result<T>
69where
70    P: AsRef<Path>,
71    T: FromReader,
72{
73    let mut file = File::open(path)?;
74    file.reads()
75}