4 stable releases
new 2.0.2 | Apr 22, 2025 |
---|---|
2.0.1 | Apr 20, 2025 |
1.1.2 | Feb 11, 2025 |
1.0.1 | Feb 5, 2025 |
#621 in Encoding
104 downloads per month
Used in cdumay_result
38KB
446 lines
cdumay_context
A flexible context management library that provides a trait-based approach for handling key-value data with support for multiple serialization formats.
Features
- Generic context management through the
Contextualize
trait and aContext
struct - Support for multiple serialization formats (with feature flags):
- JSON (feature: "json")
- TOML (feature: "toml")
- YAML (feature: "yaml")
- Allow to dump context into
reqwest
headers using feature "http-headers" - Type-safe error handling with the
Error
enum
Example Usage
use std::collections::BTreeMap;
use serde::{Serialize, Deserialize};
use cdumay_context::{Contextualize, Error, Context};
// Basic usage
let mut ctx = Context::new();
ctx.insert("name".to_string(), serde_value::Value::String("Alice".to_string()));
// JSON serialization (requires "json" feature)
#[cfg(feature = "json")]
{
let json = ctx.to_json(true).unwrap();
let ctx_from_json = Context::from_json(&json).unwrap();
assert_eq!(ctx.get("name"), ctx_from_json.get("name"));
}
// TOML serialization (requires "toml" feature)
#[cfg(feature = "toml")]
{
let toml = ctx.to_toml(true).unwrap();
let ctx_from_toml = Context::from_toml(&toml).unwrap();
assert_eq!(ctx.get("name"), ctx_from_toml.get("name"));
}
Error Handling
The library provides a comprehensive error handling system through the Error
enum:
use std::collections::BTreeMap;
use serde::{Serialize, Deserialize};
use cdumay_context::{Context, Contextualize, Error};
use rand::Rng;
fn example_error_handling() -> Result<(), Error> {
let mut rng = rand::rng();
let dice_roll: u8 = rng.random_range(1..=6);
// Generic error
if dice_roll == 7 {
return Err(Error::Generic("Something went wrong".to_string()));
}
// JSON error (with "json" feature)
#[cfg(feature = "json")]
{
let invalid_json = "{ invalid: json }";
let result = Context::from_json(invalid_json);
assert!(matches!(result, Err(Error::Json(_))));
}
Ok(())
}
Dependencies
~0.5–12MB
~135K SLoC