Skip to main content

Crate dataport

Crate dataport 

Source
Expand description

Thread-safe ports for typed data, modelled after the ports of SysML v2.

A port is an In (reader), Out (writer) or InOut (reader and writer) access to a value, which it may share with other ports. Named ports are kept in port collections, which a set of macros helps to create.

The crate works in std and in no_std environments with alloc, see Environments. Most commonly used items are in the prelude.

§Ports

A port holds a value of a data type T. The data type is fixed when the port is created and checked at runtime on every access, an access with another type fails with Error::DataType. Every T that is Any, Send, Sync, Debug and Clone can be used, see AnyPortValue.

The port types are aliases of the generic Port<D>, whose direction D decides at compile time which accesses are possible:

port typedirectionaccess traitsaccess
InInputInPortread
OutOutputOutPortwrite
InOutInputOutputInPort, OutPort and InOutPortread, write, replace and take

A port is created without a value by new::<T>() and with a value by with_value(value). Their _parseable variants also store a setter for values given as a string, see Parseable ports.

use dataport::{Error, InOut, InPort, OutPort};

let mut port = InOut::new::<i32>();
let value: Option<i32> = port.try_get()?;
assert_eq!(value, None);

port.try_set(42i32)?;
let value: Option<i32> = port.try_get()?;
assert_eq!(value, Some(42));

// the data type is checked at runtime
assert_eq!(port.try_set(1.5f64), Err(Error::DataType));

§Connecting ports

Ports exchange data by sharing a value. PortCommons::use_from makes a port use the value of another port with the same data type, so afterwards both of them, together with all ports already sharing that value, see the same value. A clone of a port shares the value as well. A port can also use the value of a PortVariant with use_from_variant or of a port in a collection with use_from_collection.

use dataport::{In, InPort, Out, OutPort, PortCommons};

let mut output = Out::new::<i32>();
let mut input = In::new::<i32>();
input.use_from(&output)?;

output.try_set(42i32)?;
let value: Option<i32> = input.try_get()?;
assert_eq!(value, Some(42));

Only the data types are checked when connecting, not the port types. The value the port held before is dropped, unless other ports still share it.

So the port type restricts the accesses through that port, the data flow of the component holding it; it does not protect the shared value. The accesses meant for the initialization and the wiring work for every port type: PortVariant::set_from_str, PortVariant::try_restore and PortVariant::to_in_out.

§Accessing values

There are three ways to access the value of a port:

accessmethodswhen the value is locked
waitingget, set and for InOut replace and takeasync, waits for the unlock
not waitingtry_get and try_setfails with Error::IsLocked
handlePortHandle: read, write, try_read, try_writethe caller locks and holds a guard

The waiting accessors are async and need an executor, any executor will do:

use dataport::{InOut, InOutPort, InPort, OutPort};

let mut port = InOut::with_value(1i32);
port.set(2i32).await?;
assert_eq!(port.replace(3i32).await?, Some(2));

let taken: Option<i32> = port.take().await?;
assert_eq!(taken, Some(3));
let value: Option<i32> = port.get().await?;
assert_eq!(value, None);

get and try_get return a clone of the value. A PortHandle avoids the clone and the repeated type check: the data type is checked once when the handle is created, then the caller locks the value and gets the guard over an Option<T>. While a write guard is alive, all other accesses to the value wait or fail with Error::IsLocked. While a read guard is alive, other reads succeed and only the writing accesses wait or fail.

use dataport::{Error, In, Out, PortCommons};

let output = Out::new::<i32>();
let mut input = In::new::<i32>();
input.use_from(&output)?;

// create the handles after connecting the ports
let writer = output.handle::<i32>()?;
let reader = input.handle::<i32>()?;

*writer.try_write()? = Some(42);
assert_eq!(*reader.try_read()?, Some(42));

// a read guard allows other reads, but no writes
let guard = reader.try_read()?;
assert_eq!(*reader.try_read()?, Some(42));
assert_eq!(writer.try_write().err(), Some(Error::IsLocked));
drop(guard);

A handle keeps the value the port had when the handle was created, connecting the port later does not change the value of the handle. So create handles only after the ports are connected.

§Change tracking

Every value has a sequence number, which is 0 for a port created without a value and 1 for one created with a value. Every change increments it, wrapping around to 1. A change is every set, replace, take and every write lock taken through a handle, whether the value is modified or not. PortCommons::sequence_number returns it, and PortCommons::changed returns a Changed future that completes as soon as the sequence number differs from the one the caller has seen:

use dataport::{InOut, OutPort, PortCommons};

let mut port = InOut::new::<i32>();
let seen = port.sequence_number();
assert_eq!(seen, 0);

port.try_set(42i32)?;
// the port changed since `seen`, so the future completes at once
let seen = port.changed(seen).await;
assert_eq!(seen, 1);

Changes in between are not queued: a task woken by a change reads the latest value. Only a limited number of tasks can wait for the change of one value at the same time, 16 with std and 4 without.

§Port variants

A PortVariant is one of the port types, decided at runtime. It allows to keep ports with different port types and data types together, as the collections do. Its accessors check the port type at runtime, an access the port type does not allow fails with Error::PortType.

use dataport::{Error, PortVariant};

let mut variant = PortVariant::create_out(1i32);
variant.try_set(42i32)?;
assert_eq!(variant.try_get::<i32>(), Err(Error::PortType));

PortVariant::try_snapshot returns a copy of a port with its own value, which PortVariant::try_restore writes back into the shared value:

use dataport::PortVariant;

let mut variant = PortVariant::create_inout(1i32);
let snapshot = variant.try_snapshot()?;
variant.try_set(2i32)?;

variant.try_restore(&snapshot)?;
assert_eq!(variant.try_get::<i32>()?, Some(1));

§Parseable ports

A port created with a _parseable constructor stores a setter that parses a string into the data type with its FromStr implementation. It is used by PortVariant::set_from_str and PortCollection::set_from_str, which are meant for the initialization, e.g. from a configuration file, so they do not wait for a locked value. The setter has to be stored at creation, because later only the port’s value knows the data type.

use dataport::{Error, PortVariant};

let mut variant = PortVariant::create_inout_parseable(0i32);
variant.set_from_str("42")?;
assert_eq!(variant.try_get::<i32>()?, Some(42));
assert_eq!(variant.set_from_str("forty-two"), Err(Error::FromStr));

// without the setter
let mut variant = PortVariant::create_inout(0i32);
assert_eq!(variant.set_from_str("42"), Err(Error::FromStr));

§Port collections

A port collection holds named PortVariants. The name identifies a port, so it has to be unique within its collection.

collectionstorageports can be added and removedorder of the ports
PortArray<S>array of fixed size Snoas created
PortVecvectoryesas created or added
PortMapB-tree mapyessorted by name

The traits split the collection functionality:

The accessors of a collection return the value itself instead of an Option, a port without a value is an Error::NoValueSet.

use dataport::{
    Error, PortCollectionAccessors, PortCollectionAccessorsCommon, create_in_entry, create_out_entry,
    create_port_array,
};

let mut ports = create_port_array!(create_in_entry!("limit", 100i32), create_out_entry!("result", i32))?;

assert!(ports.contains_name("limit"));
assert_eq!(ports.try_get::<i32>("limit")?, 100);

ports.try_set("result", 42i32)?;
// an `Out` port cannot be read
assert_eq!(ports.try_get::<i32>("result"), Err(Error::PortType));

§Creating collections with macros

create_port_array!, create_port_vec! and create_port_map! create a collection from name/port pairs, which the entry macros create: create_in_entry!, create_inout_entry! and create_out_entry!, and their _parseable variants, which create parseable ports. The name is a string literal or an identifier of something that converts into an Arc<str>. The content of the port is given in one of these forms:

entrycreates a port
create_in_entry!("a", i32)for an i32 without a value
create_in_entry!("a", 42i32)with the value, its type is the data type
create_in_entry!("a", i32, 42)with the value, which is an expression of the data type
create_in_entry!("a", i32, "42")with the value parsed from a string or char literal
create_in_entry!("a", i32, &text)with the value parsed from a referenced &str or String variable
create_in_entry!("a", i32, &String::from("42"))with the value parsed from a referenced call result
create_in_entry!("a", i32, "{b}", other)connected to the port b of the collection other
create_in_entry!("a", i32, "{=}", other)connected to the port of the same name a in the collection other

The names in a collection are unique. A name given twice as a string literal is a compile error; names given otherwise are checked when the collection is created, so the collection macros return a Result, which is an Error::AlreadyExists for a name given twice. PortArray::from_array, PortVec::from_array and PortMap::from_array check the same, and ports are added to a PortVec or a PortMap only with PortCollectionMut::add, which refuses an existing name: the collections give no mutable access to their names.

A value parsed from a string and a connection to another collection can fail at runtime, so these entries contain a ?. The surrounding function has to return a Result whose error converts from Error: a value that cannot be parsed is an Error::ParseValue, a missing port an Error::NotFound and a port with another data type an Error::DataType. The collection other is an identifier of a reference to the collection. A name in curly braces starts with a letter and contains only letters, digits, _ and blanks, otherwise the string is parsed as a value.

use dataport::{
    Error, PortCollectionAccessors, create_in_entry, create_inout_entry, create_port_array, create_port_map,
};

fn ports() -> Result<(), Error> {
    let mut parent = create_port_array!(
        create_inout_entry!("speed", f64, 1.5),
        create_inout_entry!("limit", i32, "100"),
    )?;
    let shared = &parent;
    let child = create_port_map!(
        create_in_entry!("speed", f64, "{=}", shared),
        create_in_entry!("max", i32, "{limit}", shared),
    )?;
    assert_eq!(child.try_get::<i32>("max")?, 100);

    // the ports share their values
    parent.try_set("speed", 2.5f64)?;
    assert_eq!(child.try_get::<f64>("speed")?, 2.5);
    Ok(())
}

A value given as a call, a method call or a variable, e.g. String::from("42"), string.as_str() or text, is not parsed but used as the value as it is, see the known issues of dataport_macros. Pass a reference instead, e.g. &String::from("42") or &text.

§Environments

The feature std is enabled by default. Without it the crate is no_std and needs alloc.

The values are behind the async locks of embassy-sync, see RwLock and Mutex, which use the RawMutex:

  • With std each lock has its own reentrant mutex.
  • Without std all locks use a critical section, which is usable between threads and interrupts. The platform has to provide the critical section implementation for the critical-section crate, as e.g. Ariel OS and embassy do.

The shared values are reference counted by an Arc of portable-atomic, so they also work on targets without native atomic operations.

Modules§

prelude
Most commonly used interfaces of dataport.

Macros§

create_in_entry
Creates a name/port pair of an In port.
create_in_entry_parseable
Creates a name/port pair of an In port with a FromStr setter.
create_inout_entry
Creates a name/port pair of an InOut port.
create_inout_entry_parseable
Creates a name/port pair of an InOut port with a FromStr setter.
create_out_entry
Creates a name/port pair of an Out port.
create_out_entry_parseable
Creates a name/port pair of an Out port with a FromStr setter.
create_port_array
Creates a dataport::PortArray from a comma separated list of name/port pairs.
create_port_map
Creates a dataport::PortMap from a comma separated list of name/port pairs.
create_port_vec
Creates a dataport::PortVec from a comma separated list of name/port pairs.

Structs§

Changed
Future returned by PortCommons::changed: completes with the sequence number of the port as soon as it differs from the one the caller has seen.
EmptyPortArray
Provides the empty PortArray for types without ports, which implement the port collection traits.
Input
The direction of a PortHandle of an In port, which may only read.
InputOutput
The direction of a PortHandle of an InOut port, which may read and write.
Output
The direction of a PortHandle of an Out port, which may only write.
Port
A port holding a typed value, the common implementation of the port types In, Out and InOut.
PortArray
A collection of a fixed number S of named PortVariants, in the order they are given.
PortHandle
Type-checked locked reference to the value of a port with data type T. A handle keeps its referenced value even if the port is reconnected or dropped during its lifetime.
PortMap
A collection of named PortVariants sorted by their names.
PortVec
A collection of named PortVariants in the order they are given or added.

Enums§

Error
The errors of port and port collection accesses.
PortVariant
A port of one of the port types In, InOut or Out, decided at runtime.

Statics§

EMPTY_PORT_ARRAY
The EmptyPortArray for types without ports, used by the default methods of PortCollectionProvider.

Traits§

AnyPortValue
The data types a port can hold.
InOutPort
Read and write access to the value of a port with the data type T, implemented by InOut.
InPort
Read access to the value of a port with the data type T, implemented by In and InOut.
OutPort
Write access to the value of a port with the data type T, implemented by Out and InOut.
PortCollection
A collection of named ports. Each port is identified by its name, so the name has to be unique within a certain port collection.
PortCollectionAccessors
Access to the values of the ports of a collection by their names.
PortCollectionAccessorsCommon
Access to the ports of a collection by their names, without the generic accessors of PortCollectionAccessors, so it can be used as a trait object via PortList. It connects ports of the collection to other ports and returns their sequence numbers.
PortCollectionMut
A collection of named ports, to which ports can be added and from which they can be deleted. Each port is identified by its name, so the name has to be unique within a certain port collection.
PortCollectionProvider
A type that owns a collection of ports, e.g. a component with its ports.
PortCollectionProviderMut
A type that owns a collection of ports, to which ports can be added and from which they can be deleted.
PortCommons
Methods common to all ports, whatever their port type: connecting them and tracking their changes.
PortList
The combination of PortCollection and PortCollectionAccessorsCommon, usable as dyn PortList.
Readable
Directions whose PortHandles may read.
Writable
Directions whose PortHandles may write.

Type Aliases§

Arc
A thread safe reference counting pointer. Uses portable-atomic, so it also works on targets without native atomic operations.
BlockingMutex
A mutex for short, synchronous accesses from within a critical section.
In
An input port, providing read-only access to a typed value via InPort.
InHandle
A PortHandle of an In port, which may only read.
InOut
An input/output port, providing read and write access to a typed value via InPort, OutPort and InOutPort.
InOutHandle
A PortHandle of an InOut port, which may read and write.
Mutex
An async mutex, which may be held across .await points.
MutexGuard
The guard of a locked Mutex, releasing the lock when dropped.
Out
An output port, providing write-only access to a typed value via OutPort.
OutHandle
A PortHandle of an Out port, which may only write.
RawMutex
The raw mutex used by all locks. On std each lock has its own reentrant mutex instead of one process-wide critical section.
RwLock
An async reader-writer lock, allowing multiple readers or a single writer.
RwLockReadGuard
The guard of a shared read access to a RwLock, releasing the access when dropped.
RwLockWriteGuard
The guard of an exclusive write access to a RwLock, releasing the access when dropped.