changelog shortlog graph tags branches changeset files revisions annotate raw help

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

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