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::{DecodeError, Decoder, Writer};
6use crate::model::borrowed::ValueRef;
7use crate::model::value::Value;
8
9/// `value` in the binary form.
10pub fn encode(value: &Value) -> Vec<u8> {
11    let mut w = Writer::new();
12    w.value(value);
13    w.finish()
14}
15
16/// Reads the binary form.
17///
18/// # Errors
19///
20/// [`DecodeError`] when the bytes aren't the binary form.
21pub fn decode(bytes: &[u8]) -> Result<Value, DecodeError> {
22    let mut d = Decoder::open(bytes)?;
23    let v = d.value()?;
24    d.end()?;
25    Ok(v)
26}
27
28/// Reads the binary form borrowed: every string points into `bytes`,
29/// lists and maps go in `arena` — nothing is copied.
30///
31/// # Errors
32///
33/// [`DecodeError`] when the bytes aren't the binary form.
34pub fn decode_ref<'a>(bytes: &'a [u8], arena: &'a Bump) -> Result<ValueRef<'a>, DecodeError> {
35    let mut d = Decoder::open(bytes)?;
36    let v = d.value_ref(arena)?;
37    d.end()?;
38    Ok(v)
39}