contextual/
lib.rs

1//! A small crate to deal with data in context.
2//!
3//! ```
4//! use contextual::{WithContext, AsRefWithContext, DisplayWithContext};
5//! use std::fmt;
6//!
7//! /// Index of an element in some array.
8//! pub struct Index(usize);
9//!
10//! impl<T, C: AsRef<[T]>> AsRefWithContext<T, C> for Index {
11//!   fn as_ref_with<'a>(&'a self, context: &'a C) -> &'a T {
12//!     &context.as_ref()[self.0]
13//!   }
14//! }
15//!
16//! impl<'a, C: AsRef<[&'a str]>> DisplayWithContext<C> for Index {
17//!   fn fmt_with(&self, context: &C, f: &mut fmt::Formatter) -> fmt::Result {
18//!     use fmt::Display;
19//!     context.as_ref()[self.0].fmt(f)
20//!   }
21//! }
22//!
23//! let i = Index(1);
24//! let context = ["a", "b", "c"];
25//!
26//! print!("index: {}", i.with(&context));
27//! assert_eq!(*i.with(&context).as_ref(), "b")
28//! ```
29mod as_ref;
30mod display;
31mod from;
32mod into_ref;
33mod try_from;
34
35pub use as_ref::*;
36pub use display::*;
37pub use from::*;
38pub use into_ref::*;
39pub use try_from::*;
40
41pub struct Contextual<T, C>(pub T, pub C);
42
43pub trait WithContext {
44	fn with<C>(&self, context: C) -> Contextual<&Self, C>;
45
46	fn into_with<C>(self, context: C) -> Contextual<Self, C>
47	where
48		Self: Sized;
49}
50
51impl<T: ?Sized> WithContext for T {
52	fn with<C>(&self, context: C) -> Contextual<&Self, C> {
53		Contextual(self, context)
54	}
55
56	fn into_with<C>(self, context: C) -> Contextual<Self, C>
57	where
58		Self: Sized,
59	{
60		Contextual(self, context)
61	}
62}
63
64impl<T, C> std::ops::Deref for Contextual<T, C> {
65	type Target = T;
66
67	fn deref(&self) -> &T {
68		&self.0
69	}
70}
71
72impl<T, C> std::ops::DerefMut for Contextual<T, C> {
73	fn deref_mut(&mut self) -> &mut T {
74		&mut self.0
75	}
76}