Skip to main content

Crate context_trait

Crate context_trait 

Source
Expand description

§context-trait

Runtime-synthesized trait instances using function pointer tables, scoped to a callback.

This crate provides WithContext, a wrapper that pairs a value with a context supplying trait implementations. Built-in contexts include OrdContext, HashContext, and DisplayContext.

Declarative macros with_ord!, with_hash!, and with_display! make it easy to use non-default trait implementations in a scoped block.

The impl_context_trait! macro lets users define new context types for arbitrary traits.

§Examples

use context_trait::{with_ord, OrdContext, WithContext};

let items = vec![3i32, 1, 4, 1, 5];
with_ord!(items, |a: &i32, b: &i32| b.cmp(a), |wrapped: &[WithContext<i32, OrdContext<i32>>]| {
    let mut sorted = wrapped.to_vec();
    sorted.sort();
    let values: Vec<i32> = sorted.into_iter().map(|w| w.inner).collect();
    assert_eq!(values, vec![5, 4, 3, 1, 1]);
});

Macros§

impl_context_trait
Define a new context type and its trait implementation for WithContext.
with_display
Wraps items in WithContext<T, DisplayContext<T>> with a custom display function, runs a callback, and provides the wrapped slice.
with_hash
Wraps items in WithContext<T, HashContext<T>> with a custom hash function, runs a callback, and provides the wrapped slice.
with_ord
Wraps items in WithContext<T, OrdContext<T>> with a custom comparator, runs a callback, and provides the wrapped slice.

Structs§

DisplayContext
A context providing a custom display function.
HashContext
A context providing a custom hash function.
OrdContext
A context providing a custom comparison function.
WithContext
Pairs a value with a context that supplies trait implementations.