use std::cmp::Ordering;
use std::sync::Arc;
use f_office_paint::Rgb;
use f_office_units::scale::TENTHS;
use super::Decimal;
use crate::configuration::NumberSeparators;
use crate::params::{
CHART_AXIS_GENERAL_CHARACTERS, CHART_DIGIT_GROUP, CHART_EXPONENT_DIGITS, CHART_FORMAT_RED,
CHART_FORMAT_SECTIONS, CHART_GENERAL_CHARACTERS, CHART_NUMBER_SECTIONS,
CHART_SIGNIFICANT_DIGITS,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LabelFormat(Form);
#[derive(Clone, Debug, PartialEq, Eq)]
enum Form {
AllDigits,
General(NumberSeparators, LabelPlace),
Code(Arc<Code>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WrittenLabel {
pub pieces: Vec<LabelPiece>,
pub color: Option<Rgb>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LabelPlace {
Data,
CategoryAxis,
ValueAxis,
}
impl LabelPlace {
const fn general_characters(self) -> usize {
match self {
Self::Data | Self::CategoryAxis => CHART_GENERAL_CHARACTERS,
Self::ValueAxis => CHART_AXIS_GENERAL_CHARACTERS,
}
}
const fn counts_sign(self) -> bool {
match self {
Self::Data | Self::CategoryAxis => false,
Self::ValueAxis => true,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LabelPiece {
Text(String),
Blank(char),
}
impl LabelFormat {
#[must_use]
pub(crate) const fn all_digits() -> Self {
Self(Form::AllDigits)
}
#[must_use]
pub(crate) const fn general(separators: NumberSeparators, place: LabelPlace) -> Self {
Self(Form::General(separators, place))
}
#[must_use]
pub(crate) fn code(code: &str, separators: NumberSeparators) -> Option<Self> {
if code.is_empty() {
return None;
}
let texts = sections(code)?;
let sections = texts
.into_iter()
.take(CHART_NUMBER_SECTIONS)
.map(Section::read)
.collect::<Option<Vec<_>>>()?;
Some(Self(Form::Code(Arc::new(Code {
sections,
separators,
}))))
}
#[must_use]
pub fn write(&self, value: Decimal) -> Option<WrittenLabel> {
let text = match &self.0 {
Form::AllDigits => all_digits(value),
Form::General(separators, place) => general(value, (*separators, *place))?,
Form::Code(code) => return code.write(value),
};
Some(WrittenLabel {
pieces: vec![LabelPiece::Text(text)],
color: None,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Code {
sections: Vec<Section>,
separators: NumberSeparators,
}
impl Code {
fn write(&self, value: Decimal) -> Option<WrittenLabel> {
let value = significant(value, CHART_SIGNIFICANT_DIGITS)?;
let sign = value.digits.cmp(&0);
let (section, minus) = match (self.sections.as_slice(), sign) {
([only], _) => (only, sign == Ordering::Less),
([_, below, ..], Ordering::Less) => (below, false),
([_, _, zero], Ordering::Equal) => (zero, false),
([above, ..], _) => (above, false),
([], _) => return None,
};
let number = match section.number {
Some(digits) => {
let shown = Decimal {
digits: value.digits.checked_abs()?,
exponent: value.exponent.checked_add(section.scale)?,
};
Some(digits.write(shown, self.separators)?)
}
None => None,
};
let rounds_to_zero = number
.as_deref()
.is_some_and(|pieces| !has_nonzero_digit(pieces));
let mut pieces = Vec::new();
if minus && !rounds_to_zero {
pieces.push(LabelPiece::Text("-".to_owned()));
}
pieces.extend(section.before.iter().cloned());
pieces.extend(number.into_iter().flatten());
pieces.extend(section.after.iter().cloned());
let pieces = joined(pieces);
(!pieces.is_empty()).then_some(WrittenLabel {
pieces,
color: section.color,
})
}
}
fn has_nonzero_digit(pieces: &[LabelPiece]) -> bool {
pieces.iter().any(|piece| match piece {
LabelPiece::Text(text) => text.chars().any(|ch| matches!(ch, '1'..='9')),
LabelPiece::Blank(_) => false,
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Section {
before: Vec<LabelPiece>,
number: Option<Digits>,
after: Vec<LabelPiece>,
color: Option<Rgb>,
scale: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stage {
Before,
Whole(i32),
Decimals(i32),
Exponent,
After,
}
impl Stage {
fn comma(self) -> Option<Self> {
match self {
Self::Whole(commas) => Some(Self::Whole(commas.checked_add(1)?)),
Self::Decimals(commas) => Some(Self::Decimals(commas.checked_add(1)?)),
Self::Before | Self::Exponent | Self::After => None,
}
}
}
impl Section {
fn read(text: &str) -> Option<Self> {
let mut section = Self::default();
let mut digits = Digits::default();
let mut stage = Stage::Before;
let mut chars = text.chars();
while let Some(ch) = chars.next() {
stage = section.step(&mut digits, ch, &mut chars, stage)?;
}
if digits.exponent.is_some_and(|exp| exp.digits == 0) {
return None;
}
section.end(stage)?;
section.number = (stage != Stage::Before).then_some(digits);
Some(section)
}
fn step(
&mut self,
digits: &mut Digits,
ch: char,
chars: &mut std::str::Chars<'_>,
stage: Stage,
) -> Option<Stage> {
match ch {
'0' | '#' | '?' => digits.placeholder(ch, stage),
'.' => digits.point(stage),
',' => stage.comma(),
'E' | 'e' => digits.start_exponent(ch, chars, stage),
'*' => self.fill(chars, stage),
'[' => self.bracket(&until(chars, ']')?, stage),
'%' => self.percent(stage),
_ => self.literal(literal(ch, chars)?, stage),
}
}
fn fill(&mut self, rest: &mut std::str::Chars<'_>, stage: Stage) -> Option<Stage> {
rest.next()?;
if stage == Stage::Before {
return Some(stage);
}
self.end(stage)?;
Some(Stage::After)
}
fn percent(&mut self, stage: Stage) -> Option<Stage> {
self.scale = self.scale.checked_add(2)?;
self.literal(LabelPiece::Text("%".to_owned()), stage)
}
fn literal(&mut self, piece: LabelPiece, stage: Stage) -> Option<Stage> {
if stage == Stage::Before {
self.before.push(piece);
return Some(stage);
}
self.end(stage)?;
self.after.push(piece);
Some(Stage::After)
}
fn end(&mut self, stage: Stage) -> Option<()> {
if let Stage::Whole(commas) | Stage::Decimals(commas) = stage {
let group = i32::try_from(CHART_DIGIT_GROUP).ok()?;
self.scale = self.scale.checked_sub(commas.checked_mul(group)?)?;
}
Some(())
}
fn bracket(&mut self, token: &str, stage: Stage) -> Option<Stage> {
if let Some(currency) = token.strip_prefix('$') {
let symbol = currency.split('-').next()?;
if symbol.is_empty() {
return None;
}
return self.literal(LabelPiece::Text(symbol.to_owned()), stage);
}
if self.color.is_some() || !token.eq_ignore_ascii_case("Red") {
return None;
}
self.color = Some(CHART_FORMAT_RED);
Some(stage)
}
}
fn literal(ch: char, rest: &mut std::str::Chars<'_>) -> Option<LabelPiece> {
match ch {
'"' => until(rest, '"').map(LabelPiece::Text),
'\\' => rest
.next()
.map(|escaped| LabelPiece::Text(escaped.to_string())),
'_' => rest.next().map(LabelPiece::Blank),
'%' | '$' | '-' | '+' | '/' | '(' | ')' | ':' | '!' | '^' | '&' | '\'' | '~' | '{'
| '}' | '<' | '>' | '=' | ' ' => Some(LabelPiece::Text(ch.to_string())),
_ => None,
}
}
fn until(rest: &mut std::str::Chars<'_>, end: char) -> Option<String> {
let mut text = String::new();
for ch in rest.by_ref() {
if ch == end {
return Some(text);
}
text.push(ch);
}
None
}
fn sections(code: &str) -> Option<Vec<&str>> {
let mut sections = Vec::new();
let (mut start, mut quoted, mut escaped) = (0, false, false);
for (at, ch) in code.char_indices() {
match ch {
_ if escaped => escaped = false,
'\\' if !quoted => escaped = true,
'"' => quoted = !quoted,
';' if !quoted => {
sections.push(code.get(start..at)?);
start = at + 1;
}
_ => {}
}
}
sections.push(code.get(start..)?);
(sections.len() <= CHART_FORMAT_SECTIONS).then_some(sections)
}
fn joined(pieces: Vec<LabelPiece>) -> Vec<LabelPiece> {
let mut out: Vec<LabelPiece> = Vec::with_capacity(pieces.len());
for piece in pieces {
match (out.last_mut(), piece) {
(Some(LabelPiece::Text(last)), LabelPiece::Text(text)) => last.push_str(&text),
(_, piece) => out.push(piece),
}
}
out
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Exponent {
upper: bool,
always_plus: bool,
digits: u32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Digits {
whole_places: u32,
whole: u32,
whole_pad: u32,
grouped: bool,
point: bool,
fixed: u32,
decimal_pad: u32,
most: u32,
exponent: Option<Exponent>,
}
impl Digits {
fn placeholder(&mut self, ch: char, stage: Stage) -> Option<Stage> {
match stage {
Stage::Before => self.whole_placeholder(ch, 0),
Stage::Whole(commas) => self.whole_placeholder(ch, commas),
Stage::Decimals(0) => self.decimal_placeholder(ch),
Stage::Exponent => self.exponent_placeholder(ch),
Stage::Decimals(_) | Stage::After => None,
}
}
fn whole_placeholder(&mut self, ch: char, commas: i32) -> Option<Stage> {
self.grouped |= commas > 0;
self.whole_places = self.whole_places.checked_add(1)?;
if ch == '0' || self.whole > 0 {
self.whole = self.whole.checked_add(1)?;
}
if ch == '0' || ch == '?' || self.whole_pad > 0 {
self.whole_pad = self.whole_pad.checked_add(1)?;
}
Some(Stage::Whole(0))
}
fn decimal_placeholder(&mut self, ch: char) -> Option<Stage> {
self.most = self.most.checked_add(1)?;
if ch == '0' {
self.fixed = self.most;
} else if ch == '?' {
self.decimal_pad = self.most;
}
Some(Stage::Decimals(0))
}
fn exponent_placeholder(&mut self, ch: char) -> Option<Stage> {
if ch != '0' {
return None;
}
let exp = self.exponent.as_mut()?;
exp.digits = exp.digits.checked_add(1)?;
Some(Stage::Exponent)
}
fn start_exponent(
&mut self,
ch: char,
rest: &mut std::str::Chars<'_>,
stage: Stage,
) -> Option<Stage> {
let valid_stage = matches!(stage, Stage::Whole(0) | Stage::Decimals(0));
if !valid_stage || self.whole_places != 1 || self.grouped || self.decimal_pad > 0 {
return None;
}
let always_plus = match rest.next()? {
'+' => true,
'-' => false,
_ => return None,
};
self.exponent = Some(Exponent {
upper: ch == 'E',
always_plus,
digits: 0,
});
Some(Stage::Exponent)
}
fn point(&mut self, stage: Stage) -> Option<Stage> {
match stage {
Stage::Before | Stage::Whole(0) => {
self.point = true;
Some(Stage::Decimals(0))
}
Stage::Whole(_) | Stage::Decimals(_) | Stage::Exponent | Stage::After => None,
}
}
fn write(self, value: Decimal, separators: NumberSeparators) -> Option<Vec<LabelPiece>> {
if let Some(exp) = self.exponent {
return self.write_scientific(value, separators, exp);
}
let (text, lead_blanks, trail_blanks) = self.format_decimal(value, separators)?;
let mut pieces = vec![LabelPiece::Blank(' '); lead_blanks];
if !text.is_empty() {
pieces.push(LabelPiece::Text(text));
}
pieces.extend(std::iter::repeat_n(LabelPiece::Blank(' '), trail_blanks));
Some(pieces)
}
fn format_decimal(
self,
value: Decimal,
separators: NumberSeparators,
) -> Option<(String, usize, usize)> {
let rounded = places(value, self.most)?;
let (whole, mut decimals) = split(rounded, self.most)?;
let fixed = usize::try_from(self.fixed).ok()?;
while decimals.len() > fixed && decimals.ends_with('0') {
decimals.pop();
}
let shown = whole.trim_start_matches('0');
let least = usize::try_from(self.whole).ok()?;
let zeros = least.saturating_sub(shown.len());
let lead_blanks = usize::try_from(self.whole_pad)
.ok()?
.saturating_sub(shown.len() + zeros);
let mut text = "0".repeat(zeros);
text.push_str(shown);
if self.grouped {
text = grouped(&text, separators.group());
}
if self.point {
text.push(separators.decimal());
text.push_str(&decimals);
}
let trail_blanks = usize::try_from(self.decimal_pad)
.ok()?
.saturating_sub(decimals.len());
Some((text, lead_blanks, trail_blanks))
}
fn write_scientific(
self,
value: Decimal,
separators: NumberSeparators,
exp: Exponent,
) -> Option<Vec<LabelPiece>> {
let (power, mantissa) = if value.digits == 0 {
(
0_i64,
Decimal {
digits: 0,
exponent: 0,
},
)
} else {
let rounded = significant(value, self.most.checked_add(1)?)?.normalized();
let power = leading_power(rounded);
let exponent = rounded.exponent.checked_sub(i32::try_from(power).ok()?)?;
(
power,
Decimal {
digits: rounded.digits,
exponent,
},
)
};
let (text, _, _) = self.format_decimal(mantissa, separators)?;
let width = usize::try_from(exp.digits).ok()?;
let letter = if exp.upper { 'E' } else { 'e' };
let sign = if power < 0 {
"-"
} else if exp.always_plus {
"+"
} else {
""
};
let shown = format!("{text}{letter}{sign}{:0>width$}", power.unsigned_abs());
Some(vec![LabelPiece::Text(shown)])
}
}
fn grouped(digits: &str, separator: char) -> String {
let count = digits.chars().count();
let mut out = String::with_capacity(digits.len() + count / CHART_DIGIT_GROUP);
for (at, ch) in digits.chars().enumerate() {
if at > 0 && (count - at).is_multiple_of(CHART_DIGIT_GROUP) {
out.push(separator);
}
out.push(ch);
}
out
}
fn split(value: Decimal, decimals: u32) -> Option<(String, String)> {
let digits = value.digits.unsigned_abs().to_string();
let shift = i64::from(value.exponent) + i64::from(decimals);
let zeros = usize::try_from(shift).ok()?;
let all = format!("{digits}{}", "0".repeat(zeros));
let decimals = usize::try_from(decimals).ok()?;
let padded = format!("{all:0>width$}", width = decimals + 1);
let (whole, fraction) = padded.split_at(padded.len() - decimals);
Some((whole.to_owned(), fraction.to_owned()))
}
fn digit_count(digits: i64) -> u32 {
digits
.unsigned_abs()
.checked_ilog10()
.map_or(1, |log| log + 1)
}
fn whole_digits(value: Decimal) -> Option<usize> {
let whole = i64::from(digit_count(value.digits)) + i64::from(value.exponent);
usize::try_from(whole.max(1)).ok()
}
fn significant(value: Decimal, count: u32) -> Option<Decimal> {
match digit_count(value.digits).checked_sub(count) {
Some(drop) if drop > 0 => dropped(value, drop),
_ => Some(value),
}
}
fn places(value: Decimal, count: u32) -> Option<Decimal> {
let below = -i64::from(value.exponent) - i64::from(count);
match u32::try_from(below) {
Ok(drop) if drop > 0 => dropped(value, drop),
_ => Some(value),
}
}
fn dropped(value: Decimal, drop: u32) -> Option<Decimal> {
let exponent = value.exponent.checked_add(i32::try_from(drop).ok()?)?;
let Some(power) = i128::from(TENTHS).checked_pow(drop) else {
return Some(Decimal {
digits: 0,
exponent,
});
};
let digits = i128::from(value.digits);
let rest = digits.checked_rem(power)?.checked_abs()?;
let away = rest.checked_mul(2)? >= power;
let kept = digits.checked_div(power)? + if away { digits.signum() } else { 0 };
Some(Decimal {
digits: i64::try_from(kept).ok()?,
exponent,
})
}
pub(crate) fn all_digits(value: Decimal) -> String {
let value = value.normalized();
let sign = if value.digits < 0 { "-" } else { "" };
let digits = value.digits.unsigned_abs().to_string();
match usize::try_from(-value.exponent) {
Ok(0) | Err(_) => {
let zeros = usize::try_from(value.exponent).unwrap_or(0);
format!("{sign}{digits}{}", "0".repeat(zeros))
}
Ok(places) if places < digits.len() => {
let (whole, fraction) = digits.split_at(digits.len() - places);
format!("{sign}{whole}.{fraction}")
}
Ok(places) => format!("{sign}0.{}{digits}", "0".repeat(places - digits.len())),
}
}
fn general(value: Decimal, (separators, place): (NumberSeparators, LabelPlace)) -> Option<String> {
let value = significant(value, CHART_SIGNIFICANT_DIGITS)?.normalized();
if value.digits == 0 {
return Some("0".to_owned());
}
let below = value.digits < 0;
let room = place
.general_characters()
.checked_sub(usize::from(below && place.counts_sign()))?;
let magnitude = Decimal {
digits: value.digits.checked_abs()?,
exponent: value.exponent,
};
let held = i64::from(digit_count(magnitude.digits));
let decimal = general_decimal(magnitude, (separators, room));
let scientific = general_scientific(magnitude, (separators, room));
let text = match (decimal, scientific) {
(Some((text, shown)), Some((_, other))) if shown.min(held) >= other.min(held) => text,
(Some((text, _)), None) | (_, Some((text, _))) => text,
(None, None) => return None,
};
Some(if below { format!("-{text}") } else { text })
}
fn general_decimal(
magnitude: Decimal,
(separators, room): (NumberSeparators, usize),
) -> Option<(String, i64)> {
let left = room.checked_sub(whole_digits(magnitude)?)?;
let decimals = u32::try_from(left.saturating_sub(1)).ok()?;
let shown = i64::from(decimals) + leading_power(magnitude) + 1;
let rounded = places(magnitude, decimals)?.normalized();
if rounded.digits == 0 {
return None;
}
let (mut text, fraction) = split(rounded, decimals)?;
let fraction = fraction.trim_end_matches('0');
if !fraction.is_empty() {
text.push(separators.decimal());
text.push_str(fraction);
}
(text.chars().count() <= room).then_some((text, shown))
}
fn general_scientific(
magnitude: Decimal,
(separators, room): (NumberSeparators, usize),
) -> Option<(String, i64)> {
let mut best = None;
for kept in 1..=CHART_SIGNIFICANT_DIGITS {
let (length, text) = scientific(magnitude, kept, separators)?;
if length > room {
break;
}
best = Some((text, i64::from(kept)));
}
best
}
fn scientific(value: Decimal, kept: u32, separators: NumberSeparators) -> Option<(usize, String)> {
let rounded = significant(value, kept)?.normalized();
let power = leading_power(rounded);
let digits = rounded.digits.unsigned_abs().to_string();
let width = usize::try_from(kept).ok()?;
let padded = format!("{digits:0<width$}");
let (first, rest) = padded.split_at(1);
let width = usize::try_from(CHART_EXPONENT_DIGITS).ok()?;
let exponent_sign = if power < 0 { '-' } else { '+' };
let exponent = format!("E{exponent_sign}{:0>width$}", power.unsigned_abs());
let length = padded.len() + usize::from(!rest.is_empty()) + exponent.len();
let rest = rest.trim_end_matches('0');
let text = if rest.is_empty() {
format!("{first}{exponent}")
} else {
format!("{first}{}{rest}{exponent}", separators.decimal())
};
Some((length, text))
}
fn leading_power(value: Decimal) -> i64 {
i64::from(digit_count(value.digits)) - 1 + i64::from(value.exponent)
}
#[cfg(test)]
mod tests;