use std::fmt;
use std::sync::Arc;
use crate::theme::Color;
use crate::token::{valid_static_token, validate_token};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct StyleAttr(&'static str);
impl StyleAttr {
pub const fn from_static(value: &'static str) -> Self {
if !valid_static_token(value) {
panic!("invalid style attribute name");
}
Self(value)
}
pub fn checked(value: &'static str) -> Result<Self, StyleAttrError> {
validate_token(value).map_err(StyleAttrError)?;
Ok(Self(value))
}
pub const fn as_str(&self) -> &'static str {
self.0
}
}
impl fmt::Display for StyleAttr {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.0)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyleAttrError(crate::TokenIdError);
impl fmt::Display for StyleAttrError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "invalid style attribute name: {}", self.0)
}
}
impl std::error::Error for StyleAttrError {}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttrValue {
Color(Color),
Flag(bool),
Number(i32),
Index(u32),
}
impl AttrValue {
pub const fn as_color(self) -> Option<Color> {
match self {
Self::Color(color) => Some(color),
_ => None,
}
}
pub const fn as_flag(self) -> Option<bool> {
match self {
Self::Flag(value) => Some(value),
_ => None,
}
}
pub const fn as_number(self) -> Option<i32> {
match self {
Self::Number(value) => Some(value),
_ => None,
}
}
pub const fn as_index(self) -> Option<u32> {
match self {
Self::Index(value) => Some(value),
_ => None,
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AttrSet {
entries: Option<Arc<Vec<(StyleAttr, AttrValue)>>>,
}
impl AttrSet {
pub const fn new() -> Self {
Self { entries: None }
}
#[must_use]
pub fn set(self, attr: StyleAttr, value: AttrValue) -> Self {
let mut entries = self.as_slice().to_vec();
if let Some((_, slot)) = entries.iter_mut().find(|(name, _)| *name == attr) {
if *slot == value {
return self;
}
*slot = value;
} else {
entries.push((attr, value));
}
Self::from_entries(entries)
}
fn as_slice(&self) -> &[(StyleAttr, AttrValue)] {
self.entries.as_deref().map(Vec::as_slice).unwrap_or(&[])
}
pub fn get(&self, attr: StyleAttr) -> Option<AttrValue> {
self.as_slice()
.iter()
.find(|(name, _)| *name == attr)
.map(|(_, value)| *value)
}
pub fn contains(&self, attr: StyleAttr) -> bool {
self.get(attr).is_some()
}
pub fn remove(&mut self, attr: StyleAttr) -> Option<AttrValue> {
let position = self.as_slice().iter().position(|(name, _)| *name == attr)?;
let mut entries = self.as_slice().to_vec();
let (_, value) = entries.remove(position);
*self = Self::from_entries(entries);
Some(value)
}
pub fn len(&self) -> usize {
self.as_slice().len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_none()
}
pub fn iter(&self) -> impl Iterator<Item = (StyleAttr, AttrValue)> + '_ {
self.as_slice().iter().copied()
}
#[must_use]
pub fn merged(mut self, patch: &Self) -> Self {
for (attr, value) in patch.iter() {
self = self.set(attr, value);
}
self
}
fn from_entries(entries: Vec<(StyleAttr, AttrValue)>) -> Self {
if entries.is_empty() {
Self::new()
} else {
Self {
entries: Some(Arc::new(entries)),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const GRID_FILL: StyleAttr = StyleAttr::from_static("grid.fill");
const BLINK: StyleAttr = StyleAttr::from_static("blink");
#[test]
fn attributes_round_trip_by_name() {
let set = AttrSet::new()
.set(GRID_FILL, AttrValue::Number(0x2591))
.set(BLINK, AttrValue::Flag(true));
assert_eq!(set.get(GRID_FILL), Some(AttrValue::Number(0x2591)));
assert_eq!(set.get(BLINK), Some(AttrValue::Flag(true)));
assert_eq!(set.len(), 2);
}
#[test]
fn setting_the_same_name_replaces_rather_than_appends() {
let set = AttrSet::new()
.set(BLINK, AttrValue::Flag(true))
.set(BLINK, AttrValue::Flag(false));
assert_eq!(set.get(BLINK), Some(AttrValue::Flag(false)));
assert_eq!(set.len(), 1);
}
#[test]
fn attribute_count_is_not_artificially_capped() {
let mut set = AttrSet::new();
for name in [
"a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11",
] {
set = set.set(
StyleAttr::checked(name).expect("valid"),
AttrValue::Flag(true),
);
}
assert_eq!(set.len(), 12);
}
#[test]
fn removing_preserves_the_order_of_remaining_entries() {
let first = StyleAttr::from_static("first");
let second = StyleAttr::from_static("second");
let third = StyleAttr::from_static("third");
let mut set = AttrSet::new()
.set(first, AttrValue::Number(1))
.set(second, AttrValue::Number(2))
.set(third, AttrValue::Number(3));
assert_eq!(set.remove(second), Some(AttrValue::Number(2)));
assert_eq!(
set.iter().collect::<Vec<_>>(),
vec![(first, AttrValue::Number(1)), (third, AttrValue::Number(3)),]
);
}
#[test]
fn merging_lets_the_patch_win() {
let flag = StyleAttr::from_static("flag");
let base = AttrSet::new().set(flag, AttrValue::Flag(false));
let patch = AttrSet::new().set(flag, AttrValue::Flag(true));
assert_eq!(base.merged(&patch).get(flag), Some(AttrValue::Flag(true)));
}
#[test]
fn invalid_names_are_rejected() {
assert!(StyleAttr::checked("Not Valid").is_err());
}
}