flow-toolkit 0.1.0-rc.5

Ordinary typed Rust functions and exact native data for Flow Tools, served from a Rust library's one launcher.
Documentation
//! A value of a type only its call fixes, held as its bytes in the value
//! encoding (`abi.md`, *Toolkits*): what a generic Tool's type parameter and
//! a std declaration carried whole are.

use flow_abi::wire::{Shaped, ValueReader, ValueWriter, WireForm};
use flow_abi::{Catalog, DecodeError, EncodeError, Mode};
use flow_types::Type;

use crate::data::LIMITS;

/// A value of a type the call fixes, held as its bytes: a generic Tool's
/// type parameter, as the generated adapter instantiates it, or a std
/// declaration a Rust type carries without modelling it, such as
/// `code.Bundle`.
///
/// It is opaque: a Tool passes it along, stores it and answers with it, and
/// cannot look inside, as a Flow function cannot look inside a value of a
/// type it is generic over. It is read once at the type its position has,
/// and written only where its bytes are a value of the type written.
///
/// Two are equal when their bytes are, which a value's bytes are of it
/// alone. Their order is a byte order and is never Flow's order of the
/// values; it exists so that a `BTreeSet` or `BTreeMap` can hold them. The
/// writer sorts a set's elements and a dictionary's keys by Flow's order,
/// whatever order Rust keeps them in.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Encoded(Vec<u8>);

impl Encoded {
    /// The value `bytes` hold, a value of `ty` in `catalog`.
    ///
    /// # Errors
    ///
    /// When `bytes` are not exactly one value of `ty`.
    pub fn new(catalog: &Catalog, ty: &Type, bytes: Vec<u8>) -> Result<Encoded, DecodeError> {
        flow_abi::decode_bytes(catalog, ty, &bytes, Mode::Rebuild, &LIMITS)?;
        Ok(Encoded(bytes))
    }
}

impl std::fmt::Debug for Encoded {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "Encoded({} bytes)", self.0.len())
    }
}

/// Its form is never read: `#[tool]` declares a type parameter by its
/// place-holder, [`flow_abi::wire::Param`], and the derive of a std
/// declaration writes the declaration's form.
impl Shaped for Encoded {
    const FORM: WireForm = WireForm::Param(0);

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.encoded(ty, &self.0)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.encoded(ty).map(|bytes| Encoded(bytes.to_vec()))
    }
}