mycelium_util/io/
initializer.rs

1use core::ptr;
2
3/// A type used to conditionally initialize buffers passed to `Read` methods.
4#[derive(Debug)]
5pub struct Initializer(bool);
6
7impl Initializer {
8    /// Returns a new `Initializer` which will zero out buffers.
9    #[inline]
10    pub fn zeroing() -> Initializer {
11        Initializer(true)
12    }
13
14    /// Returns a new `Initializer` which will not zero out buffers.
15    ///
16    /// # Safety
17    ///
18    /// This may only be called by `Read`ers which guarantee that they will not
19    /// read from buffers passed to `Read` methods, and that the return value of
20    /// the method accurately reflects the number of bytes that have been
21    /// written to the head of the buffer.
22    #[inline]
23    pub unsafe fn nop() -> Initializer {
24        Initializer(false)
25    }
26
27    /// Indicates if a buffer should be initialized.
28    #[inline]
29    pub fn should_initialize(&self) -> bool {
30        self.0
31    }
32
33    /// Initializes a buffer if necessary.
34    #[inline]
35    pub fn initialize(&self, buf: &mut [u8]) {
36        if self.should_initialize() {
37            unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
38        }
39    }
40}