use core::fmt;
use crate::Tag;
#[derive(Copy, Clone, Default, PartialEq)]
pub struct Synthesis {
flags: u8,
width: f32,
weight: f32,
slant: f32,
skew: i8,
}
impl Synthesis {
const HAS_WIDTH: u8 = 1 << 0;
const HAS_WEIGHT: u8 = 1 << 1;
const HAS_ITALIC: u8 = 1 << 2;
const HAS_SLANT: u8 = 1 << 3;
const EMBOLDEN: u8 = 1 << 4;
const VARIATIONS: u8 = Self::HAS_WIDTH | Self::HAS_WEIGHT | Self::HAS_ITALIC | Self::HAS_SLANT;
#[inline]
const fn has(self, flag: u8) -> bool {
self.flags & flag != 0
}
#[inline]
#[must_use]
pub const fn with_width(mut self, width: f32) -> Self {
self.width = width;
self.flags |= Self::HAS_WIDTH;
self
}
#[inline]
#[must_use]
pub const fn with_weight(mut self, weight: f32) -> Self {
self.weight = weight;
self.flags |= Self::HAS_WEIGHT;
self
}
#[inline]
#[must_use]
pub const fn with_italic(mut self) -> Self {
debug_assert!(!self.has(Self::HAS_SLANT), "slant is already set");
self.slant = 0.0;
self.flags = (self.flags & !Self::HAS_SLANT) | Self::HAS_ITALIC;
self
}
#[inline]
#[must_use]
pub const fn with_slant(mut self, slant: f32) -> Self {
debug_assert!(!self.has(Self::HAS_ITALIC), "italic is already set");
self.slant = slant;
self.flags = (self.flags & !Self::HAS_ITALIC) | Self::HAS_SLANT;
self
}
#[inline]
#[must_use]
pub const fn with_embolden(mut self, embolden: bool) -> Self {
if embolden {
self.flags |= Self::EMBOLDEN;
} else {
self.flags &= !Self::EMBOLDEN;
}
self
}
#[inline]
#[must_use]
pub const fn with_skew(mut self, degrees: i8) -> Self {
self.skew = degrees;
self
}
#[inline]
pub fn any(&self) -> bool {
self.flags != 0 || self.skew != 0
}
#[inline]
pub const fn has_variations(&self) -> bool {
self.has(Self::VARIATIONS)
}
#[inline]
pub fn variation_settings(&self) -> impl Iterator<Item = (Tag, f32)> + Clone + use<> {
let style = if self.has(Self::HAS_ITALIC) {
Some((Tag::new(b"ital"), 1.0))
} else {
self.has(Self::HAS_SLANT)
.then_some((Tag::new(b"slnt"), self.slant))
};
[
self.has(Self::HAS_WIDTH)
.then_some((Tag::new(b"wdth"), self.width)),
self.has(Self::HAS_WEIGHT)
.then_some((Tag::new(b"wght"), self.weight)),
style,
]
.into_iter()
.flatten()
}
#[inline]
pub fn embolden(&self) -> bool {
self.has(Self::EMBOLDEN)
}
#[inline]
pub fn skew(&self) -> Option<f32> {
if self.skew != 0 {
Some(self.skew as f32)
} else {
None
}
}
}
#[expect(
clippy::missing_fields_in_debug,
reason = "the fields are shown as the settings they represent"
)]
impl fmt::Debug for Synthesis {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct Vars(Synthesis);
impl fmt::Debug for Vars {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.variation_settings()).finish()
}
}
f.debug_struct("Synthesis")
.field("vars", &Vars(*self))
.field("embolden", &self.embolden())
.field("skew", &self.skew)
.finish()
}
}