tilo_action_policy/
kind.rs1use std::fmt;
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum ActionKind {
12 Read,
14 Undoable,
16 Outside,
18}
19
20impl ActionKind {
21 pub const ALL: [Self; 3] = [Self::Read, Self::Undoable, Self::Outside];
22
23 const fn bit(self) -> u8 {
24 match self {
25 Self::Read => 1,
26 Self::Undoable => 2,
27 Self::Outside => 4,
28 }
29 }
30
31 #[must_use]
33 pub const fn phrase(self) -> &'static str {
34 match self {
35 Self::Read => "reading",
36 Self::Undoable => "undoable changes",
37 Self::Outside => "outside effects",
38 }
39 }
40}
41
42impl fmt::Display for ActionKind {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.write_str(match self {
45 Self::Read => "read",
46 Self::Undoable => "undoable",
47 Self::Outside => "outside",
48 })
49 }
50}
51
52#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
54pub struct KindSet(u8);
55
56impl KindSet {
57 pub const NONE: Self = Self(0);
58 pub const READ: Self = Self(1);
59 pub const UNDOABLE: Self = Self(2);
60 pub const OUTSIDE: Self = Self(4);
61 pub const READ_UNDOABLE: Self = Self(3);
62 pub const ALL: Self = Self(7);
63
64 #[must_use]
65 pub const fn of(kind: ActionKind) -> Self {
66 Self(kind.bit())
67 }
68
69 #[must_use]
70 pub const fn contains(self, kind: ActionKind) -> bool {
71 self.0 & kind.bit() != 0
72 }
73
74 #[must_use]
75 pub const fn with(self, kind: ActionKind) -> Self {
76 Self(self.0 | kind.bit())
77 }
78
79 #[must_use]
80 pub const fn union(self, other: Self) -> Self {
81 Self(self.0 | other.0)
82 }
83
84 #[must_use]
85 pub const fn is_empty(self) -> bool {
86 self.0 == 0
87 }
88
89 pub fn iter(self) -> impl Iterator<Item = ActionKind> {
91 ActionKind::ALL
92 .into_iter()
93 .filter(move |kind| self.contains(*kind))
94 }
95}
96
97impl FromIterator<ActionKind> for KindSet {
98 fn from_iter<I: IntoIterator<Item = ActionKind>>(iter: I) -> Self {
99 iter.into_iter().fold(Self::NONE, Self::with)
100 }
101}
102
103impl From<ActionKind> for KindSet {
104 fn from(kind: ActionKind) -> Self {
105 Self::of(kind)
106 }
107}
108
109impl fmt::Debug for KindSet {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 f.debug_set().entries(self.iter()).finish()
112 }
113}
114
115impl Serialize for KindSet {
116 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
117 self.iter().collect::<Vec<_>>().serialize(serializer)
119 }
120}
121
122impl<'de> Deserialize<'de> for KindSet {
123 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
124 Ok(Vec::<ActionKind>::deserialize(deserializer)?
125 .into_iter()
126 .collect())
127 }
128}