use crate::value::{Value, excel_to_date_time, format_float};
fn sections(format: &str) -> Vec<String> {
let mut sections = vec![String::new()];
let mut chars = format.chars().peekable();
let mut quoted = false;
let mut bracket = false;
while let Some(c) = chars.next() {
match c {
'"' => quoted = !quoted,
'[' if !quoted => bracket = true,
']' if !quoted => bracket = false,
'\\' if !quoted => {
sections.last_mut().unwrap().push(c);
if let Some(next) = chars.next() {
sections.last_mut().unwrap().push(next);
}
continue;
}
';' if !quoted && !bracket => {
sections.push(String::new());
continue;
}
_ => {}
}
sections.last_mut().unwrap().push(c);
}
sections
}
fn strip_brackets(section: &str) -> String {
let mut out = String::new();
let mut rest = section;
while let Some(start) = rest.find('[') {
let quoted = rest[..start].matches('"').count() % 2 == 1;
out.push_str(&rest[..start]);
let Some(end) = rest[start..].find(']') else {
out.push_str(&rest[start..]);
return out;
};
let inner = &rest[start + 1..start + end];
if quoted {
out.push_str(&rest[start..=start + end]);
} else if let Some(currency) = inner.strip_prefix('$') {
let symbol = currency.split('-').next().unwrap_or_default();
if !symbol.is_empty() {
out.push('"');
out.push_str(symbol);
out.push('"');
}
} else if matches!(
inner.to_ascii_lowercase().as_str(),
"h" | "hh" | "m" | "mm" | "s" | "ss"
) {
out.push_str(&rest[start..=start + end]);
}
rest = &rest[start + end + 1..];
}
out.push_str(rest);
out
}
fn is_date(section: &str) -> bool {
let mut quoted = false;
let mut escaped = false;
for c in section.chars() {
if escaped {
escaped = false;
continue;
}
match c {
'\\' => escaped = true,
'"' => quoted = !quoted,
'd' | 'D' | 'm' | 'M' | 'y' | 'Y' | 'h' | 'H' | 's' | 'S' if !quoted => return true,
_ => {}
}
}
false
}
const MONTHS: [&str; 12] = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const DAYS: [&str; 7] = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
fn format_date(serial: f64, section: &str) -> String {
let date = excel_to_date_time(serial);
let lower = section.to_ascii_lowercase();
let twelve_hour = lower.contains("am/pm") || lower.contains("a/p");
let chars: Vec<char> = section.chars().collect();
let mut out = String::new();
let mut i = 0;
let mut after_hour = false;
let run = |i: usize, c: char| chars[i..].iter().take_while(|x| x.eq_ignore_ascii_case(&c)).count();
let starts = |i: usize, word: &str| {
let candidate: String = chars[i..].iter().take(word.len()).collect();
candidate.eq_ignore_ascii_case(word)
};
while i < chars.len() {
let c = chars[i];
match c.to_ascii_lowercase() {
'"' => {
let end = chars[i + 1..]
.iter()
.position(|x| *x == '"')
.map_or(chars.len(), |p| i + 1 + p);
out.extend(&chars[i + 1..end]);
i = end + 1;
}
'\\' => {
if let Some(next) = chars.get(i + 1) {
out.push(*next);
}
i += 2;
}
'_' => {
out.push(' ');
i += 2;
}
'*' => i += 2,
'[' => {
let end = chars[i..].iter().position(|x| *x == ']').map_or(chars.len(), |p| i + p);
let inner: String = chars[i + 1..end].iter().collect::<String>().to_ascii_lowercase();
let total_seconds = (serial * 86_400.0).round() as i64;
match inner.as_str() {
"h" | "hh" => out.push_str(&format!("{:0width$}", total_seconds / 3600, width = inner.len())),
"m" | "mm" => out.push_str(&format!("{:0width$}", total_seconds / 60, width = inner.len())),
_ => out.push_str(&format!("{:0width$}", total_seconds, width = inner.len())),
}
after_hour = inner.starts_with('h');
i = end + 1;
}
'y' => {
let n = run(i, 'y');
let year = date.year();
if n <= 2 {
out.push_str(&format!("{:02}", year % 100));
} else {
out.push_str(&format!("{year:04}"));
}
i += n;
}
'd' => {
let n = run(i, 'd');
let weekday = date.weekday().to_monday_zero_offset() as usize;
match n {
1 => out.push_str(&date.day().to_string()),
2 => out.push_str(&format!("{:02}", date.day())),
3 => out.push_str(&DAYS[weekday][..3]),
_ => out.push_str(DAYS[weekday]),
}
i += n;
}
'h' => {
let n = run(i, 'h');
let mut hour = date.hour() as i64;
if twelve_hour {
hour %= 12;
if hour == 0 {
hour = 12;
}
}
if n >= 2 {
out.push_str(&format!("{hour:02}"));
} else {
out.push_str(&hour.to_string());
}
after_hour = true;
i += n;
}
'm' => {
let n = run(i, 'm');
let next_is_second = chars[i + n..]
.iter()
.find(|x| x.is_ascii_alphabetic())
.is_some_and(|x| x.eq_ignore_ascii_case(&'s'));
if (after_hour || next_is_second) && n <= 2 {
let minute = date.minute();
out.push_str(&if n == 2 {
format!("{minute:02}")
} else {
minute.to_string()
});
after_hour = false;
} else {
let month = date.month() as usize;
match n {
1 => out.push_str(&month.to_string()),
2 => out.push_str(&format!("{month:02}")),
3 => out.push_str(&MONTHS[month - 1][..3]),
5 => out.push_str(&MONTHS[month - 1][..1]),
_ => out.push_str(MONTHS[month - 1]),
}
}
i += n;
}
's' => {
let n = run(i, 's');
let second = date.second();
out.push_str(&if n >= 2 {
format!("{second:02}")
} else {
second.to_string()
});
i += n;
if chars.get(i) == Some(&'.') {
let digits = chars[i + 1..].iter().take_while(|x| **x == '0').count();
if digits > 0 {
let fraction = (serial * 86_400.0).fract();
let scaled = (fraction * 10f64.powi(digits as i32)).round() as i64;
out.push('.');
out.push_str(&format!("{scaled:0digits$}"));
i += 1 + digits;
}
}
}
'a' if starts(i, "am/pm") => {
out.push_str(if date.hour() < 12 { "AM" } else { "PM" });
i += 5;
}
'a' if starts(i, "a/p") => {
out.push(if date.hour() < 12 { 'A' } else { 'P' });
i += 3;
}
_ => {
out.push(c);
i += 1;
}
}
}
out
}
fn thousands(digits: &str) -> String {
let mut out = String::new();
for (index, c) in digits.chars().enumerate() {
if index > 0 && (digits.len() - index).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
fn format_number(value: f64, section: &str) -> String {
let chars: Vec<char> = section.chars().collect();
let is_placeholder = |c: char| matches!(c, '0' | '#' | '?' | ',' | '.');
let mut prefix = String::new();
let mut pattern = String::new();
let mut suffix = String::new();
let mut percent = 0;
let mut scientific: Option<String> = None;
let mut i = 0;
let mut stage = 0;
while i < chars.len() {
let c = chars[i];
let literal: Option<String> = match c {
'"' => {
let end = chars[i + 1..]
.iter()
.position(|x| *x == '"')
.map_or(chars.len(), |p| i + 1 + p);
let text: String = chars[i + 1..end.min(chars.len())].iter().collect();
i = end + 1;
Some(text)
}
'\\' => {
let text = chars.get(i + 1).map(char::to_string).unwrap_or_default();
i += 2;
Some(text)
}
'_' => {
i += 2;
Some(" ".to_owned())
}
'*' => {
i += 2;
Some(String::new())
}
'%' => {
percent += 1;
i += 1;
Some("%".to_owned())
}
'E' | 'e' if stage == 1 && matches!(chars.get(i + 1), Some('+' | '-')) => {
let sign = chars[i + 1];
let digits = chars[i + 2..].iter().take_while(|x| matches!(x, '0' | '#')).count();
scientific = Some(format!("{sign}{digits}"));
i += 2 + digits;
stage = 2;
None
}
c if is_placeholder(c)
&& stage < 2
&& (c != ',' && c != '.'
|| stage == 1
|| chars[i + 1..].iter().any(|x| matches!(x, '0' | '#' | '?'))) =>
{
stage = 1;
pattern.push(c);
i += 1;
None
}
c => {
i += 1;
Some(c.to_string())
}
};
if let Some(text) = literal {
if stage == 0 {
prefix.push_str(&text);
} else {
stage = 2;
suffix.push_str(&text);
}
}
}
if pattern.is_empty() {
return format!("{prefix}{suffix}");
}
let mut value = value * 100f64.powi(percent);
let trimmed = pattern.trim_end_matches(',');
for _ in 0..(pattern.len() - trimmed.len()) {
value /= 1000.0;
}
let pattern = trimmed;
let (integer_pattern, decimal_pattern) = match pattern.split_once('.') {
Some((integer, decimal)) => (integer, decimal.replace(',', "")),
None => (pattern, String::new()),
};
let grouped = integer_pattern.contains(',');
let min_integer = integer_pattern.chars().filter(|c| *c == '0').count();
let decimals = decimal_pattern.len();
let required_decimals = decimal_pattern.trim_end_matches(['#', '?']).len();
let mut exponent_text = String::new();
if let Some(spec) = &scientific {
let sign = spec.chars().next().unwrap_or('+');
let digits: usize = spec[1..].parse().unwrap_or(2);
let exponent = if value == 0.0 {
0
} else {
value.abs().log10().floor() as i32
};
value /= 10f64.powi(exponent);
let sign_text = if exponent < 0 {
"-"
} else if sign == '+' {
"+"
} else {
""
};
exponent_text = format!("E{sign_text}{:0digits$}", exponent.abs());
}
let rounded = format!("{:.*}", decimals, value.abs());
let (integer, fraction) = match rounded.split_once('.') {
Some((integer, fraction)) => (integer.to_owned(), fraction.to_owned()),
None => (rounded.clone(), String::new()),
};
let mut integer = integer.trim_start_matches('0').to_owned();
while integer.len() < min_integer {
integer.insert(0, '0');
}
if grouped {
integer = thousands(&integer);
}
let mut fraction = fraction;
while fraction.len() > required_decimals && fraction.ends_with('0') {
fraction.pop();
}
let mut number = integer;
if decimals > 0 && (!fraction.is_empty() || pattern.ends_with('.')) {
number.push('.');
number.push_str(&fraction);
} else if pattern.ends_with('.') {
number.push('.');
}
let negative = value < 0.0 && rounded.chars().any(|c| c.is_ascii_digit() && c != '0');
format!(
"{}{prefix}{number}{exponent_text}{suffix}",
if negative { "-" } else { "" }
)
}
fn general(value: &Value) -> String {
match value {
Value::Float(number) => format_float(*number),
other => other.to_text(),
}
}
pub fn format_value(value: &Value, format: &str) -> String {
let format = format.trim();
let number = match value {
Value::Int(number) => *number as f64,
Value::Float(number) => *number,
Value::Bool(value) => return if *value { "TRUE".to_owned() } else { "FALSE".to_owned() },
Value::Null => return String::new(),
Value::String(text) => {
let parts = sections(format);
if let Some(text_section) = parts.get(3) {
return text_section.replace('@', text).replace('"', "");
}
if parts.len() == 1 && parts[0].contains('@') && parts[0] != "@" {
return strip_literals(&parts[0]).replace('@', text);
}
return text.clone();
}
other => return other.to_text(),
};
if format.is_empty() || format.eq_ignore_ascii_case("general") || format == "@" {
return general(value);
}
let parts = sections(format);
let (section, value) = match parts.len() {
1 => (parts[0].as_str(), number),
2 => {
if number < 0.0 {
(parts[1].as_str(), -number)
} else {
(parts[0].as_str(), number)
}
}
_ => {
if number > 0.0 {
(parts[0].as_str(), number)
} else if number < 0.0 {
(parts[1].as_str(), -number)
} else {
(parts[2].as_str(), number)
}
}
};
let section = strip_brackets(section);
if section.eq_ignore_ascii_case("general") {
return general(&Value::Float(value));
}
if is_date(§ion) && !section.contains(['0', '#']) {
return format_date(value, §ion);
}
format_number(value, §ion)
}
fn strip_literals(section: &str) -> String {
section.replace('"', "")
}
#[cfg(test)]
mod tests {
use super::*;
fn f(value: impl Into<Value>, format: &str) -> String {
format_value(&value.into(), format)
}
#[test]
fn numbers() {
assert_eq!(f(1234.567, "0"), "1235");
assert_eq!(f(1234.567, "0.00"), "1234.57");
assert_eq!(f(1234.567, "#,##0.00"), "1,234.57");
assert_eq!(f(0.256, "0%"), "26%");
assert_eq!(f(0.256, "0.0%"), "25.6%");
assert_eq!(f(-5, "0.00;(0.00)"), "(5.00)");
assert_eq!(f(5, "\"$\"#,##0.00"), "$5.00");
assert_eq!(f(12345.6, "0.00E+00"), "1.23E+04");
assert_eq!(f(1.5, "General"), "1.5");
assert_eq!(f(1234.5, "#,##0.00 [$€-407]"), "1,234.50 €");
}
#[test]
fn dates() {
let serial = 45356.0 + (14.0 * 3600.0 + 7.0 * 60.0 + 9.0) / 86_400.0;
assert_eq!(f(serial, "dd/mm/yyyy"), "05/03/2024");
assert_eq!(f(serial, "yyyy-mm-dd hh:mm:ss"), "2024-03-05 14:07:09");
assert_eq!(f(serial, "d/m/yy h:mm"), "5/3/24 14:07");
assert_eq!(f(serial, "h:mm:ss"), "14:07:09");
assert_eq!(f(serial, "h:mm AM/PM"), "2:07 PM");
assert_eq!(f(serial, "d mmm yyyy"), "5 Mar 2024");
assert_eq!(f(serial, "dddd"), "Tuesday");
}
#[test]
fn text() {
assert_eq!(f("abc", "@"), "abc");
assert_eq!(f("abc", "0.00"), "abc");
}
}