Module sandkiste::types

source ·
Expand description

Traits to be implemented by Machine::Datum to support specific types

Rationale

This module allows conversion from and to dynamic data types of scripting languages used in a VM. The Rust type covering all types of the scripting language is the associated type Machine::Datum.

As different VMs with different scripting languages may support different kinds of types, a Machine::Datum may implement all or only some Maybe… traits from this module, e.g. MaybeString and MaybeInteger when a VM supports strings and integers.

Converting from and to VM-specific data types

From VM-specific data types

Conversion to scalar data types is done through try_as_… methods, which attempt to interpret a VM-specific datum as certain type, e.g. MaybeInteger::try_as_i32 or MaybeString::try_as_str. These methods return a TypeMismatch if the type doesn’t match.

When conversion to Unicode or binary strings is desired, the VM-specific datum type must furthermore implement TryInto (ideally by implementing TryFrom) with DatumConversionFailure as error type to allow conversion into an owned String or Vec<u8>. This conversion is made available as try_into_string and try_into_binary to specify the type through the method call (as TryInto::try_into isn’t turbofishable). These convenience methods also convert the error type from DatumConversionFailure into TypeMismatch (in order to have an error type that is Send + Sync + 'static).

Collections are accessed through various methods in the MaybeArray and MaybeStringMap traits of which some may fail due to runtime errors in the VM and thus can return MachineErrors on failure.

To VM-specific data types

Conversion from scalar data types to the VM-specific type is done by implementing From, which allows creation directly from standard Rust data types (such as &str, String, or i32). See supertraits of the various Maybe… traits in this module.

Collections are created by trait methods that are implemented by the machine, e.g. HasArray::new_array.

Structs

Traits