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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
//! Simple cursor
//!
//! This module contains a very simple cursor, similar to std::io's, but without
//! relying on the io module. It also offers additional convenience functions to
//! make writing PODs easy.
//!
//! If std::io is ever ported to core::io, this module can disappear.
//!
//! - https://github.com/rust-lang/rust/issues/48331
//! - https://github.com/rust-lang-nursery/portability-wg/issues/12

use byteorder::ByteOrder;
use core::mem::{size_of, MaybeUninit};
use core::slice;

// TODO: Cursor read_raw/write_raw is totally unsafe.
// BODY: Libutils' Cursor allows creating a structure from a byte array, by doing
// BODY: pointer magic fuckery. We should be using a crate like Plain instead,
// BODY: which properly encapsulates the unsafety.

/// A minimal Cursor for writing, for use in libcore.
///
/// See https://doc.rust-lang.org/std/io/struct.Cursor.html
#[derive(Debug)]
pub struct CursorWrite<'a> {
    /// Data backing this cursor.
    data: &'a mut [u8],
    /// Position of the cursor in the data.
    pos: usize
}

impl<'a> CursorWrite<'a> {
    /// Creates a new cursor wrapping the provided underlying in-memory buffer.
    pub fn new(data: &mut [u8]) -> CursorWrite<'_> {
        CursorWrite {
            data: data,
            pos: 0
        }
    }

    /// Returns the current position of this cursor.
    pub fn pos(&self) -> usize {
        self.pos
    }

    /// Skip the given amount of bytes, returning a mutable slice to it.
    pub fn skip_write(&mut self, bytelen: usize) -> &mut [u8] {
        let ret = &mut self.data[self.pos..self.pos + bytelen];
        self.pos += bytelen;
        ret
    }

    /// Writes an u8 in the given byte ordering.
    pub fn write_u8<BO: ByteOrder>(&mut self, v: u8) {
        self.data[self.pos] = v;
        self.pos += 1;
    }
    /// Writes a u16 in the given byte ordering.
    pub fn write_u16<BO: ByteOrder>(&mut self, v: u16) {
        BO::write_u16(&mut self.data[self.pos..], v);
        self.pos += 2;
    }
    /// Writes a u32 in the given byte ordering.
    pub fn write_u32<BO: ByteOrder>(&mut self, v: u32) {
        BO::write_u32(&mut self.data[self.pos..], v);
        self.pos += 4;
    }
    /// Writes a u64 in the given byte ordering.
    pub fn write_u64<BO: ByteOrder>(&mut self, v: u64) {
        BO::write_u64(&mut self.data[self.pos..], v);
        self.pos += 8;
    }
    /// Writes the given byte slice entirely.
    pub fn write(&mut self, v: &[u8]) {
        self.data[self.pos..self.pos + v.len()].copy_from_slice(v);
        self.pos += v.len();
    }

    /// Writes the given structure.
    pub fn write_raw<T: Copy>(&mut self, v: T) {
        let ptr = &v;
        let arr = unsafe {
            slice::from_raw_parts(ptr as *const T as *const u8, size_of::<T>())
        };
        self.skip_write(size_of::<T>()).copy_from_slice(arr);
    }
}

/// A minimal Cursor for writing, for use in libcore.
///
/// See https://doc.rust-lang.org/std/io/struct.Cursor.html
#[derive(Debug)]
pub struct CursorRead<'a> {
    /// Data backing this cursor.
    data: &'a [u8],
    // Let's cheat
    /// Position of the cursor in the data.
    pos: ::core::cell::Cell<usize>
}

impl<'a> CursorRead<'a> {
    /// Creates a new cursor wrapping the provided underlying in-memory buffer.
    pub fn new(data: &[u8]) -> CursorRead<'_> {
        CursorRead {
            data: data,
            pos: 0.into()
        }
    }

    /// Returns the current position of this cursor.
    pub fn pos(&self) -> usize {
        self.pos.get()
    }

    /// Reads an u8 in the given byteorder.
    pub fn read_u8<BO: ByteOrder>(&self) -> u8 {
        let ret = self.data[self.pos.get()];
        self.pos.set(self.pos.get() + 1);
        ret
    }
    /// Reads an u16 in the given byteorder.
    pub fn read_u16<BO: ByteOrder>(&self) -> u16 {
        let ret = BO::read_u16(&self.data[self.pos.get()..]);
        self.pos.set(self.pos.get() + 2);
        ret
    }
    /// Reads an u32 in the given byteorder.
    pub fn read_u32<BO: ByteOrder>(&self) -> u32 {
        let ret = BO::read_u32(&self.data[self.pos.get()..]);
        self.pos.set(self.pos.get() + 4);
        ret
    }
    /// Reads an u64 in the given byteorder.
    pub fn read_u64<BO: ByteOrder>(&self) -> u64 {
        let ret = BO::read_u64(&self.data[self.pos.get()..]);
        self.pos.set(self.pos.get() + 8);
        ret
    }

    /// Reads `v.len()` bytes from the stream, and asserts that it is equal to
    /// `v`.
    pub fn assert(&self, v: &[u8]) {
        assert_eq!(&self.data[self.pos.get()..self.pos.get() + v.len()], v);
        self.pos.set(self.pos.get() + v.len());
    }

    /// Skips `bytelen` bytes, returning a slice to them for inspection.
    pub fn skip_read(&self, bytelen: usize) -> &[u8] {
        let ret = &self.data[self.pos.get()..self.pos.get() + bytelen];
        self.pos.set(self.pos.get() + bytelen);
        ret
    }

    /// Reads the given structure from the bytestream.
    pub fn read_raw<T: Copy>(&self) -> T {
        unsafe {
            let mut v: MaybeUninit<T> = MaybeUninit::uninit();
            core::ptr::copy(self.skip_read(size_of::<T>()).as_ptr(), v.as_mut_ptr() as *mut u8, size_of::<T>());
            v.assume_init()
        }
    }
}