### Complete Example: Index-Based Data Access Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Demonstrates combining `AsRefWithContext` and `DisplayWithContext` traits for flexible index-based data access. This example shows how an `Index` struct can be used with different contexts like string slices and `Vec`. ```rust use contextual::{WithContext, AsRefWithContext, DisplayWithContext}; use std::fmt; /// Represents an index into a collection stored in context #[derive(Clone, Copy, Debug)] pub struct Index(pub usize); // Implement AsRefWithContext for generic slice access impl> AsRefWithContext for Index { fn as_ref_with<'a>(&'a self, context: &'a C) -> &'a T { &context.as_ref()[self.0] } } // Implement DisplayWithContext for string slice contexts impl<'a, C: AsRef<[&'a str]>> DisplayWithContext for Index { fn fmt_with(&self, context: &C, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", context.as_ref()[self.0]) } } fn main() { let i = Index(1); let context = ["a", "b", "c"]; // Display via format macro let output = format!("index: {}", i.with(&context)); assert_eq!(output, "index: b"); // AsRef access let value: &str = *i.with(&context).as_ref(); assert_eq!(value, "b"); // Works with Vec too let vec_context = vec!["x", "y", "z"]; println!("From vec: {}", i.with(&vec_context)); } ``` -------------------------------- ### Implement TryFromWithContext for ValidatedSymbol Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Implement `TryFromWithContext` for fallible conversions, returning a `Result`. This example shows converting a string slice to a `ValidatedSymbol` using a `SymbolRegistry` context, with `SymbolNotFound` as the error type. ```rust use contextual::{TryFromWithContext, TryIntoWithContext}; use std::collections::HashMap; #[derive(Debug, PartialEq)] struct ValidatedSymbol(u32); #[derive(Debug, PartialEq)] struct SymbolNotFound(String); struct SymbolRegistry(HashMap); impl TryFromWithContext<&str, SymbolRegistry> for ValidatedSymbol { type Error = SymbolNotFound; fn try_from_with(value: &str, context: &SymbolRegistry) -> Result { context.0 .get(value) .map(|&id| ValidatedSymbol(id)) .ok_or_else(|| SymbolNotFound(value.to_string())) } } let mut registry = HashMap::new(); registry.insert("valid".to_string(), 42); let context = SymbolRegistry(registry); // Successful conversion let result: Result = "valid".try_into_with(&context); assert_eq!(result, Ok(ValidatedSymbol(42))); // Failed conversion let result: Result = "invalid".try_into_with(&context); assert_eq!(result, Err(SymbolNotFound("invalid".to_string()))); ``` -------------------------------- ### Implement IntoRefWithContext for StringId Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Implement `IntoRefWithContext` to consume a value and produce a reference with the context's lifetime. This example converts a `StringId` to a `&str` using a `Vec` context. ```rust use contextual::{WithContext, IntoRefWithContext}; /// A string ID that can be converted to a string slice from context #[derive(Clone, Copy)] struct StringId(usize); impl<'a> IntoRefWithContext<'a, str, Vec> for StringId { fn into_ref_with(self, context: &'a Vec) -> &'a str { &context[self.0] } } let strings = vec![ "hello".to_string(), "world".to_string(), ]; let id = StringId(0); // The into_str() convenience method consumes the Contextual wrapper let s: &str = id.with(&strings).into_str(); assert_eq!(s, "hello"); // The original id can be reused since StringId is Copy let s2: &str = id.with(&strings).into_str(); assert_eq!(s2, "hello"); ``` -------------------------------- ### Implement DisplayWithContext for Contextual Formatting Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Implement DisplayWithContext to enable context-aware formatting for types. The Contextual wrapper automatically implements std::fmt::Display. ```rust use contextual::{WithContext, DisplayWithContext}; use std::fmt; /// An index that displays the value from context when formatted struct NameIndex(usize); impl> DisplayWithContext for NameIndex { fn fmt_with(&self, context: &C, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", context.as_ref()[self.0]) } } let names = ["Alice", "Bob", "Charlie"]; let idx = NameIndex(2); // The Contextual wrapper implements Display let message = format!("Hello, {}!", idx.with(&names)); assert_eq!(message, "Hello, Charlie!"); // Works with print macros println!("Selected: {}", idx.with(&names)); // DisplayWithContext is also implemented for references and Cow types let idx_ref = &idx; println!("Via reference: {}", idx_ref.with(&names)); ``` -------------------------------- ### Implement Contextual Traits in Rust Source: https://github.com/timothee-haudebourg/contextual/blob/main/README.md Demonstrates implementing AsRefWithContext and DisplayWithContext for an Index struct to access and display data from a slice context. ```rust use contextual::{WithContext, AsRefWithContext, DisplayWithContext}; use std::fmt; /// Index of an element in some array. pub struct Index(usize); impl> AsRefWithContext for Index { fn as_ref_with<'a>(&'a self, context: &'a C) -> &'a T { &context.as_ref()[self.0] } } impl<'a, C: AsRef<[&'a str]>> DisplayWithContext for Index { fn fmt_with(&self, context: &C, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Display; context.as_ref()[self.0].fmt(f) } } let i = Index(1); let context = ["a", "b", "c"]; print!("index: {}", i.with(&context)); assert_eq!(*i.with(&context).as_ref(), "b") ``` -------------------------------- ### Implement AsRefWithContext for Contextual References Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Implement AsRefWithContext to allow types to return references to data stored in a context. The Contextual wrapper automatically implements AsRef. ```rust use contextual::{WithContext, AsRefWithContext}; /// A simple index type that references elements in a slice context struct Index(usize); impl> AsRefWithContext for Index { fn as_ref_with<'a>(&'a self, context: &'a C) -> &'a T { &context.as_ref()[self.0] } } let items = ["first", "second", "third"]; let idx = Index(1); // Use .with() to create a Contextual, then .as_ref() works automatically let contextual = idx.with(&items); let value: &str = *contextual.as_ref(); assert_eq!(value, "second"); ``` ```rust /// For string contexts, the as_str() convenience method is available struct StringIndex(usize); impl> AsRefWithContext for StringIndex { fn as_ref_with<'a>(&'a self, context: &'a C) -> &'a str { context.as_ref()[self.0] } } let words = ["hello", "world"]; let idx = StringIndex(0); assert_eq!(idx.with(&words).as_str(), "hello"); ``` -------------------------------- ### Implement FromWithContext for Symbol Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Implement `FromWithContext` to create a `Symbol` from a string slice using a `SymbolTable` context. This automatically provides `IntoWithContext`. ```rust use contextual::{FromWithContext, IntoWithContext}; use std::collections::HashMap; /// A symbol that can be created from a string using a symbol table context #[derive(Debug, PartialEq)] struct Symbol(u32); /// The context: a mapping from strings to symbol IDs struct SymbolTable(HashMap); impl FromWithContext<&str, SymbolTable> for Symbol { fn from_with(value: &str, context: &SymbolTable) -> Self { Symbol(*context.0.get(value).unwrap_or(&0)) } } let mut table = HashMap::new(); table.insert("foo".to_string(), 1); table.insert("bar".to_string(), 2); let context = SymbolTable(table); // Use FromWithContext directly let sym1 = Symbol::from_with("foo", &context); assert_eq!(sym1, Symbol(1)); // Use IntoWithContext (automatically available) let sym2: Symbol = "bar".into_with(&context); assert_eq!(sym2, Symbol(2)); // Unknown symbols get default value let sym3: Symbol = "unknown".into_with(&context); assert_eq!(sym3, Symbol(0)); ``` -------------------------------- ### Create Contextual Wrappers with WithContext Source: https://context7.com/timothee-haudebourg/contextual/llms.txt Use the WithContext trait to create Contextual wrappers for references or owned values, enabling context-aware operations. ```rust use contextual::WithContext; // Any type can use the WithContext trait let index: usize = 1; let context = vec!["apple", "banana", "cherry"]; // Create a Contextual wrapper using .with() for references let contextual_ref = index.with(&context); // Create a Contextual wrapper using .into_with() for owned values let contextual_owned = index.into_with(&context); // The Contextual struct implements Deref, so you can access the inner value assert_eq!(*contextual_ref, 1); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.