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
120
121
122
123
124
125
126
127
128
129
130
use core::fmt::{self, Debug, Formatter};

/// Read an [`InlineResource`]'s data from its binary form in memory.
///
/// # Examples
///
/// ```rust
/// # use hotg_rune_core::{decode_inline_resource, InlineResource};
/// let resource = InlineResource::new(*b"Name", *b"Some Value");
/// let bytes = resource.as_bytes();
///
/// let (name, value, rest) = decode_inline_resource(bytes).unwrap();
///
/// assert_eq!(name, "Name");
/// assert_eq!(value, b"Some Value");
/// assert!(rest.is_empty());
/// ```
pub fn decode_inline_resource(bytes: &[u8]) -> Option<(&str, &[u8], &[u8])> {
    let (name_len, rest) = read_u32(bytes)?;
    if rest.len() < name_len {
        return None;
    }
    let (name, bytes) = rest.split_at(name_len);
    let name = core::str::from_utf8(name).ok()?;

    let (data_len, bytes) = read_u32(bytes)?;
    if bytes.len() < data_len {
        return None;
    }
    let (data, bytes) = bytes.split_at(data_len as usize);

    Some((name, data, bytes))
}

fn read_u32(buffer: &[u8]) -> Option<(usize, &[u8])> {
    if buffer.len() < 4 {
        return None;
    }

    let (head, tail) = buffer.split_at(4);

    let mut number = [0; 4];
    number.copy_from_slice(head);

    Some((u32::from_be_bytes(number) as usize, tail))
}

/// A `(&str, &[u8])` which stores the first field (name) and second field
/// (data) inline and can be read out of memory using
/// [`decode_inline_resource()`].
#[derive(Clone, PartialEq)]
#[repr(C)]
pub struct InlineResource<const NAME_LEN: usize, const DATA_LEN: usize> {
    _name_len: [u8; 4],
    name: [u8; NAME_LEN],
    _data_len: [u8; 4],
    data: [u8; DATA_LEN],
}

impl<const NAME_LEN: usize, const DATA_LEN: usize>
    InlineResource<NAME_LEN, DATA_LEN>
{
    pub const fn new(name: [u8; NAME_LEN], data: [u8; DATA_LEN]) -> Self {
        InlineResource {
            _name_len: (NAME_LEN as u32).to_be_bytes(),
            name,
            _data_len: (DATA_LEN as u32).to_be_bytes(),
            data,
        }
    }

    fn name(&self) -> Option<&str> {
        core::str::from_utf8(self.name_raw()).ok()
    }

    fn name_raw(&self) -> &[u8] { &self.name }

    fn data(&self) -> &[u8] { &self.data }

    pub fn as_bytes(&self) -> &[u8] {
        unsafe {
            core::slice::from_raw_parts(
                self as *const Self as *const u8,
                core::mem::size_of::<Self>(),
            )
        }
    }
}

impl<const NAME_LEN: usize, const DATA_LEN: usize> Debug
    for InlineResource<NAME_LEN, DATA_LEN>
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("InlineResource");

        match self.name() {
            Some(n) => {
                d.field("name", &n);
            },
            None => {
                d.field("name", &"(non-utf8)");
            },
        }

        d.field(
            "data",
            &format_args!("({} bytes hidden)", self.data().len()),
        );

        d.finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn read_from_binary() {
        let resource = InlineResource::new(*b"name", *b"value");
        let as_bytes = resource.as_bytes();

        let (got_name, got_value, rest) =
            decode_inline_resource(as_bytes).unwrap();

        assert_eq!(got_name, resource.name().unwrap());
        assert_eq!(got_value, resource.data());
        assert!(rest.is_empty());
    }
}