layline_codegen/model/
choice.rs1use alloc::string::String;
4use alloc::vec::Vec;
5
6use super::Derive;
7
8use super::{Endian, Segment};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum Discriminant {
14 Field(String),
18 BodyLength,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct Arm {
28 pub value: u64,
30 pub body: Vec<Segment>,
32 pub name: String,
34 pub doc: Option<String>,
36}
37
38impl Arm {
39 #[must_use]
41 pub fn new(value: u64, name: &str, body: Vec<Segment>) -> Self {
42 Self { value, body, name: String::from(name), doc: None }
43 }
44
45 #[must_use]
47 pub fn with_doc(self, doc: &str) -> Self {
48 Self { doc: Some(String::from(doc)), ..self }
49 }
50
51 #[must_use]
53 pub fn open_ended(&self) -> bool {
54 self.body.iter().any(Segment::open_ended)
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
63#[non_exhaustive]
64pub struct ChoiceDef {
65 pub name: String,
67 pub endian: Endian,
69 pub arms: Vec<Arm>,
71 pub other: Option<String>,
73 pub other_bytes: Option<usize>,
77 pub doc: Option<String>,
79 pub derives: Vec<Derive>,
81}
82
83impl ChoiceDef {
84 #[must_use]
86 pub fn new(name: &str, arms: Vec<Arm>) -> Self {
87 Self {
88 name: String::from(name),
89 endian: Endian::Le,
90 arms,
91 other: None,
92 other_bytes: None,
93 doc: None,
94 derives: Vec::new(),
95 }
96 }
97
98 #[must_use]
100 pub fn with_derives(self, derives: Vec<Derive>) -> Self {
101 Self { derives, ..self }
102 }
103
104 #[must_use]
106 pub fn with_endian(self, endian: Endian) -> Self {
107 Self { endian, ..self }
108 }
109
110 #[must_use]
112 pub fn with_other(self, other: &str) -> Self {
113 Self { other: Some(String::from(other)), ..self }
114 }
115
116 #[must_use]
120 pub fn with_other_bytes(self, bytes: usize) -> Self {
121 Self { other_bytes: Some(bytes), ..self }
122 }
123
124 #[must_use]
126 pub fn with_doc(self, doc: &str) -> Self {
127 Self { doc: Some(String::from(doc)), ..self }
128 }
129
130 #[must_use]
134 pub fn open_ended(&self) -> bool {
135 (self.other.is_some() && self.other_bytes.is_none())
136 || self.arms.iter().any(Arm::open_ended)
137 }
138}