Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crosstrait #212

Merged
merged 11 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ jobs:
with:
profile: minimal
toolchain: stable
target: thumbv7em-none-eabihf
override: true

- name: Cargo Doc
Expand All @@ -77,41 +76,37 @@ jobs:
toolchain:
- stable
- 1.70.0 # keep in sync with manifest MSRV
target:
- thumbv7em-none-eabihf

steps:
- uses: actions/checkout@v2
- name: Install Rust ${{ matrix.toolchain }}
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.toolchain }}
target: ${{ matrix.target }}
override: true

- name: Cargo Check
uses: actions-rs/cargo@v1
with:
command: check
args: --verbose --target ${{ matrix.target }}
args: --verbose

- name: Cargo Build [No-Features]
uses: actions-rs/cargo@v1
with:
command: build
args: --no-default-features --target ${{ matrix.target }}
args: --no-default-features

- name: Cargo Build
uses: actions-rs/cargo@v1
with:
command: build
args: --target ${{ matrix.target }}

- name: Cargo Build [Release]
uses: actions-rs/cargo@v1
with:
command: build
args: --release --target ${{ matrix.target }}
args: --release

- name: Cargo Build [Examples]
uses: actions-rs/cargo@v1
Expand All @@ -128,9 +123,7 @@ jobs:
- 1.70.0 # keep in sync with manifest MSRV
args:
- ""
- --all-features
- --no-default-features
- --no-default-features --features json-core

steps:
- uses: actions/checkout@v2
Expand All @@ -153,6 +146,28 @@ jobs:
command: test
args: ${{ matrix.args }}

embedded:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
target: thumbv7m-none-eabi
- name: Install QEMU
run: |
sudo apt-get update
sudo apt-get install -y qemu-system-arm
- run: cargo run --release
env:
RUSTFLAGS: -C link-arg=-Tlink.x -D warnings
working-directory: crosstrait/tests/embedded
continue-on-error: true
- run: cargo run --release --features used_linker
env:
RUSTFLAGS: -C link-arg=-Tlink.x -D warnings
working-directory: crosstrait/tests/embedded

examples:
runs-on: ubuntu-latest
strategy:
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[workspace]
members = [
"crosstrait",
"miniconf_derive",
"miniconf",
"miniconf_mqtt",
Expand Down
24 changes: 24 additions & 0 deletions crosstrait/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[package]
name = "crosstrait"
version = "0.1.0"
edition = "2021"
authors = ["Robert Jördens <[email protected]>"]
license = "MIT OR Apache-2.0"
description = "Cast from `dyn Any` to other trait objects, with no_std, no alloc support"
repository = "https://github.com/quartiq/miniconf"
documentation = "https://docs.rs/crosstrait"
readme = "README.md"
categories = ["rust-patterns", "embedded", "no-std", "no-std::no-alloc"]
keywords = ["linkage", "trait", "cast", "any"]

[dependencies]
linkme = "0.3"
heapless = "0.8" # not(feature = "std")
gensym = "0.1"
once_cell = { version = "1.19", default-features = false, features = ["critical-section"] }

[features]
std = ["alloc", "once_cell/std"]
used_linker = ["linkme/used_linker"]
alloc = []
default = ["std"]
105 changes: 105 additions & 0 deletions crosstrait/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# Cast from `dyn Any` to other trait objects

* `no_std` no alloc support
* No proc macros

## Usage

```toml
[dependencies]
crosstrait = "0.1"
```

Then use the `register!{ Type => Trait }` declarative macro and the [`Cast`] traits.

For embedded, the linker needs to be informed of the type registry.

## Example

```rust
use core::any::Any;
use crosstrait::{Cast, Castable, CastableRef, register, REGISTRY};

// Some example traits to play with
use core::{fmt::{Debug, Formatter, Write}, ops::{AddAssign, SubAssign}};

// Add types and trait implementations in the default global registy
// Implementation status is verified at compile time
register! { i32 => dyn Debug }

// Registering foreign types and traits works fine
// Serialization/deserialization of `dyn Any` is a major use case
// register! { i32 => dyn erased_serde::Serialize }

// Check for trait impl registration on concrete type
assert!(i32::castable::<dyn Debug>());

// Check for trait impl registration on Any
let any: &dyn Any = &42i32;
assert!(any.castable::<dyn Debug>());

// SubAssign<i32> is impl'd for i32 but not registered
assert!(!any.castable::<dyn SubAssign<i32>>());

// Cast ref
let a: &dyn Debug = any.cast().unwrap();
println!("42 = {a:?}");

// Cast mut
let mut value = 5i32;
let any: &mut dyn Any = &mut value;
let v: &mut dyn AddAssign<i32> = any.cast().unwrap();
*v += 3;
assert_eq!(value, 5 + 3);

// Cast Box
let any: Box<dyn Any> = Box::new(0i32);
let _: Box<dyn Debug> = any.cast().unwrap();

// Cast Rc
use std::rc::Rc;
let any: Rc<dyn Any> = Rc::new(0i32);
let _: Rc<dyn Debug> = any.cast().unwrap();

// Cast Arc
use std::sync::Arc;
let any: Arc<dyn Any + Sync + Send> = Arc::new(0i32);
let _: Arc<dyn Debug> = any.cast().unwrap();

// Explicit registry usage
let any: &dyn Any = &0i32;
let _: &dyn Debug = REGISTRY.cast_ref(any).unwrap();

// Autotraits and type/const generics are distinct
let a: Option<&(dyn Debug + Sync)> = any.cast();
assert!(a.is_none());

// Registration can happen anywhere in any order in any downstream crate
register! { i32 => dyn AddAssign<i32> }

// If a type is not Send + Sync, it can't cast as Arc. `no_arc` accounts for that
register! { Formatter => dyn Write, no_arc }
```

## Related crates

* [`intertrait`](https://crates.io/crates/intertrait): similar goals, `std`
* [`miniconf`](https://crates.io/crates/miniconf): provides several ways to get `dyn Any` from nodes in
heterogeneous nested data structures, `no_std`, no alloc
* [`erased_serde`](https://crates.io/crates/erased-serde): `Serialize`/`Serializer`/`Deserializer` trait objects
* [`linkme`](https://crates.io/crates/linkme): linker magic used to build distributed static type registry

## Limitations

### Registry size on `no_std`

Currently the size of the global registry on `no_std` is fixed and arbitrarily set to 128 entries.

### Auto traits

Since adding any combination of auto traits (in particular `Send`, `Sync`, `Unpin`) to a trait results in a distinct trait,
all relevant combinations of traits plus auto traits needs to be registered explicitly.

### Global registry

A custom non-static [`Registry`] can be built and used explicitly but the `Cast` traits will not use it.
Loading
Loading