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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
#![allow(incomplete_features)] #![feature(const_generics)] //! # binserde //! //! A crate similar to serde, but specialized for serializing into a compact //! binary format, including features like string deduplication. //! //! *This crate is very WIP.* Features currently not implemented but planned //! include incremental versioning support so that old formats can still be //! loaded when the data format changes, deduplication of arbitrary data //! structures, and explicit tagging (writing a struct or enum as a set of //! key/value pairs instead of serializing the items in order of declaration, //! for higher resistance to format changes at the expense of output size) //! //! ## Usage //! //! ``` //! use std::fs::File; //! use std::io::BufReader; //! //! #[derive(BinSerialize, BinDeserialize, Eq, PartialEq)] //! struct MyData { //! v1: String, //! v2: Option<usize>, //! } //! //! let my_data = MyData { //! v1: "Some Text".to_string(), //! v2: Some(12415165), //! }; //! //! let vec = binserde::serialize(&my_data).unwrap(); //! //! let copy_of_my_data: MyData = binserde::deserialize(&vec).unwrap(); //! //! assert_eq!(my_data, copy_of_my_data); //! ``` //! //! ## Macro Attributes //! //! `#[derive(BinSerialize)]` and `#[derive(BinDeserialize)]` allows using //! attributes on the type itself and its fields to control (de)serialization. //! //! ### `#[binserde(skip)]` //! //! Valid for: fields //! //! Skips the field when serializing. When deserializing, uses //! [`Default::default()`] instead of reading from the stream to fill the field. //! //! ### `#[binserde(no_dedup)]` //! //! Valid for: fields //! //! Turns off deduplication for this field. See [Deduplication] for more //! information about how it works. //! //! ### `#[binserde(index = n)]` //! //! Valid for: fields //! //! **not implemented** //! //! Moves the field and all following fields to the specified position `n` when //! serializing, shifting everything originally after that position to the //! right. //! //! #### Example: //! //! ``` //! #[derive(BinSerialize)] //! struct S { //! w: u8, //! x: u8, //! #[binserde(index = 0)] //! y: u8, //! z: u8, //! } //! //! let vec = binserde::serialize(&S { w: 0, x: 1, y: 2, z: 3 }); //! //! assert_eq!(&[2, 3, 0, 1], &vec); //! ``` //! //! The attribute moved `y` and `z` into position 0, pushing `w` and `x` back to //! positions 2 and 3 respectively. //! //! The attribute can be applied on more than one field, in which case moving //! operations will be evaluated from top to bottom. That means, the following //! struct serializes in the order z, x, y, w and not x, y, z, w or any other //! order: //! //! ``` //! #[derive(BinSerialize)] //! struct S { //! w: u8, //! #[binserde(index = 0)] //! x: u8, //! y: u8, //! #[binserde(index = 0)] //! z: u8, //! } //! ``` //! //! # Deduplication //! //! Deduplication is currently only implemented for strings. It works by taking //! any [`String`] or [`str`] that is serialized using its [`BinSerializer`] //! implementation and adds it to a seperate list which is written to the //! beginning of the buffer given to [`serialize`] (or an equivalent function, //! after which the actual data follows. In that data, the string is replaced by //! a `usize` pointing to the index in the string list. Effectively, a //! deduplicated data structure gets transformed from this: //! //! ``` //! struct S { //! s1: String, //! s2: String, //! strs: Vec<String>, //! something_else: u32, //! } //! ``` //! //! to this: //! //! ``` //! struct S1 { //! strings: Vec<String>, //! s1: usize, //! s2: usize, //! strs: Vec<usize>, //! something_else: u32, //! } //! ``` //! //! when serializing. This can have a major impact on the resulting size of the //! serialized data structure when multiple occurrences of the same string //! appear. //! extern crate self as binserde; use std::fmt::Display; use std::io; use std::io::{Cursor, Read, Write}; use std::num::TryFromIntError; use std::string::FromUtf8Error; use thiserror::Error; pub use binserde_derive::{BinDeserialize, BinSerialize}; use de::BinDeserializeOwned; pub use de::{BinDeserialize, BinDeserializer}; use dedup::DedupContext; pub use ser::{BinSerialize, BinSerializer}; pub use serde::Mode; use crate::de::BinDeserializerBase; use crate::ser::{BinSerializerBase, PrescanSerializer}; pub mod de; pub mod dedup; pub mod ser; pub mod serde; mod serdeimpl; pub mod try_iter; mod varint; mod write_ext; pub mod util; pub fn serialize<T>(value: &T) -> Result<Vec<u8>> where T: BinSerialize + ?Sized, { serialize_with(value, Mode::default()) } pub fn serialize_into<W, T>(pipe: W, value: &T) -> Result<()> where W: Write, T: BinSerialize + ?Sized, { serialize_with_into(pipe, value, Mode::default()) } pub fn serialize_with<T>(value: &T, mode: Mode) -> Result<Vec<u8>> where T: BinSerialize + ?Sized, { let mut buf = Cursor::new(Vec::new()); serialize_with_into(&mut buf, value, mode)?; Ok(buf.into_inner()) } pub fn serialize_with_into<W, T>(mut pipe: W, value: &T, mode: Mode) -> Result<()> where W: Write, T: BinSerialize + ?Sized, { if mode.use_dedup { let mut ps = PrescanSerializer::new().with_mode(mode); value.serialize(&mut ps)?; ps.dedup().write_to(&mut pipe)?; } let mut serializer = BinSerializerBase::new(pipe).with_mode(mode); value.serialize(&mut serializer)?; Ok(()) } pub fn deserialize<T>(buf: &[u8]) -> Result<T> where T: BinDeserializeOwned, { deserialize_with(buf, Mode::default()) } pub fn deserialize_with<T>(buf: &[u8], mode: Mode) -> Result<T> where T: BinDeserializeOwned, { deserialize_with_from(Cursor::new(buf), mode) } pub fn deserialize_from<R, T>(pipe: R) -> Result<T> where R: Read, T: BinDeserializeOwned, { deserialize_with_from(pipe, Mode::default()) } pub fn deserialize_with_from<R, T>(mut pipe: R, mode: Mode) -> Result<T> where R: Read, T: BinDeserializeOwned, { let context = if mode.use_dedup { DedupContext::read_from(&mut pipe)? } else { DedupContext::new() }; let deserializer = BinDeserializerBase::new(pipe, &context).with_mode(mode); T::deserialize(deserializer) } pub fn deserialize_in_place<R, T>(target: &mut T, mut pipe: R, mode: Mode) -> Result<()> where R: Read, T: BinDeserializeOwned, { let context = if mode.use_dedup { DedupContext::read_from(&mut pipe)? } else { DedupContext::new() }; let deserializer = BinDeserializerBase::new(pipe, &context).with_mode(mode); target.deserialize_in_place(deserializer) } pub type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug, Error)] pub enum Error { #[error("I/O error: {0}")] Io(#[from] io::Error), #[error("string too long")] TryFromInt(#[from] TryFromIntError), #[error("invalid UTF-8 string")] InvalidUtf8(#[from] FromUtf8Error), #[error("indexed string out of range: {0}")] StrOutOfRange(usize), #[error("{0}")] Custom(String), } impl Error { pub fn custom<S: Display>(s: S) -> Self { Error::Custom(s.to_string()) } } #[test] fn serialize_inline_test() { use std::collections::{HashMap, HashSet}; #[derive(Debug, PartialEq, Eq, BinSerialize, BinDeserialize)] struct Test { vec: Vec<Test1>, map_set: HashMap<String, HashSet<String>>, test2: Vec<Test2>, } #[derive(Debug, PartialEq, Eq, BinSerialize, BinDeserialize)] struct Test1(String, i32); #[derive(Debug, PartialEq, Eq, BinSerialize, BinDeserialize)] enum Test2 { A, B(i32, i32, i32), C { thing: i64 }, } let s = Test { vec: vec![ Test1("yyyyyyyyyyyyyyyyyy".to_string(), 4), Test1("a".to_string(), 4), Test1("yyyyyyyyyyyyyyyyyy".to_string(), 4), Test1("ab".to_string(), 4), Test1("abc".to_string(), 4), Test1("abcd".to_string(), 4), ], map_set: vec![("a", vec!["a", "b", "c"]), ("a1", vec!["a1", "b1", "c1"])] .into_iter() .map(|el| { ( el.0.to_string(), el.1.into_iter().map(|el| el.to_string()).collect(), ) }) .collect(), test2: vec![ Test2::A, Test2::B(1, 1992323, 5), Test2::C { thing: 23456788765432, }, ], }; { let mode = Mode::dedup(); let buf = serialize_with(&s, mode).expect("failed to serialize"); println!("{:02X?}", buf); let s1: Test = deserialize_with(&buf, mode).expect("failed to deserialize"); assert_eq!(s, s1); } { let buf = serialize(&s).expect("failed to serialize"); println!("{:02X?}", buf); let s1: Test = deserialize(&buf).expect("failed to deserialize"); assert_eq!(s, s1); } } #[test] fn serialize_constant_output() { assert_eq!(&[3, 97, 98, 99], &*serialize(&"abc").unwrap()); assert_eq!(&[0xFF], &*serialize(&true).unwrap()); assert_eq!(&[0x00], &*serialize(&false).unwrap()); assert_eq!( &[0x03, 0x02, 0x05, 0x45], &*serialize_with( &[1i16, -3i16, -35i16] as &[i16], Mode::default().with_fixed_size_use_varint(true) ) .unwrap() ); }