Skip to content

Commit e078a42

Browse files
committed
fam: add FamStructWrapper::from_header
Add a utility function for constructing an empty FamStructWrapper with a given header. Signed-off-by: Patrick Roy <[email protected]>
1 parent e4aa208 commit e078a42

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/fam.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,23 @@ impl<T: Default + FamStruct> FamStructWrapper<T> {
249249
Ok(FamStructWrapper { mem_allocator })
250250
}
251251

252+
/// Constructs a FamStructWrapper with an empty flexible array member
253+
/// from the given FamStruct header.
254+
///
255+
/// # Errors
256+
///
257+
/// If the length stored in the header is not 0, returns [`Error::SizeLimitExceeded`]
258+
pub fn from_header(header: T) -> Result<FamStructWrapper<T>, Error> {
259+
if header.len() != 0 {
260+
return Err(Error::SizeLimitExceeded);
261+
}
262+
263+
// SAFETY: We are passing an array of length 1, which corresponds to exactly
264+
// the header. The length inside the header is set to 0, and there are also no
265+
// further elements in the vector that would constitute any T::Entry.
266+
unsafe { Ok(Self::from_raw(vec![header])) }
267+
}
268+
252269
/// Create a new FamStructWrapper from a slice of elements.
253270
///
254271
/// # Arguments
@@ -965,6 +982,21 @@ mod tests {
965982
assert!(adapter == adapter.clone());
966983
}
967984

985+
#[test]
986+
fn test_from_header() {
987+
let header = MockFamStruct::default();
988+
let wrapper = MockFamStructWrapper::from_header(header).unwrap();
989+
assert_eq!(wrapper.len(), 0);
990+
assert_eq!(wrapper.as_fam_struct_ref().len, 0);
991+
992+
let header = MockFamStruct {
993+
len: 100,
994+
..Default::default()
995+
};
996+
let error = MockFamStructWrapper::from_header(header);
997+
assert!(matches!(error, Err(Error::SizeLimitExceeded)));
998+
}
999+
9681000
#[test]
9691001
fn test_raw_content() {
9701002
let data = vec![

0 commit comments

Comments
 (0)