1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
#![cfg_attr(test, feature(test))]
#![forbid(unsafe_code)]
//! Bitcode is a crate for encoding and decoding using a tinier
//! binary serialization strategy. You can easily go from having
//! an object in memory, quickly serialize it to bytes, and then
//! deserialize it back just as fast!
//!
//! The format is not necessarily stable between versions. If you want
//! a stable format, consider [bincode](https://docs.rs/bincode/latest/bincode/).
//!
//! ### Usage
//!
//! ```edition2021
//! // The object that we will serialize.
//! let target: Vec<String> = vec!["a".to_owned(), "b".to_owned(), "c".to_owned()];
//!
//! let encoded: Vec<u8> = bitcode::serialize(&target).unwrap();
//! let decoded: Vec<String> = bitcode::deserialize(&encoded).unwrap();
//! assert_eq!(target, decoded);
//! ```
// Actually required see https://doc.rust-lang.org/beta/unstable-book/library-features/test.html
#[cfg(test)]
extern crate core;
#[cfg(test)]
extern crate test;
pub use buffer::Buffer;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, Formatter};
mod buffer;
mod de;
mod nightly;
mod read;
mod ser;
mod word;
mod word_buffer;
mod write;
#[cfg(all(test, not(miri)))]
mod benches;
#[cfg(test)]
mod bit_buffer;
#[cfg(test)]
mod tests;
/// Serializes a `T:` [`Serialize`] into a [`Vec<u8>`].
///
/// **Warning:** The format is subject to change between versions.
pub fn serialize<T: ?Sized>(t: &T) -> Result<Vec<u8>>
where
T: Serialize,
{
Ok(Buffer::new().serialize(t)?.to_vec())
}
/// Deserializes a [`&[u8]`][`prim@slice`] into an instance of `T:` [`Deserialize`].
///
/// **Warning:** The format is subject to change between versions.
pub fn deserialize<'a, T>(bytes: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
Buffer::new().deserialize(bytes)
}
impl Buffer {
/// Serializes a `T:` [`Serialize`] into a [`&[u8]`][`prim@slice`]. Can reuse the buffer's
/// allocations.
///
/// Even if you call `to_vec` on the [`&[u8]`][`prim@slice`], it's still more efficient than
/// [`serialize`].
///
/// **Warning:** The format is subject to change between versions.
pub fn serialize<T: ?Sized>(&mut self, t: &T) -> Result<&[u8]>
where
T: Serialize,
{
ser::serialize_internal(&mut self.0, t)
}
/// Deserializes a [`&[u8]`][`prim@slice`] into an instance of `T:` [`Deserialize`]. Can reuse
/// the buffer's allocations.
///
/// **Warning:** The format is subject to change between versions.
pub fn deserialize<'a, T>(&mut self, bytes: &'a [u8]) -> Result<T>
where
T: Deserialize<'a>,
{
de::deserialize_internal(&mut self.0, bytes)
}
}
/// (De)serialization errors.
///
/// # Debug mode
///
/// In debug mode, the error contains a reason.
///
/// # Release mode
///
/// In release mode, the error is a zero-sized type for efficiency.
#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub struct Error(ErrorImpl);
#[cfg(not(debug_assertions))]
type ErrorImpl = ();
#[cfg(debug_assertions)]
type ErrorImpl = E;
impl Error {
/// Replaces an invalid message. E.g. read_variant_index calls read_len but converts
/// `E::Invalid("length")` to `E::Invalid("variant index")`.
pub(crate) fn map_invalid(self, _s: &'static str) -> Self {
#[cfg(debug_assertions)]
return Self(match self.0 {
E::Invalid(_) => E::Invalid(_s),
_ => self.0,
});
#[cfg(not(debug_assertions))]
self
}
pub(crate) fn same(&self, other: &Self) -> bool {
self.0 == other.0
}
}
/// Inner error that can be converted to [`Error`] with [`E::e`].
#[derive(Debug, PartialEq)]
pub(crate) enum E {
#[cfg(debug_assertions)]
Custom(String),
Eof,
ExpectedEof,
Invalid(&'static str),
NotSupported(&'static str),
}
impl E {
fn e(self) -> Error {
#[cfg(debug_assertions)]
return Error(self);
#[cfg(not(debug_assertions))]
Error(())
}
}
type Result<T> = std::result::Result<T, Error>;
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
#[cfg(debug_assertions)]
return Display::fmt(&self.0, f);
#[cfg(not(debug_assertions))]
f.write_str("bitcode error")
}
}
impl Display for E {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
#[cfg(debug_assertions)]
Self::Custom(s) => write!(f, "custom: {s}"),
Self::Eof => write!(f, "eof"),
Self::ExpectedEof => write!(f, "expected eof"),
Self::Invalid(s) => write!(f, "invalid {s}"),
Self::NotSupported(s) => write!(f, "{s} is not supported"),
}
}
}
impl std::error::Error for Error {}
impl serde::ser::Error for Error {
fn custom<T>(_msg: T) -> Self
where
T: Display,
{
#[cfg(debug_assertions)]
return Self(E::Custom(_msg.to_string()));
#[cfg(not(debug_assertions))]
Self(())
}
}
impl serde::de::Error for Error {
fn custom<T>(_msg: T) -> Self
where
T: Display,
{
#[cfg(debug_assertions)]
return Self(E::Custom(_msg.to_string()));
#[cfg(not(debug_assertions))]
Self(())
}
}