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 type | direction | access traits | access |
|---|---|---|---|
In | Input | InPort | read |
Out | Output | OutPort | write |
InOut | InputOutput | InPort, OutPort and InOutPort | read, 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:
| access | methods | when the value is locked |
|---|---|---|
| waiting | get, set and for InOut replace and take | async, waits for the unlock |
| not waiting | try_get and try_set | fails with Error::IsLocked |
| handle | PortHandle: read, write, try_read, try_write | the 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.
| collection | storage | ports can be added and removed | order of the ports |
|---|---|---|---|
PortArray<S> | array of fixed size S | no | as created |
PortVec | vector | yes | as created or added |
PortMap | B-tree map | yes | sorted by name |
The traits split the collection functionality:
PortCollectionfinds a port by its name and iterates over the ports. It is what a new collection type implements.PortCollectionMutadds and deletes ports, soPortArraydoes not implement it.PortCollectionAccessorsandPortCollectionAccessorsCommonaccess the ports by name: their values, handles, sequence numbers and connections to other ports and collections. They are implemented for everyPortCollectionthat isSendandSync.PortListcombinesPortCollectionandPortCollectionAccessorsCommonto a trait usable asdyn PortList, whichPortCollectionAccessorswith its generic methods is not.PortCollectionProviderandPortCollectionProviderMutgive access to the collection a type owns, e.g. the ports of a component. A type without ports can provide theEMPTY_PORT_ARRAY.
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:
| entry | creates 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
stdeach lock has its own reentrant mutex. - Without
stdall locks use a critical section, which is usable between threads and interrupts. The platform has to provide the critical section implementation for thecritical-sectioncrate, 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§
Macros§
- create_
in_ entry - Creates a name/port pair of an
Inport. - create_
in_ entry_ parseable - Creates a name/port pair of an
Inport with aFromStrsetter. - create_
inout_ entry - Creates a name/port pair of an
InOutport. - create_
inout_ entry_ parseable - Creates a name/port pair of an
InOutport with aFromStrsetter. - create_
out_ entry - Creates a name/port pair of an
Outport. - create_
out_ entry_ parseable - Creates a name/port pair of an
Outport with aFromStrsetter. - create_
port_ array - Creates a
dataport::PortArrayfrom a comma separated list of name/port pairs. - create_
port_ map - Creates a
dataport::PortMapfrom a comma separated list of name/port pairs. - create_
port_ vec - Creates a
dataport::PortVecfrom 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. - Empty
Port Array - Provides the empty
PortArrayfor types without ports, which implement the port collection traits. - Input
- The direction of a
PortHandleof anInport, which may only read. - Input
Output - The direction of a
PortHandleof anInOutport, which may read and write. - Output
- The direction of a
PortHandleof anOutport, which may only write. - Port
- A port holding a typed value, the common implementation of the port types
In,OutandInOut. - Port
Array - A collection of a fixed number
Sof namedPortVariants, in the order they are given. - Port
Handle - 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.
- Port
Variant - A port of one of the port types
In,InOutorOut, decided at runtime.
Statics§
- EMPTY_
PORT_ ARRAY - The
EmptyPortArrayfor types without ports, used by the default methods ofPortCollectionProvider.
Traits§
- AnyPort
Value - The data types a port can hold.
- InOut
Port - Read and write access to the value of a port with the data type
T, implemented byInOut. - InPort
- Read access to the value of a port with the data type
T, implemented byInandInOut. - OutPort
- Write access to the value of a port with the data type
T, implemented byOutandInOut. - Port
Collection - A collection of named ports. Each port is identified by its name, so the name has to be unique within a certain port collection.
- Port
Collection Accessors - Access to the values of the ports of a collection by their names.
- Port
Collection Accessors Common - 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 viaPortList. It connects ports of the collection to other ports and returns their sequence numbers. - Port
Collection Mut - 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.
- Port
Collection Provider - A type that owns a collection of ports, e.g. a component with its ports.
- Port
Collection Provider Mut - A type that owns a collection of ports, to which ports can be added and from which they can be deleted.
- Port
Commons - Methods common to all ports, whatever their port type: connecting them and tracking their changes.
- Port
List - The combination of
PortCollectionandPortCollectionAccessorsCommon, usable asdyn 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. - Blocking
Mutex - 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
PortHandleof anInport, which may only read. - InOut
- An input/output port, providing read and write access to a typed value
via
InPort,OutPortandInOutPort. - InOut
Handle - A
PortHandleof anInOutport, which may read and write. - Mutex
- An async mutex, which may be held across
.awaitpoints. - Mutex
Guard - 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
PortHandleof anOutport, which may only write. - RawMutex
- The raw mutex used by all locks.
On
stdeach 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.
- RwLock
Read Guard - The guard of a shared read access to a
RwLock, releasing the access when dropped. - RwLock
Write Guard - The guard of an exclusive write access to a
RwLock, releasing the access when dropped.