flow_toolkit/encoded.rs
1//! A value of a type only its call fixes, held as its bytes in the value
2//! encoding (`abi.md`, *Toolkits*): what a generic Tool's type parameter and
3//! a std declaration carried whole are.
4
5use flow_abi::wire::{Shaped, ValueReader, ValueWriter, WireForm};
6use flow_abi::{Catalog, DecodeError, EncodeError, Mode};
7use flow_types::Type;
8
9use crate::data::LIMITS;
10
11/// A value of a type the call fixes, held as its bytes: a generic Tool's
12/// type parameter, as the generated adapter instantiates it, or a std
13/// declaration a Rust type carries without modelling it, such as
14/// `code.Bundle`.
15///
16/// It is opaque: a Tool passes it along, stores it and answers with it, and
17/// cannot look inside, as a Flow function cannot look inside a value of a
18/// type it is generic over. It is read once at the type its position has,
19/// and written only where its bytes are a value of the type written.
20///
21/// Two are equal when their bytes are, which a value's bytes are of it
22/// alone. Their order is a byte order and is never Flow's order of the
23/// values; it exists so that a `BTreeSet` or `BTreeMap` can hold them. The
24/// writer sorts a set's elements and a dictionary's keys by Flow's order,
25/// whatever order Rust keeps them in.
26#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct Encoded(Vec<u8>);
28
29impl Encoded {
30 /// The value `bytes` hold, a value of `ty` in `catalog`.
31 ///
32 /// # Errors
33 ///
34 /// When `bytes` are not exactly one value of `ty`.
35 pub fn new(catalog: &Catalog, ty: &Type, bytes: Vec<u8>) -> Result<Encoded, DecodeError> {
36 flow_abi::decode_bytes(catalog, ty, &bytes, Mode::Rebuild, &LIMITS)?;
37 Ok(Encoded(bytes))
38 }
39}
40
41impl std::fmt::Debug for Encoded {
42 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 write!(formatter, "Encoded({} bytes)", self.0.len())
44 }
45}
46
47/// Its form is never read: `#[tool]` declares a type parameter by its
48/// place-holder, [`flow_abi::wire::Param`], and the derive of a std
49/// declaration writes the declaration's form.
50impl Shaped for Encoded {
51 const FORM: WireForm = WireForm::Param(0);
52
53 fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
54 out.encoded(ty, &self.0)
55 }
56
57 fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
58 input.encoded(ty).map(|bytes| Encoded(bytes.to_vec()))
59 }
60}