asciidork_meta/
job_attrs.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::collections::HashMap;

use crate::internal::*;
use crate::validate;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobAttr {
  pub readonly: bool,
  pub value: AttrValue,
}

impl JobAttr {
  pub fn modifiable(value: impl Into<AttrValue>) -> Self {
    Self { readonly: false, value: value.into() }
  }

  pub fn readonly(value: impl Into<AttrValue>) -> Self {
    Self { readonly: true, value: value.into() }
  }
}

#[derive(Clone, PartialEq, Eq, Default)]
pub struct JobAttrs(HashMap<String, JobAttr>);

impl JobAttrs {
  pub fn empty() -> Self {
    Self(HashMap::new())
  }

  pub fn insert(&mut self, key: impl Into<String>, job_attr: JobAttr) -> Result<(), String> {
    let key: String = key.into();
    validate::attr(self, &key, &job_attr.value)?;
    self.0.insert(key, job_attr);
    Ok(())
  }

  pub fn insert_unchecked(&mut self, key: impl Into<String>, job_attr: JobAttr) {
    let key: String = key.into();
    self.0.insert(key, job_attr);
  }

  pub fn get(&self, key: &str) -> Option<&JobAttr> {
    self.0.get(key)
  }

  pub fn remove(&mut self, key: &str) {
    self.0.remove(key);
  }
}

impl std::fmt::Debug for JobAttrs {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "JobAttrs(<num attrs: {}>)", self.0.len())
  }
}

impl ReadAttr for JobAttrs {
  fn get(&self, key: &str) -> Option<&AttrValue> {
    self.0.get(key).map(|attr| &attr.value)
  }
}

impl RemoveAttr for JobAttrs {
  fn remove(&mut self, key: &str) {
    self.0.remove(key);
  }
}

impl AsRef<HashMap<String, JobAttr>> for JobAttrs {
  fn as_ref(&self) -> &HashMap<String, JobAttr> {
    &self.0
  }
}