Skip to main content

geop_ops_model/
records.rs

1//! [`Records`]: what a part records of some of its entities besides their
2//! shape, by name — the cable a solid is swept from, the sheet a sheet-metal
3//! body is bent from — as the value of a target the steps that make them
4//! revise.
5
6use std::collections::BTreeMap;
7
8use geop_core_math::geop_error::{GeopError, GeopResult};
9use geop_core_program::target::Target;
10
11/// Records of `T`, by the name of what each is of.
12#[derive(Clone, Debug, PartialEq)]
13pub struct Records<T>(BTreeMap<String, T>);
14
15/// Every step that makes such an entity adds to them.
16impl<T: PartialEq + 'static> Target for Records<T> {
17    const CHAIN: bool = true;
18}
19
20impl<T> Default for Records<T> {
21    fn default() -> Self {
22        Self(BTreeMap::new())
23    }
24}
25
26impl<T> Records<T> {
27    /// Records `record` under `name`. Fails, leaving the records as they
28    /// are, if there is one of that name already.
29    pub fn add(&mut self, name: impl Into<String>, record: T) -> GeopResult<()> {
30        let name = name.into();
31        if self.0.contains_key(&name) {
32            return Err(GeopError::new(format!(
33                "the part has a record of {name:?} already"
34            )));
35        }
36        self.0.insert(name, record);
37        Ok(())
38    }
39
40    /// Records `record` under `name`, in place of what was.
41    pub fn insert(&mut self, name: impl Into<String>, record: T) {
42        self.0.insert(name.into(), record);
43    }
44
45    /// Takes the record of `name` out, if there is one: what it was of is
46    /// gone.
47    pub fn remove(&mut self, name: &str) -> Option<T> {
48        self.0.remove(name)
49    }
50
51    /// The record of `name`, if there is one.
52    pub fn get(&self, name: &str) -> Option<&T> {
53        self.0.get(name)
54    }
55
56    /// Every record, by name, in the order of the names.
57    pub fn iter(&self) -> impl Iterator<Item = (&str, &T)> {
58        self.0.iter().map(|(name, record)| (name.as_str(), record))
59    }
60}