summaryrefslogtreecommitdiffstats
path: root/rust/kernel/block/mq/raw_writer.rs
blob: 9222465d670bfebb4a84b68f68be1eccbe4ce38f (plain)
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
// SPDX-License-Identifier: GPL-2.0

use core::fmt::{self, Write};

use crate::error::Result;
use crate::prelude::EINVAL;

/// A mutable reference to a byte buffer where a string can be written into.
///
/// # Invariants
///
/// `buffer` is always null terminated.
pub(crate) struct RawWriter<'a> {
    buffer: &'a mut [u8],
    pos: usize,
}

impl<'a> RawWriter<'a> {
    /// Create a new `RawWriter` instance.
    fn new(buffer: &'a mut [u8]) -> Result<RawWriter<'a>> {
        *(buffer.last_mut().ok_or(EINVAL)?) = 0;

        // INVARIANT: We null terminated the buffer above.
        Ok(Self { buffer, pos: 0 })
    }

    pub(crate) fn from_array<const N: usize>(
        a: &'a mut [core::ffi::c_char; N],
    ) -> Result<RawWriter<'a>> {
        Self::new(
            // SAFETY: the buffer of `a` is valid for read and write as `u8` for
            // at least `N` bytes.
            unsafe { core::slice::from_raw_parts_mut(a.as_mut_ptr().cast::<u8>(), N) },
        )
    }
}

impl Write for RawWriter<'_> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let bytes = s.as_bytes();
        let len = bytes.len();

        // We do not want to overwrite our null terminator
        if self.pos + len > self.buffer.len() - 1 {
            return Err(fmt::Error);
        }

        // INVARIANT: We are not overwriting the last byte
        self.buffer[self.pos..self.pos + len].copy_from_slice(bytes);

        self.pos += len;

        Ok(())
    }
}