Crates.io | fmttools |
lib.rs | fmttools |
version | 0.2.2 |
source | src |
created_at | 2023-11-28 01:02:26.190777 |
updated_at | 2023-11-30 09:09:12.561369 |
description | Tools for modifying text without allocating any intermediate buffers or unsafe code |
homepage | |
repository | https://github.com/jmeggitt/fmttools |
max_upload_size | |
id | 1051475 |
size | 42,570 |
Tools for efficient modification of text as part of a single write!
call.
use fmttools::join;
let elements = vec!["abc", "\n", "123"];
assert_eq!("abc, \n, 123", format!("{}", join(&elements, ", ")));
assert_eq!("\"abc\", \"\\n\", \"123\"", format!("{:?}", join(&elements, ", ")));
use fmttools::join_fmt;
// Alternatively, a closure can be used
fn format_element(x: &i32, f: &mut Formatter<'_>) -> fmt::Result {
if *x > 3 {
return write!(f, "3+");
}
write!(f, "{}", x)
}
let elements = vec![1, 2, 3, 4, 5];
assert_eq!("1, 2, 3, 3+, 3+", format!("{}", join_fmt(&elements, ", ", format_element)));
use fmttools::replace;
#[derive(Debug)]
struct FooBar {
a: String,
}
let value = FooBar { a: "Bar".to_string() };
assert_eq!("FooBiz { a: \"Biz\" }", format!("{:?}", replace(&value, "Bar", "Biz")));
use fmttools::{DebugWith, ToFormatWith};
type RegistryKey = u32;
struct Registry {
key_names: HashMap<RegistryKey, String>,
}
struct FooEntry {
key: RegistryKey,
}
impl DebugWith<Registry> for FooEntry {
fn fmt(&self, f: &mut Formatter<'_>, registry: &Registry) -> fmt::Result {
let key_name = registry.key_names.get(&self.key)
.map(|x| x.as_str())
.unwrap_or("unknown");
write!(f, "FooEntry {{ key: {:?} }}", key_name)
}
}
let registry = Registry {
key_names: HashMap::from([
(2, "FooA".to_string()),
(5, "FooB".to_string()),
(9, "Bar".to_string()),
]),
};
let entry = FooEntry { key: 5 };
assert_eq!("FooEntry { key: \"FooB\" }", format!("{:?}", entry.fmt_with(®istry)));
Licensed under the Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0 or the MIT license https://opensource.org/licenses/MIT, at your option. This file may not be copied, modified, or distributed except according to those terms.