Skip to main content

substrate_data/wire/binary/
codec.rs

1//! Values to and from the binary form, whole.
2
3use bumpalo::Bump;
4
5use super::writer::START_BYTES;
6use super::{DecodeError, Decoder, Writer};
7use crate::model::borrowed::ValueRef;
8use crate::model::value::Value;
9
10/// `value` in the binary form.
11pub fn encode(value: &Value) -> Vec<u8> {
12    let mut out = Vec::with_capacity(START_BYTES);
13    encode_into(value, &mut out);
14    out
15}
16
17/// `value` in the binary form, appended to `out` (a whole document, header
18/// first): a buffer that is kept and reused grows once.
19pub fn encode_into(value: &Value, out: &mut Vec<u8>) {
20    let mut w = Writer::appending(std::mem::take(out));
21    w.value(value);
22    *out = w.finish();
23}
24
25/// Reads the binary form.
26///
27/// # Errors
28///
29/// [`DecodeError`] when the bytes aren't the binary form.
30pub fn decode(bytes: &[u8]) -> Result<Value, DecodeError> {
31    let mut d = Decoder::open(bytes)?;
32    let v = d.value()?;
33    d.end()?;
34    Ok(v)
35}
36
37/// A document of version 1 or 2 as a version 2 one: what reading an old
38/// file and saving it again does. Nothing is lost: the value read is the
39/// value written, and every value version 1 holds has a version 2 form (a
40/// [`crate::Stream`] is the list of its items, as it is read anywhere
41/// without a schema).
42///
43/// # Errors
44///
45/// [`DecodeError`] when the bytes aren't the binary form; nothing is written then.
46pub fn upgrade(bytes: &[u8]) -> Result<Vec<u8>, DecodeError> {
47    decode(bytes).map(|value| encode(&value))
48}
49
50/// Reads the binary form borrowed: every string points into `bytes`,
51/// lists and maps go in `arena` — nothing is copied.
52///
53/// # Errors
54///
55/// [`DecodeError`] when the bytes aren't the binary form.
56pub fn decode_ref<'a>(bytes: &'a [u8], arena: &'a Bump) -> Result<ValueRef<'a>, DecodeError> {
57    let mut d = Decoder::open(bytes)?;
58    let v = d.value_ref(arena)?;
59    d.end()?;
60    Ok(v)
61}