/ utilities / src / io.rs
io.rs
 1  // Copyright (c) 2019-2025 Alpha-Delta Network Inc.
 2  // This file is part of the alphavm library.
 3  
 4  // Licensed under the Apache License, Version 2.0 (the "License");
 5  // you may not use this file except in compliance with the License.
 6  // You may obtain a copy of the License at:
 7  
 8  // http://www.apache.org/licenses/LICENSE-2.0
 9  
10  // Unless required by applicable law or agreed to in writing, software
11  // distributed under the License is distributed on an "AS IS" BASIS,
12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  // See the License for the specific language governing permissions and
14  // limitations under the License.
15  
16  use std::{cmp, mem};
17  
18  #[derive(Debug)]
19  pub struct Error;
20  
21  pub type Result<T> = core::result::Result<T, Error>;
22  
23  pub trait Read {
24      fn read_exact(&mut self, data: &mut [u8]) -> Result<()>;
25  }
26  
27  pub trait Write {
28      fn write_all(&mut self, data: &[u8]) -> Result<()>;
29  }
30  
31  impl<R: Read + ?Sized> Read for &mut R {
32      #[inline]
33      fn read_exact(&mut self, data: &mut [u8]) -> Result<()> {
34          (**self).read_exact(data)
35      }
36  }
37  
38  impl Read for &[u8] {
39      fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
40          if buf.len() > self.len() {
41              return Err(Error);
42          }
43          let (a, b) = self.split_at(buf.len());
44  
45          // First check if the amount of bytes we want to read is small:
46          // `copy_from_slice` will generally expand to a call to `memcpy`, and
47          // for a single byte the overhead is significant.
48          if buf.len() == 1 {
49              buf[0] = a[0];
50          } else {
51              buf.copy_from_slice(a);
52          }
53  
54          *self = b;
55          Ok(())
56      }
57  }
58  
59  impl<W: Write + ?Sized> Write for &mut W {
60      #[inline]
61      fn write_all(&mut self, data: &[u8]) -> Result<()> {
62          (**self).write_all(data)
63      }
64  }
65  
66  impl Write for &mut [u8] {
67      #[inline]
68      fn write_all(&mut self, data: &[u8]) -> Result<()> {
69          let amt = cmp::min(data.len(), self.len());
70          let (a, b) = mem::replace(self, &mut []).split_at_mut(amt);
71          a.copy_from_slice(&data[..amt]);
72          *self = b;
73  
74          if amt == data.len() { Ok(()) } else { Err(Error) }
75      }
76  }
77  
78  impl Write for Vec<u8> {
79      #[inline]
80      fn write_all(&mut self, buf: &[u8]) -> Result<()> {
81          self.extend_from_slice(buf);
82          Ok(())
83      }
84  }