use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct StyleId(u32);
impl StyleId {
#[must_use]
pub const fn from_index(index: u32) -> Self {
Self(index)
}
#[must_use]
pub const fn index(self) -> u32 {
self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Color {
#[default]
Auto,
Argb(u32),
Indexed(u32),
Theme {
id: u32,
tint: i32,
},
}
impl Color {
#[must_use]
pub fn from_argb_str(s: &str) -> Option<Self> {
if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let v = u32::from_str_radix(s, 16).ok()?;
match s.len() {
8 => Some(Self::Argb(v)),
6 => Some(Self::Argb(0xFF00_0000 | v)),
_ => None,
}
}
#[must_use]
pub fn to_argb_str(&self) -> Option<String> {
match self {
Self::Argb(v) => Some(format!("{v:08X}")),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Underline {
#[default]
None,
Single,
Double,
SingleAccounting,
DoubleAccounting,
}
impl Underline {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Single => "single",
Self::Double => "double",
Self::SingleAccounting => "singleAccounting",
Self::DoubleAccounting => "doubleAccounting",
}
}
#[must_use]
pub fn parse(s: &str) -> Self {
match s {
"none" => Self::None,
"double" => Self::Double,
"singleAccounting" => Self::SingleAccounting,
"doubleAccounting" => Self::DoubleAccounting,
_ => Self::Single,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Script {
#[default]
Baseline,
Superscript,
Subscript,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Font {
pub name: String,
pub size: u32,
pub bold: bool,
pub italic: bool,
pub underline: Underline,
pub strike: bool,
pub color: Color,
pub script: Script,
pub family: Option<u32>,
pub charset: Option<u32>,
pub scheme: Option<FontScheme>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FontScheme {
Major,
Minor,
}
impl FontScheme {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
match value {
"major" => Some(Self::Major),
"minor" => Some(Self::Minor),
_ => None,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Major => "major",
Self::Minor => "minor",
}
}
}
impl Font {
#[must_use]
pub fn with(&self, run: &DiffFont) -> Self {
Self {
name: run.name.clone().unwrap_or_else(|| self.name.clone()),
size: run.size.unwrap_or(self.size),
bold: run.bold.unwrap_or(self.bold),
italic: run.italic.unwrap_or(self.italic),
underline: run.underline.unwrap_or(self.underline),
strike: run.strike.unwrap_or(self.strike),
color: run.color.clone().unwrap_or_else(|| self.color.clone()),
script: run.script.unwrap_or(self.script),
family: run.family.or(self.family),
charset: run.charset.or(self.charset),
scheme: run.scheme.or(self.scheme),
}
}
}
impl From<&Font> for DiffFont {
fn from(font: &Font) -> Self {
Self {
name: Some(font.name.clone()),
size: Some(font.size),
bold: Some(font.bold),
italic: Some(font.italic),
underline: Some(font.underline),
strike: Some(font.strike),
color: Some(font.color.clone()),
script: Some(font.script),
charset: font.charset,
family: font.family,
scheme: font.scheme,
}
}
}
impl Default for Font {
fn default() -> Self {
Self {
name: "Calibri".into(),
size: 1100,
bold: false,
italic: false,
underline: Underline::None,
strike: false,
color: Color::Auto,
script: Script::Baseline,
family: None,
charset: None,
scheme: None,
}
}
}
impl Font {
#[must_use]
pub fn size_points(&self) -> f64 {
f64::from(self.size) / 100.0
}
pub fn set_size_points(&mut self, points: f64) {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "font sizes are small positive numbers"
)]
{
self.size = (points.max(0.0) * 100.0).round() as u32;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Pattern {
#[default]
None,
Solid,
Named(&'static str),
}
const NAMED_PATTERNS: [&str; 17] = [
"darkDown",
"darkGray",
"darkGrid",
"darkHorizontal",
"darkTrellis",
"darkUp",
"darkVertical",
"gray0625",
"gray125",
"lightDown",
"lightGray",
"lightGrid",
"lightHorizontal",
"lightTrellis",
"lightUp",
"lightVertical",
"mediumGray",
];
impl Pattern {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Solid => "solid",
Self::Named(name) => name,
}
}
#[must_use]
pub fn parse(s: &str) -> Self {
match s {
"solid" => Self::Solid,
"none" | "" => Self::None,
other => NAMED_PATTERNS
.iter()
.find(|p| **p == other)
.map_or(Self::None, |p| Self::Named(p)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Fill {
pub pattern: Pattern,
pub foreground: Color,
pub background: Color,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BorderStyle {
#[default]
None,
Named(&'static str),
}
const BORDER_STYLES: [&str; 12] = [
"thin",
"medium",
"thick",
"dashed",
"dotted",
"double",
"hair",
"mediumDashed",
"dashDot",
"mediumDashDot",
"dashDotDot",
"mediumDashDotDot",
];
impl BorderStyle {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Named(name) => name,
}
}
#[must_use]
pub fn parse(s: &str) -> Self {
BORDER_STYLES
.iter()
.find(|b| **b == s)
.map_or(Self::None, |b| Self::Named(b))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Border {
pub style: BorderStyle,
pub color: Color,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Borders {
pub left: Border,
pub right: Border,
pub top: Border,
pub bottom: Border,
pub diagonal: Border,
pub diagonal_direction: DiagonalDirection,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum DiagonalDirection {
#[default]
None,
Up,
Down,
Both,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum HorizontalAlign {
#[default]
General,
Left,
Center,
Right,
Justify,
Fill,
CenterContinuous,
Distributed,
}
impl HorizontalAlign {
#[must_use]
pub const fn as_str(self) -> Option<&'static str> {
Some(match self {
Self::General => return None,
Self::Left => "left",
Self::Center => "center",
Self::Right => "right",
Self::Justify => "justify",
Self::Fill => "fill",
Self::CenterContinuous => "centerContinuous",
Self::Distributed => "distributed",
})
}
#[must_use]
pub fn parse(s: &str) -> Self {
match s {
"left" => Self::Left,
"center" => Self::Center,
"right" => Self::Right,
"justify" => Self::Justify,
"fill" => Self::Fill,
"centerContinuous" => Self::CenterContinuous,
"distributed" => Self::Distributed,
_ => Self::General,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum VerticalAlign {
#[default]
Bottom,
Top,
Center,
Justify,
Distributed,
}
impl VerticalAlign {
#[must_use]
pub const fn as_str(self) -> Option<&'static str> {
Some(match self {
Self::Bottom => return None,
Self::Top => "top",
Self::Center => "center",
Self::Justify => "justify",
Self::Distributed => "distributed",
})
}
#[must_use]
pub fn parse(s: &str) -> Self {
match s {
"top" => Self::Top,
"center" => Self::Center,
"justify" => Self::Justify,
"distributed" => Self::Distributed,
_ => Self::Bottom,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Alignment {
pub horizontal: HorizontalAlign,
pub vertical: VerticalAlign,
pub wrap_text: bool,
pub shrink_to_fit: bool,
pub indent: u32,
pub text_rotation: u32,
pub reading_order: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ProtectionState {
#[default]
Inherit,
On,
Off,
}
impl ProtectionState {
#[must_use]
pub const fn as_bool(self) -> Option<bool> {
match self {
Self::Inherit => None,
Self::On => Some(true),
Self::Off => Some(false),
}
}
#[must_use]
pub fn from_attr(s: &str) -> Self {
if s == "1" || s == "true" {
Self::On
} else {
Self::Off
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Protection {
pub locked: ProtectionState,
pub hidden: ProtectionState,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum NumberFormat {
#[default]
General,
Builtin(u16),
Custom(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Style {
pub number_format: NumberFormat,
pub font: Font,
pub fill: Fill,
pub borders: Borders,
pub alignment: Alignment,
pub protection: Protection,
pub checkbox: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct DiffFont {
pub name: Option<String>,
pub size: Option<u32>,
pub bold: Option<bool>,
pub italic: Option<bool>,
pub underline: Option<Underline>,
pub strike: Option<bool>,
pub color: Option<Color>,
pub script: Option<Script>,
pub charset: Option<u32>,
pub family: Option<u32>,
pub scheme: Option<FontScheme>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct DiffFill {
pub pattern: Option<Pattern>,
pub foreground: Option<Color>,
pub background: Option<Color>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct DiffBorders {
pub left: Option<Border>,
pub right: Option<Border>,
pub top: Option<Border>,
pub bottom: Option<Border>,
pub diagonal: Option<Border>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct DifferentialStyle {
pub font: Option<DiffFont>,
pub fill: Option<DiffFill>,
pub borders: Option<DiffBorders>,
pub number_format: Option<NumberFormat>,
pub alignment: Option<Alignment>,
pub protection: Option<Protection>,
}
#[derive(Debug, Clone)]
pub struct StyleTable {
styles: Vec<Style>,
index: HashMap<Style, StyleId>,
pub differential: Vec<DifferentialStyle>,
}
impl Default for StyleTable {
fn default() -> Self {
let default = Style::default();
Self {
styles: vec![default.clone()],
index: HashMap::from([(default, StyleId::default())]),
differential: Vec::new(),
}
}
}
impl StyleTable {
#[must_use]
pub fn from_styles(styles: Vec<Style>) -> Self {
if styles.is_empty() {
return Self::default();
}
let mut index = HashMap::new();
for (i, style) in styles.iter().enumerate() {
index
.entry(style.clone())
.or_insert_with(|| StyleId::from_index(u32::try_from(i).unwrap_or(u32::MAX)));
}
Self {
styles,
index,
differential: Vec::new(),
}
}
pub fn intern(&mut self, style: Style) -> StyleId {
if let Some(&id) = self.index.get(&style) {
return id;
}
let id = StyleId::from_index(u32::try_from(self.styles.len()).unwrap_or(u32::MAX));
self.styles.push(style.clone());
self.index.insert(style, id);
id
}
#[must_use]
pub fn get(&self, id: StyleId) -> Option<&Style> {
self.styles.get(id.index() as usize)
}
#[must_use]
pub fn all(&self) -> &[Style] {
&self.styles
}
#[must_use]
pub fn len(&self) -> usize {
self.styles.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::{
BorderStyle, Color, Font, NumberFormat, Pattern, Style, StyleId, StyleTable, Underline,
};
#[test]
fn argb_str_accepts_rrggbb_as_opaque() {
assert_eq!(
Color::from_argb_str("D8D8D8"),
Some(Color::Argb(0xFFD8_D8D8))
);
assert_eq!(
Color::from_argb_str("80D8D8D8"),
Some(Color::Argb(0x80D8_D8D8))
);
assert_eq!(Color::from_argb_str("D8D8"), None);
assert_eq!(Color::from_argb_str("+D8D8D8"), None);
}
#[test]
fn default_style_is_index_zero() {
let t = StyleTable::default();
assert_eq!(t.len(), 1);
assert_eq!(t.get(StyleId::default()), Some(&Style::default()));
}
#[test]
fn equal_styles_share_one_id() {
let mut t = StyleTable::default();
let percent = Style {
number_format: NumberFormat::Custom("0.00%".into()),
..Style::default()
};
let a = t.intern(percent.clone());
let b = t.intern(percent);
assert_eq!(a, b, "equal styles are not duplicated");
assert_eq!(t.len(), 2, "the default style plus one new one");
let other = t.intern(Style {
number_format: NumberFormat::Builtin(9),
..Style::default()
});
assert_ne!(a, other);
assert_eq!(
t.intern(Style::default()),
StyleId::default(),
"the default is already there"
);
}
#[test]
fn positional_table_keeps_duplicate_slots() {
let table = StyleTable::from_styles(vec![Style::default(), Style::default()]);
assert_eq!(table.len(), 2);
assert_eq!(table.get(StyleId::from_index(1)), Some(&Style::default()));
}
#[test]
fn unknown_id_is_none() {
assert!(StyleTable::default().get(StyleId::from_index(99)).is_none());
}
#[test]
fn colors_round_trip_through_argb() {
let c = Color::from_argb_str("FFFF0000").expect("valid argb");
assert_eq!(c, Color::Argb(0xFFFF_0000));
assert_eq!(c.to_argb_str().as_deref(), Some("FFFF0000"));
assert!(Color::from_argb_str("zzzzzzzz").is_none());
assert!(Color::Auto.to_argb_str().is_none());
}
#[test]
fn enum_attributes_round_trip() {
for u in [
Underline::None,
Underline::Single,
Underline::Double,
Underline::SingleAccounting,
Underline::DoubleAccounting,
] {
assert_eq!(Underline::parse(u.as_str()), u);
}
assert_eq!(Underline::parse(""), Underline::Single);
for p in [Pattern::None, Pattern::Solid, Pattern::Named("darkGrid")] {
assert_eq!(Pattern::parse(p.as_str()), p);
}
assert_eq!(
Pattern::parse("nonsense"),
Pattern::None,
"unknown patterns are dropped"
);
for b in [BorderStyle::None, BorderStyle::Named("mediumDashDot")] {
assert_eq!(BorderStyle::parse(b.as_str()), b);
}
}
#[test]
fn font_size_is_stored_in_hundredths() {
let mut f = Font::default();
assert!((f.size_points() - 11.0).abs() < f64::EPSILON);
f.set_size_points(11.5);
assert_eq!(f.size, 1150, "stored in hundredths of a point");
assert!((f.size_points() - 11.5).abs() < f64::EPSILON);
}
}
pub mod format;