1 | use crate::lib::fmt::{self, Write}; |
2 | use crate::lib::str; |
3 | |
4 | pub(super) struct Buf<'a> { |
5 | bytes: &'a mut [u8], |
6 | offset: usize, |
7 | } |
8 | |
9 | impl<'a> Buf<'a> { |
10 | pub fn new(bytes: &'a mut [u8]) -> Self { |
11 | Buf { bytes, offset: 0 } |
12 | } |
13 | |
14 | pub fn as_str(&self) -> &str { |
15 | let slice = &self.bytes[..self.offset]; |
16 | unsafe { str::from_utf8_unchecked(slice) } |
17 | } |
18 | } |
19 | |
20 | impl<'a> Write for Buf<'a> { |
21 | fn write_str(&mut self, s: &str) -> fmt::Result { |
22 | if self.offset + s.len() > self.bytes.len() { |
23 | Err(fmt::Error) |
24 | } else { |
25 | self.bytes[self.offset..self.offset + s.len()].copy_from_slice(s.as_bytes()); |
26 | self.offset += s.len(); |
27 | Ok(()) |
28 | } |
29 | } |
30 | } |
31 | |