flexbuffers/lib.rs
1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Flexbuffers is a high performance schemaless binary data format designed at Google.
16//! It is complementary to the schema-ed format [Flatbuffers](http://docs.rs/flatbuffers/).
17//! See [Flexbuffer Internals](https://google.github.io/flatbuffers/flatbuffers_internals.html)
18//! for details on the binary format.
19//!
20//! See the examples for usage:
21//! * [Example](https://github.com/google/flatbuffers/blob/master/samples/sample_flexbuffers.rs)
22//! * [Serde Example](https://github.com/google/flatbuffers/blob/master/samples/sample_flexbuffers_serde.rs)
23//!
24//! This rust implementation is in progress and, until the 1.0 release, breaking API changes may
25//! happen between minor versions.
26// TODO(cneo): serde stuff are behind a default-on feature flag
27//             Reader to Json is behind a default-off feature flag
28//             Serializable structs are Pushable
29//             Serde with maps - field names and type names.
30
31// Until flat/flexbuffers is on Rust v1.42, we cannot use the previously unstable matches! macro.
32#![allow(unknown_lints)]
33#![allow(clippy::match_like_matches_macro)]
34
35#[macro_use]
36extern crate bitflags;
37extern crate byteorder;
38#[macro_use]
39extern crate serde_derive;
40extern crate num_enum;
41extern crate serde;
42
43mod bitwidth;
44mod buffer;
45mod builder;
46mod flexbuffer_type;
47mod reader;
48
49pub use bitwidth::BitWidth;
50pub use buffer::Buffer;
51pub use builder::Error as SerializationError;
52pub use builder::{
53    singleton, Builder, BuilderOptions, FlexbufferSerializer, MapBuilder, Pushable, VectorBuilder,
54};
55pub use flexbuffer_type::FlexBufferType;
56pub use reader::Error as ReaderError;
57pub use reader::{DeserializationError, MapReader, Reader, ReaderIterator, VectorReader};
58use serde::{Deserialize, Serialize};
59
60mod private {
61    pub trait Sealed {}
62}
63
64/// Serialize as a flexbuffer into a vector.
65pub fn to_vec<T: Serialize>(x: T) -> Result<Vec<u8>, SerializationError> {
66    let mut s = FlexbufferSerializer::new();
67    x.serialize(&mut s)?;
68    Ok(s.take_buffer())
69}
70
71/// Deserialize a type from a flexbuffer.
72pub fn from_slice<'de, T: Deserialize<'de>>(buf: &'de [u8]) -> Result<T, DeserializationError> {
73    let r = Reader::get_root(buf)?;
74    T::deserialize(r)
75}
76
77/// Deserialize a type from a flexbuffer.
78pub fn from_buffer<'de, T: Deserialize<'de>, B: Buffer>(
79    buf: &'de B,
80) -> Result<T, DeserializationError> {
81    let r = Reader::get_root(buf as &'de [u8])?;
82    T::deserialize(r)
83}
84
85/// This struct, when pushed will be serialized as a `FlexBufferType::Blob`.
86///
87/// A `Blob` is a variable width `length` followed by that many bytes of data.
88#[derive(Debug, PartialEq, Eq)]
89pub struct Blob<B>(pub B);
90
91impl<B: Buffer> Clone for Blob<B> {
92    fn clone(&self) -> Self {
93        Blob(self.0.shallow_copy())
94    }
95}
96
97/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectUInt`.
98///
99/// It is an unsigned integer stored by reference in the flexbuffer. This can reduce the
100/// size of vectors and maps containing the `IndirectUInt`.
101#[derive(Debug, Copy, Clone, PartialEq, Eq)]
102pub struct IndirectUInt(pub u64);
103
104/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectInt`.
105///
106/// It is a signed integer stored by reference in the flexbuffer. This can reduce the
107/// size of vectors and maps containing the `IndirectInt`.
108#[derive(Debug, Copy, Clone, PartialEq, Eq)]
109pub struct IndirectInt(pub i64);
110
111/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectFloat`.
112///
113/// It is a floating point stored by reference in the flexbuffer. This can reduce the
114/// size of vectors and maps containing the `IndirectFloat`.
115#[derive(Debug, Copy, Clone, PartialEq)]
116pub struct IndirectFloat(pub f64);