1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
//! Runtime implementation of [`format!`].
//!
//! # `std::fmt` compatible formatting
//!
//! All options but the fill character for alignment is supported
//! (due to [rust-lang/rfcs#3394](https://github.com/rust-lang/rfcs/pull/3394)).
//!
//! Though the non [`Display`] traits need to be enabled through
//! [features](#features).
//!
//! ```
//! use interpolator::{format, Formattable};
//!
//! let formatted = format(
//! "{value:+05}", // could be dynamic
//! &[("value", Formattable::display(&12))].into_iter().collect(),
//! )?;
//!
//! assert_eq!(formatted, format!("{:+05}", 12));
//! # return Ok::<(), interpolator::Error>(())
//! ```
#
(i.e. `#(({}))#`).
It is also possible to only iterate a sub-slice specified through a range
before the format string, i.e. `{list:i1..4}`. For open ranges range
bounds can also be omitted. To index from the end, you can use negative
range bounds.
It is also possible to index a single value by only specifying an [`isize`]
`{list:i1}`.
A [`Formattable`] implementing iter is created using [`Formattable::iter`]:
```
// HashMap macro
use collection_literals::hash;
use interpolator::{format, Formattable};
// Needs to be a slice of references because `Formattable::display` expects a
// reference
let items = [&"hello", &"hi", &"hey"].map(Formattable::display);
let items = Formattable::iter(&items);
let format_str = "Greetings: {items:i..-1(`{}`)(, )} and `{items:i-1}`";
assert_eq!(
format(format_str, &hash!("items" => items))?,
"Greetings: `hello`, `hi` and `hey`"
);
# return Ok::<(), interpolator::Error>(())
```"#
)]
//! See [`format`](format()) and [`write`](write()) for details.
//!
//! # Features
//! By default only [`Display`] is supported, the rest of the
//! [formatting traits](https://doc.rust-lang.org/std/fmt/index.html#formatting-traits)
//! can be enabled through the following features.
//!
//! - `debug` enables `?`, `x?` and `X?` trait specifiers
//! - `number` enables `x`, `X`, `b`, `o`, `e` and `E` trait specifiers
//! - `pointer` enables `p` trait specifiers
//! - `iter` enables [`i`](#i-iter-format) trait specifier
#![warn(clippy::pedantic, missing_docs)]
#![allow(
clippy::wildcard_imports,
clippy::implicit_hasher,
clippy::enum_glob_use,
clippy::module_name_repetitions
)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
use std::borrow::Borrow;
use std::collections::HashMap;
use std::error::Error as StdError;
#[cfg(feature = "pointer")]
use std::fmt::Pointer;
#[cfg(feature = "number")]
use std::fmt::{Binary, LowerExp, LowerHex, Octal, UpperExp, UpperHex};
use std::fmt::{Debug, Display, Error as FmtError, Write};
use std::hash::Hash;
use std::num::ParseIntError;
#[macro_use]
mod error;
pub use error::*;
mod hard_coded;
use hard_coded::format_value;
mod formattable;
pub use formattable::*;
mod parser;
use parser::*;
type Result<T = (), E = Error> = std::result::Result<T, E>;
/// Runtime version of [`format!`].
///
/// Takes a string and a context, containing [`Formattable`] values, returns a
/// string.
///
/// ```
/// use interpolator::{format, Formattable};
///
/// let formatted = format(
/// "{value:+05}", // could be dynamic
/// &[("value", Formattable::display(&12))].into_iter().collect(),
/// )
/// .unwrap();
///
/// assert_eq!(formatted, format!("{:+05}", 12));
/// ```
///
/// # Errors
///
/// It will return an error if the specified format string has invalid syntax,
/// the type doesn't implement the expected trait, or the formatting itself
/// failed.
///
/// For more details have a look at [`Error`] and [`ParseError`].
pub fn format<K: Borrow<str> + Eq + Hash>(
format: &str,
context: &HashMap<K, Formattable>,
) -> Result<String> {
let mut out = String::with_capacity(format.len());
write(&mut out, format, context)?;
Ok(out)
}
/// Runtime version of [`write!`].
///
/// Takes a mutable [`Write`] e.g. `&mut String`, a format string and a context,
/// containing [`Formattable`] values.
///
/// ```
/// use interpolator::{write, Formattable};
///
/// let mut buf = String::new();
/// write(
/// &mut buf,
/// "{value:+05}", // could be dynamic
/// &[("value", Formattable::display(&12))].into_iter().collect(),
/// )
/// .unwrap();
///
/// assert_eq!(buf, format!("{:+05}", 12));
/// ```
///
/// # Errors
///
/// It will return an error if the specified format string has invalid syntax,
/// the type doesn't implement the expected trait, or the formatting itself
/// failed.
///
/// For more details have a look at [`Error`] and [`ParseError`].
pub fn write<'a, K: Borrow<str> + Eq + Hash, F: Borrow<Formattable<'a>>>(
out: &mut impl Write,
mut format: &str,
context: &'a HashMap<K, F>,
) -> Result {
let format = &mut format;
let idx = &mut 0;
while !format.is_empty() {
if format.starts_with("{{") || format.starts_with("}}") {
out.write_str(&format[..1])
.map_err(|e| Error::Fmt(e, *idx))?;
step(2, format, idx);
continue;
}
if format.starts_with('{') {
step(1, format, idx);
let start = *idx;
let FormatArgument {
ident,
alignment,
sign,
hash,
zero,
width,
precision,
trait_,
} = FormatArgument::from_str(format, idx)?;
let value = context
.get(ident)
.ok_or(Error::MissingValue(ident.to_string(), start))?;
format_value(
out,
value.borrow(),
width,
precision,
alignment,
sign,
hash,
zero,
trait_,
*idx,
)?;
ensure!(format.starts_with('}'), ParseError::Expected("}", *idx));
step(1, format, idx);
continue;
}
let next = format
.chars()
.next()
.expect("should contain a char if not empty");
out.write_char(next).map_err(|e| Error::Fmt(e, *idx))?;
step(next.len_utf8(), format, idx);
}
Ok(())
}