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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use super::traits::StructAsBytes;
use crate::InformationRequestHeaderTag;
use crate::{HeaderTagFlag, MbiTagType};
use alloc::collections::BTreeSet;
use alloc::vec::Vec;
use core::fmt::Debug;
use core::mem::size_of;
#[derive(Debug)]
#[cfg(feature = "builder")]
pub struct InformationRequestHeaderTagBuilder {
flag: HeaderTagFlag,
irs: BTreeSet<MbiTagType>,
}
#[cfg(feature = "builder")]
impl InformationRequestHeaderTagBuilder {
pub fn new(flag: HeaderTagFlag) -> Self {
Self {
irs: BTreeSet::new(),
flag,
}
}
pub fn expected_len(&self) -> usize {
let basic_header_size = size_of::<InformationRequestHeaderTag<0>>();
let req_tags_size = self.irs.len() * size_of::<MbiTagType>();
basic_header_size + req_tags_size
}
pub fn add_ir(mut self, tag: MbiTagType) -> Self {
self.irs.insert(tag);
self
}
pub fn add_irs(mut self, tags: &[MbiTagType]) -> Self {
self.irs.extend(tags);
self
}
pub fn build(self) -> Vec<u8> {
let expected_len = self.expected_len();
let mut data = Vec::with_capacity(expected_len);
let basic_tag = InformationRequestHeaderTag::<0>::new(
self.flag,
[],
Some(expected_len as u32),
);
data.extend(basic_tag.struct_as_bytes());
#[cfg(debug_assertions)]
{
let basic_tag_size = size_of::<InformationRequestHeaderTag<0>>();
assert_eq!(
data.len(),
basic_tag_size,
"the vector must be as long as the basic tag!"
);
}
for tag in &self.irs {
let bytes: [u8; 4] = (*tag as u32).to_ne_bytes();
data.extend(&bytes);
}
debug_assert_eq!(
data.len(),
expected_len,
"the byte vector must be as long as the expected size of the struct"
);
data
}
}
#[cfg(test)]
mod tests {
use crate::builder::information_request::InformationRequestHeaderTagBuilder;
use crate::{HeaderTagFlag, InformationRequestHeaderTag, MbiTagType};
#[test]
fn test_builder() {
let builder = InformationRequestHeaderTagBuilder::new(HeaderTagFlag::Required)
.add_ir(MbiTagType::EfiMmap)
.add_ir(MbiTagType::BootLoaderName)
.add_ir(MbiTagType::Cmdline);
assert_eq!(builder.expected_len(), 2 + 2 + 4 + 3 * 4);
let tag = builder.build();
let tag = unsafe {
(tag.as_ptr() as *const InformationRequestHeaderTag<3>)
.as_ref()
.unwrap()
};
assert_eq!(tag.flags(), HeaderTagFlag::Required);
assert_eq!(tag.size(), 2 + 2 + 4 + 3 * 4);
assert_eq!(tag.dynamic_requests_size(), 3);
assert!(tag.requests().contains(&MbiTagType::EfiMmap));
assert!(tag.requests().contains(&MbiTagType::BootLoaderName));
assert!(tag.requests().contains(&MbiTagType::Cmdline));
assert_eq!(tag.requests().len(), 3);
assert!(!tag.requests().contains(&MbiTagType::AcpiV1));
println!("{:#?}", tag);
}
}