Skip to main content

Crate read_only

Crate read_only 

Source
Expand description

Read-only field exposure macros.

This crate intentionally combines two patterns:

  • cast is the classic cast-based readonly-field pattern, re-exported from the readonly crate.
  • embed is this crate’s safe composition-based alternative that builds a dedicated ReadOnly* view struct and dereferences into it without unsafe code in the generated access path.

Two attributes are provided:

  • #[cast] (re-exported from the readonly crate) — generates a ReadOnly* struct with the same fields and provides Deref via an unsafe pointer cast. Fields remain writable within the defining module but become read-only externally.

  • #[embed] — safe composition pattern. Fields annotated #[readonly] are moved into a ReadOnly* struct embedded inside the owning struct. A safe Deref<Target=ReadOnly*> impl is generated. Non-readonly fields stay on the owning struct and are accessed directly.

The default-enabled docs feature makes rustdoc render a docs-only outer struct for #[embed] so readonly fields appear directly in the documented field list.

For #[embed], writing pub on a #[readonly] field is optional: the generated readonly view promotes inherited visibility to the struct’s visibility.

§Choosing a Macro

Use cast when you want the familiar readonly behavior and the smallest syntax change.

Use embed when you want an explicit readonly view type and a safe composition-based implementation.

§About cast

cast is a re-export of readonly::make. This crate intentionally uses the upstream implementation and upstream item documentation for that macro. The crate-level docs and README provide the local framing for how cast fits beside embed.

§Examples

See the runnable examples in:

  • examples/basic.rs
  • examples/embed_deref.rs

Attribute Macros§

cast
embed