use super::Functions;
use super::library::{INT_HINT, text};
use super::value::Value;
use std::iter::Peekable;
use std::str::Chars;
const DECIMALS: usize = 6;
pub(crate) fn format(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
let mut out = String::new();
for (piece, value) in pieces(args)? {
match piece {
Piece::Text(text) => out.push_str(&text),
Piece::Verb(verb) => out.push_str(&verb.written(value.unwrap_or(&Value::Null))?),
}
}
Ok(Value::string(&out))
}
pub(crate) fn format_size(args: &[Value]) -> usize {
pieces(args).map_or(0, |pieces| {
pieces
.iter()
.map(|(piece, value)| match piece {
Piece::Text(text) => text.chars().count(),
Piece::Verb(verb) => verb.size(value.unwrap_or(&Value::Null)),
})
.sum()
})
}
enum Piece {
Text(String),
Verb(Verb),
}
struct Verb {
letter: char,
width: usize,
zeros: bool,
precision: Option<usize>,
}
fn pieces(args: &[Value]) -> Result<Vec<(Piece, Option<&Value>)>, String> {
let values: &[Value] = match args.get(1) {
Some(Value::List(values)) => values,
_ => &[],
};
let mut pieces = Vec::new();
let mut given = values.iter();
let mut text_so_far = String::new();
let mut chars = text(args, 0).chars().peekable();
while let Some(c) = chars.next() {
if c != '%' {
text_so_far.push(c);
} else if chars.next_if_eq(&'%').is_some() {
text_so_far.push('%');
} else {
let verb = Verb::read(&mut chars)?;
let value = given.next().ok_or_else(|| {
format!(
"format() takes a value for each verb, and was given {}",
values.len()
)
})?;
pieces.push((Piece::Text(std::mem::take(&mut text_so_far)), None));
pieces.push((Piece::Verb(verb), Some(value)));
}
}
if given.next().is_some() {
let verbs = pieces.len() / 2;
return Err(format!(
"format() takes a value for each verb: {verbs} verbs, {} values",
values.len()
));
}
pieces.push((Piece::Text(text_so_far), None));
Ok(pieces)
}
impl Verb {
fn read(chars: &mut Peekable<Chars>) -> Result<Self, String> {
let zeros = chars.next_if_eq(&'0').is_some();
let width = number(chars).unwrap_or(0);
let precision = chars.next_if_eq(&'.').map(|_| number(chars).unwrap_or(0));
let letter = chars
.next()
.ok_or("format()'s template ends in a verb without its letter")?;
let verb = Self {
letter,
width,
zeros,
precision,
};
match letter {
's' | 'd' | 'f' => {}
other => {
return Err(format!(
"format() has the verbs %s, %d, %f and %%, not %{other}"
));
}
}
if zeros && letter == 's' {
return Err("format()'s %s is padded with spaces, not zeros".to_string());
}
if precision.is_some() && letter != 'f' {
return Err(format!("format()'s %{letter} takes no precision"));
}
Ok(verb)
}
fn written(&self, value: &Value) -> Result<String, String> {
let text = match (self.letter, value) {
('d', Value::Int(n)) => n.to_string(),
('f', Value::Int(_) | Value::Double(_)) => {
fixed(number_of(value), self.precision.unwrap_or(DECIMALS))
}
('s', value) => value
.written()
.map_err(|reason| format!("format()'s %s: {reason}"))?
.unwrap_or_default(),
('d', Value::Double(_)) => {
return Err(format!("format()'s %d takes an int, not double{INT_HINT}"));
}
(letter, value) => {
return Err(format!(
"format()'s %{letter} takes a number, not {}",
value.kind()
));
}
};
Ok(padded(text, self.width, self.zeros))
}
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the whole part's digits are few, and the number is rounded and made positive first"
)]
fn size(&self, value: &Value) -> usize {
let written = match (self.letter, value) {
('f', Value::Int(_) | Value::Double(_)) => {
let n = number_of(value);
let decimals = self.precision.unwrap_or(DECIMALS);
let whole = n.abs().round();
let digits = if whole < 1.0 {
1
} else {
whole.log10().floor() as usize + 1
};
usize::from(n.is_sign_negative()) + digits + usize::from(decimals > 0) + decimals
}
(_, value) => value
.written()
.ok()
.flatten()
.map_or(0, |text| text.chars().count()),
};
written.max(self.width)
}
}
fn fixed(n: f64, decimals: usize) -> String {
let exact = decimals.min(EXACT_DECIMALS);
let mut text = format!("{n:.exact$}");
text.extend(std::iter::repeat_n('0', decimals - exact));
text
}
const EXACT_DECIMALS: usize = 1100;
fn padded(text: String, width: usize, zeros: bool) -> String {
let fill = width.saturating_sub(text.chars().count());
if fill == 0 {
return text;
}
let (sign, digits) = match text.strip_prefix('-') {
Some(digits) if zeros => ("-", digits),
_ => ("", text.as_str()),
};
let pad = if zeros { '0' } else { ' ' };
let mut out = String::with_capacity(text.len() + fill);
out.push_str(sign);
out.extend(std::iter::repeat_n(pad, fill));
out.push_str(digits);
out
}
#[allow(
clippy::cast_precision_loss,
reason = "an int is written as the nearest double, as CEL converts it"
)]
fn number_of(value: &Value) -> f64 {
match value {
Value::Int(n) => *n as f64,
Value::Double(n) => *n,
_ => 0.0,
}
}
fn number(chars: &mut Peekable<Chars>) -> Option<usize> {
let mut found = None;
while let Some(digit) = chars.next_if(char::is_ascii_digit) {
let digit = digit.to_digit(10).map_or(0, |d| d as usize);
found = Some(
found
.unwrap_or(0_usize)
.saturating_mul(10)
.saturating_add(digit),
);
}
found
}
#[cfg(test)]
mod tests;