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/// Reads the binary form borrowed: every string points into `bytes`,
38/// lists and maps go in `arena` — nothing is copied.
39///
40/// # Errors
41///
42/// [`DecodeError`] when the bytes aren't the binary form.
43pub fn decode_ref<'a>(bytes: &'a [u8], arena: &'a Bump) -> Result<ValueRef<'a>, DecodeError> {
44    let mut d = Decoder::open(bytes)?;
45    let v = d.value_ref(arena)?;
46    d.end()?;
47    Ok(v)
48}