Note: this library is fairly stable and tested, but new features are in the early stages of development and feedback (positive or negative) would be much appreciated. If you use this library and liked it or decided not to use it, please ping me at @vitiral on twitter or vitiral@gmail.com via email to tell me about your experience. I would particularily like to see the code where it is being used. Thankyou!
This library is for rust developers who want to bring rust-like formatting to non-static strings.
``` extern crate strfmt; use strfmt::strfmt; use std::collections::HashMap;
fn itworks() { let mut vars = HashMap::new(); vars.insert("name".tostring(), "bob"); vars.insert("job".to_string(), "python developer");
let fmt = "hi, my name is {name} and I am a {job}!".to_string();
assert_eq!(strfmt(&fmt, &vars).unwrap(), "hi, my name is bob and I am a python developer!")
} ```
In addition to the strfmt
function, this library has the Format
trait which adds the
format
method to str
and String
types.
assert_eq!("hi, my name is {name}".format(&vars), "hi, my name is bob")
You can use this library any time you have dynamic strings you want to format, such as if you are providing your users a ui or are reading configuration files.
strfmt does not support empty identifiers (i.e. {}
or {:<10}
. Integer identifiers
will be read as str keys to the hashmap (i.e. {1:<10}
will have key == "1")
This feature is in Beta and may change. I expect it to be fairly stable at this point but would appreciate feedback on development.
In addition, "signed 0 padding" (i.e. +000042) is not yet supported for numeric types
Using strfmt_map
it is also possible to format integers and floats:
```
let mut vars: HashMap
let f = |mut fmt: Formatter| { fmt.f64(*vars.get(fmt.key).unwrap()) }; asserteq!(strfmtmap("{x:<7.2}", f).unwrap(), "42.42 "); asserteq!(strfmtmap("{y:+.2E}", f).unwrap(), "-1.00E2"); asserteq!(strfmtmap("{z:+.2E}", f).unwrap(), "+0.00E0"); ```
strfmt aims to support all of the formatting options defined in
std::fmt
. Currently it officially only supports
the format options for strings (beta support for i64 and f64)
See the syntax for how to create a formatted string
strfmt_map
and add format_map
to the Format
trait.f64
method to Formatter
allowing those using strfmt_map
to formati64
method to Formatter
allowing those using strfmt_map
to formatformat_f64(&self, HashMap<String, f64>
method to Format
allowing usersformat_i64(&self, HashMap<String, i64>
method to Format
allowing usersvec
method to Formatter
allowing those usin strfmt_map
to formatVec<Display>
in a way that uses precision and widthAdding functionality should be fairly easy, the main piece of work is checking and handling
the flags correctly and creating comprehensive tests. Hopefully I will be creating the f64
method soon to show how it can be done, but I could really use all the help I can get on
making this libray complete.