use cadkit_core::{Props, Value};
pub const LEVEL_ID: &str = "dgn.level_id";
pub const COLOR_INDEX: &str = "dgn.color_index";
pub const WEIGHT: &str = "dgn.weight";
pub const STYLE: &str = "dgn.style";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct Symbology {
pub level: Option<u32>,
pub color_index: Option<u32>,
pub weight: Option<u32>,
pub style: Option<u32>,
}
impl Symbology {
pub const fn new() -> Self {
Self {
level: None,
color_index: None,
weight: None,
style: None,
}
}
pub fn from_props(props: &Props) -> Self {
let get = |key: &str| match props.get(key) {
Some(Value::Int(n)) => u32::try_from(*n).ok(),
_ => None,
};
Self {
level: get(LEVEL_ID),
color_index: get(COLOR_INDEX),
weight: get(WEIGHT),
style: get(STYLE),
}
}
pub fn write_props(&self, props: &mut Props) {
for (key, value) in [
(LEVEL_ID, self.level),
(COLOR_INDEX, self.color_index),
(WEIGHT, self.weight),
(STYLE, self.style),
] {
match value {
Some(v) => {
props.insert(key.to_owned(), Value::Int(i64::from(v)));
}
None => {
props.remove(key);
}
}
}
}
#[must_use]
pub const fn with_level(mut self, level: u32) -> Self {
self.level = Some(level);
self
}
#[must_use]
pub const fn with_color_index(mut self, color_index: u32) -> Self {
self.color_index = Some(color_index);
self
}
#[must_use]
pub const fn with_weight(mut self, weight: u32) -> Self {
self.weight = Some(weight);
self
}
#[must_use]
pub const fn with_style(mut self, style: u32) -> Self {
self.style = Some(style);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_through_props_and_ignores_foreign_values() {
let mut props = Props::new();
props.insert("dxf.other".into(), Value::Int(1));
props.insert(STYLE.into(), Value::Text("dashed".into()));
assert_eq!(Symbology::from_props(&props), Symbology::new());
let s = Symbology::new()
.with_level(3)
.with_color_index(5)
.with_weight(2);
s.write_props(&mut props);
assert_eq!(Symbology::from_props(&props), s);
assert!(!props.contains_key(STYLE));
assert_eq!(props.get(COLOR_INDEX), Some(&Value::Int(5)));
assert!(props.contains_key("dxf.other"));
props.insert(WEIGHT.into(), Value::Int(-1));
assert_eq!(Symbology::from_props(&props).weight, None);
}
}