changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / rust/lib/sxp/src/nostd.rs

changeset 698: 96958d3eb5b0
parent: 0ccbbd142694
author: Richard Westhaver <ellis@rwest.io>
date: Fri, 04 Oct 2024 22:04:59 -0400
permissions: -rw-r--r--
description: fixes
1 //! nostd.rs --- nostd support
2 
3 //! Reimplements core logic and types from `std::io` in an `alloc`-friendly
4 //! fashion.
5 
6 use alloc::vec::Vec;
7 use core::{
8  fmt::{self, Display},
9  result,
10 };
11 
12 pub enum ErrorKind {
13  Other,
14 }
15 
16 // I/O errors can never occur in no-std mode. All our no-std I/O implementations
17 // are infallible.
18 pub struct Error;
19 
20 impl Display for Error {
21  fn fmt(&self, _formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
22  unreachable!()
23  }
24 }
25 
26 impl Error {
27  pub(crate) fn new(_kind: ErrorKind, _error: &'static str) -> Error {
28  Error
29  }
30 }
31 
32 pub type Result<T> = result::Result<T, Error>;
33 
34 pub trait Write {
35  fn write(&mut self, buf: &[u8]) -> Result<usize>;
36 
37  fn write_all(&mut self, buf: &[u8]) -> Result<()> {
38  // All our Write impls in no_std mode always write the whole buffer in
39  // one call infallibly.
40  let result = self.write(buf);
41  debug_assert!(result.is_ok());
42  debug_assert_eq!(result.unwrap_or(0), buf.len());
43  Ok(())
44  }
45 
46  fn flush(&mut self) -> Result<()>;
47 }
48 
49 impl<W: Write> Write for &mut W {
50  #[inline]
51  fn write(&mut self, buf: &[u8]) -> Result<usize> {
52  (*self).write(buf)
53  }
54 
55  #[inline]
56  fn write_all(&mut self, buf: &[u8]) -> Result<()> {
57  (*self).write_all(buf)
58  }
59 
60  #[inline]
61  fn flush(&mut self) -> Result<()> {
62  (*self).flush()
63  }
64 }
65 
66 impl Write for Vec<u8> {
67  #[inline]
68  fn write(&mut self, buf: &[u8]) -> Result<usize> {
69  self.extend_from_slice(buf);
70  Ok(buf.len())
71  }
72 
73  #[inline]
74  fn write_all(&mut self, buf: &[u8]) -> Result<()> {
75  self.extend_from_slice(buf);
76  Ok(())
77  }
78 
79  #[inline]
80  fn flush(&mut self) -> Result<()> {
81  Ok(())
82  }
83 }