pub struct ExpandStr(/* private fields */);Expand description
A template string with ${name} placeholders, awaiting expansion.
Construct with new (or new_static
for a 'static literal), then resolve against an ExpandLookup
with expand_to_string or
write_expanded. Deserialises transparently
from a string, so an ExpandStr field in a serde config is just a
plain string in TOML / JSON / YAML.
Construction performs no validation: a template with an unterminated
${ or an unresolved placeholder is held verbatim until expansion
time and only then errors. The trade-off is that new / new_static
are infallible — and new_static is const, so an
ExpandStr can live in a const or static binding.
§Example
use std::collections::HashMap;
use zenops_expand::ExpandStr;
let path = ExpandStr::new_static("${home}/.config");
let mut env = HashMap::new();
env.insert("home", "/home/ada");
assert_eq!(path.expand_to_string(&env).unwrap(), "/home/ada/.config");Implementations§
Source§impl ExpandStr
impl ExpandStr
Sourcepub const fn new_static(raw: &'static str) -> Self
pub const fn new_static(raw: &'static str) -> Self
Wrap a 'static template string without allocating.
const, so suitable for const and static bindings.
Sourcepub fn expand_to_string(
&self,
lookup: &(impl ExpandLookup + ?Sized),
) -> Result<String, ExpandError>
pub fn expand_to_string( &self, lookup: &(impl ExpandLookup + ?Sized), ) -> Result<String, ExpandError>
Expand the template into a new String.
Each ${name} is replaced with the value lookup writes for that
name. Literal characters pass through unchanged.
§Example
use std::collections::HashMap;
use zenops_expand::ExpandStr;
let t = ExpandStr::new_static("${greeting}, ${name}!");
let mut lookup: HashMap<&str, &str> = HashMap::new();
lookup.insert("greeting", "hi");
lookup.insert("name", "Ada");
assert_eq!(t.expand_to_string(&lookup).unwrap(), "hi, Ada!");Sourcepub fn write_expanded(
&self,
lookup: &(impl ExpandLookup + ?Sized),
f: &mut impl Write,
) -> Result<(), ExpandError>
pub fn write_expanded( &self, lookup: &(impl ExpandLookup + ?Sized), f: &mut impl Write, ) -> Result<(), ExpandError>
Expand the template into an existing fmt::Write sink.
Equivalent to expand_to_string but writes into a caller-supplied
buffer, so multiple templates can be concatenated without
intermediate allocations. On error the sink may have been written
to partially.
§Example
use std::collections::HashMap;
use std::fmt::Write;
use zenops_expand::ExpandStr;
let mut lookup: HashMap<&str, &str> = HashMap::new();
lookup.insert("user", "ada");
let mut out = String::from("path=");
let t = ExpandStr::new_static("/home/${user}");
t.write_expanded(&lookup, &mut out).unwrap();
write!(out, ";").unwrap();
assert_eq!(out, "path=/home/ada;");Sourcepub fn as_template(&self) -> &str
pub fn as_template(&self) -> &str
Get the raw template string.