kernel/utilities/binary_write.rs
1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Basic binary write interface and supporting structs.
6//!
7//! This simple trait provides a synchronous interface for printing an arbitrary
8//! binary slice. This mirrors the `core::fmt::Write` interface but doesn't
9//! expect a `&str`.
10
11/// Interface for writing an arbitrary buffer.
12pub trait BinaryWrite {
13 /// Write the `buffer` to some underlying print mechanism.
14 ///
15 /// Returns `Ok(usize)` on success with the number of bytes from `buffer`
16 /// that were written. Returns `Err(())` on any error.
17 fn write_buffer(&mut self, buffer: &[u8]) -> Result<usize, ()>;
18}
19
20/// Provide a `BinaryWrite` interface on top of a synchronous `core::fmt::Write`
21/// interface.
22///
23/// Note, this MUST only be used to reverse the output of
24/// `WriteToBinaryOffsetWrapper`. That is, this assume that the binary strings
25/// are valid UTF-8, which will be the case if the binary buffer comes from some
26/// `core::fmt::Write` operation originally.
27pub(crate) struct BinaryToWriteWrapper<'a> {
28 writer: &'a mut dyn core::fmt::Write,
29}
30
31impl<'a> BinaryToWriteWrapper<'a> {
32 pub(crate) fn new(writer: &'a mut dyn core::fmt::Write) -> Self {
33 Self { writer }
34 }
35}
36
37impl BinaryWrite for BinaryToWriteWrapper<'_> {
38 fn write_buffer(&mut self, buffer: &[u8]) -> Result<usize, ()> {
39 // Convert the binary string to UTF-8 so we can print it as a string. If
40 // this is not actually a UTF-8 string, then return Err(()).
41 let s = core::str::from_utf8(buffer).or(Err(()))?;
42 let _ = self.writer.write_str(s);
43 Ok(buffer.len())
44 }
45}