databuf/lib.rs
1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3// #![cfg_attr(feature = "nightly", feature(min_specialization))]
4
5pub use databuf_derive::*;
6/// contains configuration options.
7pub mod config;
8/// This module defines the error types.
9pub mod error;
10/// This module provides types for encoding and decoding variable-length integers
11pub mod var_int;
12
13mod record;
14mod types;
15mod utils;
16
17use std::{io, io::Write};
18
19/// It is an alias for a boxed [std::error::Error].
20pub type Error = Box<dyn std::error::Error + Send + Sync>;
21
22/// It is an alias for a `Result<T, Error>` type.
23///
24/// `Error` is an alias for boxed [std::error::Error] that may occur during [Decode::decode] operation.
25pub type Result<T, E = Error> = std::result::Result<T, E>;
26
27/// This trait used to serialize the data structure into binary format.
28pub trait Encode {
29 /// Serialize the data into binary format.
30 fn encode<const CONFIG: u16>(&self, _: &mut (impl Write + ?Sized)) -> io::Result<()>;
31
32 /// This is a convenient method used to encode a value into binary data and return it as a [Vec<u8>].
33 ///
34 /// ### Example
35 ///
36 /// ```
37 /// use databuf::{Encode, config::num::LE};
38 ///
39 /// #[derive(Encode)]
40 /// struct FooBar {
41 /// foo: u8,
42 /// bar: [u8; 2],
43 /// }
44 /// let bytes = FooBar { foo: 1, bar: [2, 3] }.to_bytes::<LE>();
45 /// assert_eq!(bytes, vec![1, 2, 3]);
46 /// ```
47 #[inline]
48 fn to_bytes<const CONFIG: u16>(&self) -> Vec<u8> {
49 let mut vec = Vec::new();
50 self.encode::<CONFIG>(&mut vec).unwrap();
51 vec
52 }
53}
54
55/// This trait used to deserialize the data structure from binary format.
56pub trait Decode<'de>: Sized {
57 /// Deserialize the data from binary format.
58 fn decode<const CONFIG: u16>(_: &mut &'de [u8]) -> Result<Self>;
59
60 /// This is a convenient method used to decode a value from slice.
61 ///
62 /// ### Example
63 ///
64 /// ```
65 /// use databuf::{Decode, config::num::LE};
66 ///
67 /// #[derive(Decode, PartialEq, Debug)]
68 /// struct FooBar {
69 /// foo: u8,
70 /// bar: [u8; 2],
71 /// }
72 ///
73 /// let foobar = FooBar::from_bytes::<LE>(&[1, 2, 3]).unwrap();
74 /// assert_eq!(foobar, FooBar { foo: 1, bar: [2, 3] });
75 /// ```
76 #[inline]
77 fn from_bytes<const CONFIG: u16>(bytes: &'de [u8]) -> Result<Self> {
78 let mut reader = bytes;
79 Decode::decode::<CONFIG>(&mut reader)
80 }
81}
82
83/// Instead of borrowing the data returns owned value.
84///
85/// This trait is automatically implemented for any type that implements the [Decode] trait.
86pub trait DecodeOwned: for<'de> Decode<'de> {}
87impl<T> DecodeOwned for T where T: for<'de> Decode<'de> {}