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
use crate::{
constants::{ENUM_DISCRIMINANT_WORD_WIDTH, WORD_SIZE},
errors::{error, Error, Result},
param_types::ParamType,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumVariants {
variants: Vec<(String, ParamType)>,
}
impl EnumVariants {
pub fn new(variants: Vec<(String, ParamType)>) -> Result<EnumVariants> {
if !variants.is_empty() {
Ok(EnumVariants { variants })
} else {
Err(error!(InvalidData, "Enum variants can not be empty!"))
}
}
pub fn variants(&self) -> &Vec<(String, ParamType)> {
&self.variants
}
pub fn param_types(&self) -> Vec<ParamType> {
self.variants
.iter()
.map(|(_, param_type)| param_type)
.cloned()
.collect()
}
pub fn select_variant(&self, discriminant: u8) -> Result<&(String, ParamType)> {
self.variants.get(discriminant as usize).ok_or_else(|| {
error!(
InvalidData,
"Discriminant '{discriminant}' doesn't point to any variant: {:?}",
self.variants()
)
})
}
pub fn only_units_inside(&self) -> bool {
self.variants
.iter()
.all(|(_, variant)| *variant == ParamType::Unit)
}
pub fn compute_encoding_width_of_enum(&self) -> usize {
if self.only_units_inside() {
return ENUM_DISCRIMINANT_WORD_WIDTH;
}
self.param_types()
.iter()
.map(|p| p.compute_encoding_width())
.max()
.map(|width| width + ENUM_DISCRIMINANT_WORD_WIDTH)
.expect(
"Will never panic because EnumVariants must have at least one variant inside it!",
)
}
pub fn compute_padding_amount(&self, variant_param_type: &ParamType) -> usize {
let biggest_variant_width =
self.compute_encoding_width_of_enum() - ENUM_DISCRIMINANT_WORD_WIDTH;
let variant_width = variant_param_type.compute_encoding_width();
(biggest_variant_width - variant_width) * WORD_SIZE
}
}