kernel/utilities/
io_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//! Re-implementation of `std:io` traits not available in `no_std`.
6
7use crate::collections::ring_buffer::RingBuffer;
8
9/// Implementation of `std::io::Write` for `no_std`.
10///
11/// This takes bytes instead of a string (contrary to [`core::fmt::Write`]), but
12/// we cannot use `std::io::Write' as it isn't available in `no_std` (due to
13/// `std::io::Error` not being available).
14///
15/// Also, in our use cases, writes are infallible, so the write function cannot
16/// return an `Err`, however it might not be able to write everything, so it
17/// returns the number of bytes written.
18///
19/// See also the tracking issue:
20/// <https://github.com/rust-lang/rfcs/issues/2262>.
21pub trait IoWrite {
22    fn write(&mut self, buf: &[u8]) -> usize;
23
24    fn write_ring_buffer(&mut self, buf: &RingBuffer<'_, u8>) -> usize {
25        let (left, right) = buf.as_slices();
26        let mut total = 0;
27        if let Some(slice) = left {
28            total += self.write(slice);
29        }
30        if let Some(slice) = right {
31            total += self.write(slice);
32        }
33        total
34    }
35}