Skip to main content

Context

Struct Context 

Source
pub struct Context { /* private fields */ }
Expand description

Represents the context for template rendering.

Stores key → Value bindings. The shape is backwards compatible with the previous String → String API: set(key, value) still accepts two Strings and stores them as a Value::String; get(key) still returns Option<&String> for the Value::String case.

For nested data — needed by dot-notation paths like {{user.name}} — use Context::set_value with a richer Value (typically built via Value::from on a list, map, or primitive).

§Examples

use staticweaver_core::Context;

let mut context = Context::new();
context.set("name".to_string(), "Alice".to_string());
assert_eq!(context.get("name"), Some(&"Alice".to_string()));

Implementations§

Source§

impl Context

Source

pub fn new() -> Context

Creates a new, empty Context.

§Examples
use staticweaver_core::Context;

let context = Context::new();
assert!(context.is_empty());
Source

pub fn with_capacity(capacity: usize) -> Context

Creates a new Context with the specified capacity.

§Examples
use staticweaver_core::Context;

let context = Context::with_capacity(10);
assert!(context.is_empty());
assert!(context.capacity() >= 10);
Source

pub fn hash(&self) -> u64

Stable, iteration-order-independent hash of every entry.

Keys are sorted before being fed to the hasher (issue #30). The previous XOR aggregation was order-independent but collision-prone: two distinct (key, value) sets could XOR to the same u64, returning a stale render from the render_page cache.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("key".to_string(), "value".to_string());
let hash = context.hash();
assert_ne!(hash, 0);
Source

pub fn set(&mut self, key: String, value: String)

Sets a string-typed entry. Backwards-compatible with the pre-Value API; internally wraps the value as Value::String.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("name".to_string(), "Alice".to_string());
assert_eq!(context.get("name"), Some(&"Alice".to_string()));
Source

pub fn set_value<V>(&mut self, key: String, value: V)
where V: Into<Value>,

Stores any Into<Value> payload. Use this for non-string contexts (booleans, numbers, lists, nested maps).

§Examples
use staticweaver_core::{Context, context::Value};

let mut ctx = Context::new();
ctx.set_value("count".to_string(), 42);
ctx.set_value("active".to_string(), true);
ctx.set_value("tags".to_string(), vec!["rust", "ssg"]);

assert!(matches!(ctx.get_value("count"), Some(Value::Number(42))));
assert!(matches!(ctx.get_value("active"), Some(Value::Bool(true))));
Source

pub fn set_value_string(&mut self, key: &str, value: &str)

Borrowed-key counterpart to Context::set_value. Allocates a new String for the key only when no entry with that key exists; on update the existing key is reused and only the value slot is overwritten. Use this in tight loops where the same key is set repeatedly — the #each iterator helpers (this, @index, @first, @last, @key) are the canonical case.

§Examples
use staticweaver_core::Context;

let mut ctx = Context::new();
// First call allocates the key; second call only overwrites the value.
ctx.set_value_str("count", 1);
ctx.set_value_str("count", 2);
assert_eq!(format!("{:?}", ctx.get_value("count")), "Some(Number(2))");

Borrowed-string variant of Context::set_value_str for Value::String entries. When the existing slot is already a Value::String, this clears its buffer and pushes the new bytes in place, reusing the heap allocation instead of building a fresh String. For tight loops that set the same string-keyed slot repeatedly (most notably #each binding this to a Value::String item on every iteration) this saves one heap allocation per call after the first. Type changes (slot was a Number/Bool/etc) fall through to a full overwrite.

§Examples
use staticweaver_core::Context;

let mut ctx = Context::new();
ctx.set_value_string("greeting", "Hello");
ctx.set_value_string("greeting", "Hi"); // reuses the buffer
Source

pub fn set_value_str<V>(&mut self, key: &str, value: V)
where V: Into<Value>,

Borrowed-key counterpart to Context::set_value. Allocates a new String for the key only when no entry with that key exists; on update the existing key is reused and only the value slot is overwritten. Use this in tight loops where the same key is set repeatedly — the #each iterator helpers (this, @index, @first, @last, @key) are the canonical case.

§Examples
use staticweaver_core::Context;

let mut ctx = Context::new();
// First call allocates the key; second only overwrites the value.
ctx.set_value_str("count", 1);
ctx.set_value_str("count", 2);
assert_eq!(format!("{:?}", ctx.get_value("count")), "Some(Number(2))");
Source

pub fn get(&self, key: &str) -> Option<&String>

Returns the inner string for a Value::String entry, matching the historical signature. Non-string values return None (use Context::get_value or Context::get_path instead).

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("name".to_string(), "Bob".to_string());
assert_eq!(context.get("name"), Some(&"Bob".to_string()));
assert_eq!(context.get("age"), None);
Source

pub fn get_value(&self, key: &str) -> Option<&Value>

Returns the raw Value for a top-level key.

§Examples
use staticweaver_core::{Context, context::Value};

let mut ctx = Context::new();
ctx.set_value("count".to_string(), 7);
assert!(matches!(ctx.get_value("count"), Some(Value::Number(7))));
Source

pub fn get_path(&self, path: &str) -> Option<&Value>

Resolves a dot-separated path through nested Map and List values. Returns None for any missing segment or type mismatch.

§Examples
use staticweaver_core::{Context, context::Value};
use fnv::FnvHashMap;

let mut user = FnvHashMap::default();
let _ = user.insert("name".to_string(), Value::String("Ada".to_string()));

let mut ctx = Context::new();
ctx.set_value("user".to_string(), Value::Map(user));

assert!(matches!(ctx.get_path("user.name"), Some(Value::String(_))));
assert!(ctx.get_path("user.missing").is_none());
Source

pub fn get_mut(&mut self, key: &str) -> Option<&mut String>

Returns a mutable reference to the inner string for a Value::String entry. Returns None for any other variant.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("name".to_string(), "Bob".to_string());
if let Some(value) = context.get_mut("name") {
    *value = "Alice".to_string();
}
assert_eq!(context.get("name"), Some(&"Alice".to_string()));
Source

pub fn remove(&mut self, key: &str) -> Option<String>

Removes a key. Returns the inner string when the prior value was a Value::String; returns None for any other type or missing key.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("name".to_string(), "Alice".to_string());
assert_eq!(context.remove("name"), Some("Alice".to_string()));
assert_eq!(context.get("name"), None);
Source

pub fn len(&self) -> usize

Returns the number of top-level entries.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("key".to_string(), "value".to_string());
assert_eq!(context.len(), 1);
Source

pub fn capacity(&self) -> usize

Capacity of the underlying map.

§Examples
use staticweaver_core::Context;

let context = Context::with_capacity(10);
assert!(context.capacity() >= 10);
Source

pub fn is_empty(&self) -> bool

true when the context has no entries.

§Examples
use staticweaver_core::Context;

let context = Context::new();
assert!(context.is_empty());
Source

pub fn iter(&self) -> impl Iterator<Item = (&String, &Value)>

Iterator over (key, &Value) pairs.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("k".to_string(), "v".to_string());
for (key, _value) in context.iter() {
    assert_eq!(key, "k");
}
Source

pub fn clear(&mut self)

Removes every entry.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("key".to_string(), "value".to_string());
assert!(!context.is_empty());

context.clear();
assert!(context.is_empty());
Source

pub fn update<K, V>(&mut self, key: K, value: V)
where K: Into<String>, V: Into<String>,

Update or insert a string-valued entry.

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.set("key".to_string(), "old_value".to_string());
context.update("key", "new_value");
assert_eq!(context.get("key"), Some(&"new_value".to_string()));

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Context

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Context

Source§

fn default() -> Context

Returns the “default value” for a type. Read more
Source§

impl Extend<(String, String)> for Context

Source§

fn extend<T>(&mut self, iter: T)
where T: IntoIterator<Item = (String, String)>,

Extends the context from (String, String) pairs (back-compat shape).

§Examples
use staticweaver_core::Context;

let mut context = Context::new();
context.extend(vec![
    ("key1".to_string(), "value1".to_string()),
    ("key2".to_string(), "value2".to_string()),
]);
assert_eq!(context.get("key1"), Some(&"value1".to_string()));
assert_eq!(context.get("key2"), Some(&"value2".to_string()));
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl FromIterator<(String, String)> for Context

Source§

fn from_iter<I>(iter: I) -> Context
where I: IntoIterator<Item = (String, String)>,

Builds a context from (String, String) pairs (back-compat shape). Each value is wrapped as Value::String.

§Examples
use staticweaver_core::Context;

let pairs = vec![
    ("key1".to_string(), "value1".to_string()),
    ("key2".to_string(), "value2".to_string()),
];
let context: Context = pairs.into_iter().collect();
assert_eq!(context.get("key1"), Some(&"value1".to_string()));
assert_eq!(context.get("key2"), Some(&"value2".to_string()));
Source§

impl PartialEq for Context

Source§

fn eq(&self, other: &Context) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Context

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more