multiboot2_common/
bytes_ref.rs

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
//! Module for [`BytesRef`].

use crate::{ALIGNMENT, Header, MemoryError};
use core::marker::PhantomData;
use core::mem;
use core::ops::Deref;

/// Wraps a byte slice representing a Multiboot2 structure including an optional
/// terminating padding, if necessary.
///
/// This type helps that casts to a specific tag from the underlying bytes are
/// either same-size casts or down-size casts, but never upsize-casts, which are
/// illegal and UB! Instances of this type guarantee that the memory
/// requirements promised in the crates description are respected.
#[derive(Clone, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct BytesRef<'a, H: Header> {
    bytes: &'a [u8],
    // Ensure that consumers can rely on the size properties for `H` that
    // already have been verified when this type was constructed.
    _h: PhantomData<H>,
}

impl<'a, H: Header> TryFrom<&'a [u8]> for BytesRef<'a, H> {
    type Error = MemoryError;

    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        if bytes.len() < mem::size_of::<H>() {
            return Err(MemoryError::ShorterThanHeader);
        }
        // Doesn't work as expected: if align_of_val(&value[0]) < ALIGNMENT {
        if bytes.as_ptr().align_offset(ALIGNMENT) != 0 {
            return Err(MemoryError::WrongAlignment);
        }
        let padding_bytes = bytes.len() % ALIGNMENT;
        if padding_bytes != 0 {
            return Err(MemoryError::MissingPadding);
        }
        Ok(Self {
            bytes,
            _h: PhantomData,
        })
    }
}

impl<'a, H: Header> Deref for BytesRef<'a, H> {
    type Target = &'a [u8];

    fn deref(&self) -> &Self::Target {
        &self.bytes
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{AlignedBytes, DummyTestHeader};

    #[test]
    fn test_bytes_ref() {
        let empty: &[u8] = &[];
        assert_eq!(
            BytesRef::<'_, DummyTestHeader>::try_from(empty),
            Err(MemoryError::ShorterThanHeader)
        );

        let slice = &[0_u8, 1, 2, 3, 4, 5, 6];
        assert_eq!(
            BytesRef::<'_, DummyTestHeader>::try_from(&slice[..]),
            Err(MemoryError::ShorterThanHeader)
        );

        let slice = AlignedBytes([0_u8, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0]);
        // Guaranteed wrong alignment
        let unaligned_slice = &slice[3..];
        assert_eq!(
            BytesRef::<'_, DummyTestHeader>::try_from(unaligned_slice),
            Err(MemoryError::WrongAlignment)
        );

        let slice = AlignedBytes([0_u8, 1, 2, 3, 4, 5, 6, 7]);
        let slice = &slice[..];
        assert_eq!(
            BytesRef::try_from(slice),
            Ok(BytesRef {
                bytes: slice,
                _h: PhantomData::<DummyTestHeader>
            })
        );
    }
}