An ε-copy serialization/deserialization framework for Rust
An ε-copy serialization/deserialization framework for Rust
ε-serde is a Rust framework for ε-copy serialization and deserialization.
Large immutable data structures need time to be deserialized using the [serde] approach. A possible solution for this problem is given by frameworks such as [Abomonation], [rkyv], and [zerovec], which provide zero-copy deserialization: the stream of bytes serializing the data structure can be used directly as a Rust structure. In particular, this approach makes it possible to map into memory an on-disk data structure, making it available instantly. It also makes it possible to load the data structure in a memory region with particular attributes, such as transparent huge pages on Linux. Even when using standard memory load and deserialization happen much faster as the entire structure can be loaded with a single read operation.
ε-serde has the same goals as the zero-copy frameworks above but provides different tradeoffs.
Since in these data structures typically most of the data is given by large chunks of memory in the form of slices or vectors, at deserialization time one can build quickly a proper Rust structure whose referenced memory, however, is not copied. We call this approach ε-copy deserialization, as typically a minuscule fraction of the serialized data is copied to build the structure. The result is similar to that of the frameworks above, but the performance of the deserialized structure will be identical to that of a standard, in-memory Rust structure, as references are resolved at deserialization time.
We provide procedural macros implementing serialization and deserialization
methods, basic (de)serialization for primitive types, vectors, etc., convenience
memory-mapping methods based on [mmap_rs], and a [MemCase] structure that
couples a deserialized instance with its backend (e.g., a slice of memory or a
memory-mapped region). A [MemCase] provides an [uncase] method that yields
references to the deserialized instance it contains. Moreover, a [MemCase] can
also contain an owned instance, making it possible to use the same code for both
owned and, say, memory-mapped instances.
Tommaso Fontana, while working at INRIA under the supervision of Stefano
Zacchiroli, came up with the basic idea for ε-serde, that is, replacing
instances with equivalent references. The code was developed jointly with
Sebastiano Vigna, who came up with the [MemCase] and the
[ZeroCopy]/[DeepCopy] logic. Valentin Lorentz joined later, providing
major improvements in soundness.
These are the main limitations you should be aware of before choosing to use ε-serde:
Your types cannot contain references. For example, you cannot use ε-serde on a tree. (You can actually have some references to zero-copy data though—see [this example].)
While we provide procedural macros that implement serialization and
deserialization, they require that your type is written and used in a specific
way for ε-copy deserialization to work properly; in particular, the fields you
want to ε-copy must contain type parameters implementing [DeserInner], to
which a [deserialization type] is associated, and that will be replaced by
such a type. For example, we provide implementations for Vec/Box,
where T is zero-copy, or String/Box, which have deserialization
associated type &[T] or &str, respectively. Vectors and boxed slices whose
elements are not zero-copy will be deserialized recursively in memory
instead.
After deserialization of an instance of type T, you will obtain an instance
of a deserialization associated type [DeserType], which is just an
instance of T with different values for the type parameters (e.g.,
&[usize] instead of Vec), and which will usually reference the
underlying serialized support (e.g., a memory-mapped region); hence the need
for a lifetime. If you need to store the deserialized instance in a field of a
new structure you will need to couple permanently the instance with its
serialization support, which is obtained by putting it in a [MemCase] using
the convenience methods [Deserialize::load_mem], [Deserialize::read_mem],
[Deserialize::load_mmap], [Deserialize::read_mmap], and
[Deserialize::mmap].
You must write impl blocks that work both for T and for
DeserType. For example, if you have a field of type Vec, you will
get a field of type &[T] after deserialization, so you must write your code
in a way that works for both types (e.g., by using AsRef).
No validation or padding cleaning is performed on (de)serialized instances. If you plan to serialize data and distribute it, you must take care of these issues.
The serialized format is endianness-dependent.
Almost instant deserialization with minimal allocation provided that you designed your type following the ε-serde guidelines or that you use standard types.
The instance you get by deserialization has essentially the same type as the one you serialized, except that type parameters will be replaced by their deserialization associated type (e.g., vectors will become references to slices). This is not the case with [rkyv], which requires you to reimplement all methods on a new, different deserialization type, in which, in particular, all primitive types are replaced with [rkyv]'s endianness-specific counterparts.
The structure you get by deserialization has exactly the same performance as the structure you serialized. This is not the case with [zerovec] or [rkyv], which have to resolve relative addressing.
You can serialize instances containing references to slices, or even exact-size iterators, and they will be deserialized as if you had written a vector. It is thus possible to serialize instances larger than the available memory, and later map them into memory.
You can deserialize from read-only supports, as all dynamic information generated at deserialization time is stored in newly allocated memory. This is not the case with [Abomonation].
Let us start with the simplest case: data that can be zero-copy deserialized. In this case, we serialize an array of a thousand zeros, and get back a reference to such an array:
…Note how we serialize an array, but we deserialize a reference. The reference
points inside b, so there is no copy performed. The call to
[deserialize_full] creates a new array instead. The fourth call maps the data
structure into memory and returns a [MemCase] that can be used to get
a reference to the array; moreover, the [MemCase] can be passed to other
functions or stored in a structure field, as it contains both the structure and
the memory-mapped region that supports it.
The type alias [DeserType] can be used to derive the deserialization type
associated with a type. It contains a lifetime, which is the lifetime of the
memory region containing the serialized data. When deserializing into a
[MemCase], however, the lifetime is 'static, as [MemCase] is an owned
type.
Zero-copy deserialization is not that interesting because it can be applied only
to data whose memory layout and size are fixed and known at compile time. This
time, let us serialize a Vec containing a thousand zeros: ε-serde will
deserialize its deserialization associated type, which is a reference to a
slice.
…Note how we serialize a vector, but we deserialize a reference to a slice; the
same would happen when serializing a boxed slice; in fact, vectors and boxed
slices are interchangeable. The reference points inside b, so there is very
little copy performed (in fact, just a pointer and the length of the slice). All
this is because usize is a zero-copy type. Note also that we use the
convenience method [Deserialize::load_full].
If your code must work both with the original and the deserialized version,
however, it must be written for a trait that is implemented by both types, such
as AsRef.
You can define your types to be zero-copy, in which case they will work like
usize in the previous examples. This requires the structure to be made of
zero-copy fields, and to be annotated with #[epserde(zero_copy)] and #[repr(C)]
(which means that you will lose the possibility that the compiler reorders the
fields to optimize memory usage):
…If a type is not zero-copy, instead, vectors/boxed slices will be always deserialized into vectors/boxed slices.
If you define a type that satisfies the requirements for being zero-copy, but
has no annotation, ε-serde will cause a compilation error. You must annotate the
type with either #[epserde(zero_copy)] or #[epserde(deep_copy)] to silence the
error.
More flexibility can be obtained by defining types with fields whose types are defined by parameters. In this case, ε-serde will deserialize instances of the type replacing its type parameters with the deserialization associated type.
Let us design a structure that will contain an integer, which will be copied, and a vector of integers that we want to ε-copy:
…Note how the field originally containing a Vec now contains a
&[isize] (this replacement is generated automatically). The reference points
inside b, so there is no need to copy the field. Nonetheless, deserialization
creates a new structure MyStruct, ε-copying the original data. The second call
creates a full copy instead. We can write methods for our structure that will
work for the ε-copied version: we just have to take care that they are defined
in a way that will work both on the original type parameter and on its
deserialization associated type; we can also use type to reduce the clutter:
…It is important to note that the derive code replaces every occurrence of a type parameter with its associated (de)serialization type. The substitution is uniform across the structure, so the same parameter cannot end up in two different forms in the deserialization type. For example, the following code will not compile:
# use epserde::prelude::*;
# fn main() -> Result> {
#[derive(Epserde, Debug, PartialEq)]
struct MyStructParam {
id: isize,
data: A,
vec: Vec
}
# Ok(())
# }The error reports that the trait bound A: CopyType is not satisfied: the
derive can substitute A consistently in both fields only when it knows
whether A is deep-copy or zero-copy, because Vec's deserialization type
depends on that.
Adding a bound on A resolves the issue:
# use epserde::prelude::*;
# fn main() -> Result> {
#[derive(Epserde, Debug, PartialEq)]
struct MyStructParam {
id: isize,
data: A,
vec: Vec
}
# Ok(())
# }Alternatively, when you want a specific field's type to stay verbatim in the
deserialization type (no substitution inside it, full-copy deserialization),
mark that field with the #[epserde(force_full_copy)]
attribute.
Note that adding the bound A: ZeroCopy will not work—the derive should replace
Vec with &[A] in the deserialization type, but that is incompatible
with the syntax of the type (a specific error will be issued).
Replacement happens recursively:
# use epserde::prelude::*;
#[derive(Epserde, Debug, PartialEq)]
struct MyStructRec {
data: Vec,
}
// Create a structure where A is a Vec
let s = MyStructRec { data: vec![vec![0, 1, 2, 3], vec![4, 5, 6, 7]] };
// Serialize it
let mut file = std::env::temp_dir();
file.push("serialized5");
unsafe { s.store(&file)? };
// Load the serialized form in a buffer
let b = std::fs::read(&file)?;
let t: MyStructRec = unsafe { >::deserialize_eps(b.as_ref())? };
assert_eq!(s.data.len(), t.data.len());
assert_eq!(&s.data[0], t.data[0]);
assert_eq!(&s.data[1], t.data[1]No open issues yet, or sync has not completed.