Merge "Implements some std::io functions in kata_io"

GitOrigin-RevId: b5b1afb7b0528acd100fd35a84a48b984f1b02c1
This commit is contained in:
Matt Harvey 2021-09-16 18:42:08 +00:00 committed by Sam Leffler
parent 6b25d6fea0
commit 4904a61ca0
2 changed files with 48 additions and 13 deletions

View File

@ -4,14 +4,43 @@ pub struct Error;
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T> = core::result::Result<T, Error>;
/// Interface for the CLI to consume bytes. /// Partial mimic of std::io::Read.
pub trait Read { pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> Result<usize>; fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
while !buf.is_empty() {
match self.read(buf) {
Ok(0) => break,
Ok(n) => {
let tmp = buf;
buf = &mut tmp[n..];
}
Err(e) => return Err(e),
}
}
if !buf.is_empty() {
Err(Error)
} else {
Ok(())
}
}
} }
/// Interface for the CLI to emit bytes. /// Partial mimic of std::io::Write.
pub trait Write { pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize>; fn write(&mut self, buf: &[u8]) -> Result<usize>;
fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
while !buf.is_empty() {
match self.write(buf) {
Ok(0) => return Err(Error),
Ok(n) => buf = &buf[n..],
Err(e) => return Err(e),
}
}
Ok(())
}
} }
/// Adapter for writing core::fmt formatted strings. /// Adapter for writing core::fmt formatted strings.
@ -25,13 +54,13 @@ impl core::fmt::Write for dyn Write + '_ {
} }
} }
impl dyn Read + '_ { pub enum SeekFrom {
pub fn get_u8(&mut self) -> Result<u8> { Start(u64),
let mut buf: [u8; 1] = [0u8]; End(i64),
let n_read = self.read(&mut buf)?; Current(i64),
match n_read {
1usize => Ok(buf[0]),
_ => Err(Error),
}
} }
/// Partial mimic of std::io::Seek.
pub trait Seek {
fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
} }

View File

@ -39,6 +39,12 @@ pub struct LineReader {
buf: [u8; LINE_MAX], buf: [u8; LINE_MAX],
} }
fn get_u8(reader: &mut dyn io::Read) -> io::Result<u8> {
let mut buf: [u8; 1] = [0u8];
reader.read_exact(&mut buf)?;
Ok(buf[0])
}
impl LineReader { impl LineReader {
pub fn new() -> LineReader { pub fn new() -> LineReader {
LineReader { LineReader {
@ -55,13 +61,13 @@ impl LineReader {
const BACKSPACE: u8 = 8u8; const BACKSPACE: u8 = 8u8;
let mut len = 0; let mut len = 0;
while len < self.buf.len() { while len < self.buf.len() {
let mut c = input.get_u8()?; let mut c = get_u8(input)?;
while c == DEL || c == BACKSPACE { while c == DEL || c == BACKSPACE {
if len > 0 { if len > 0 {
output.write(&[BACKSPACE, b' ', BACKSPACE])?; output.write(&[BACKSPACE, b' ', BACKSPACE])?;
len -= 1; len -= 1;
} }
c = input.get_u8()?; c = get_u8(input)?;
} }
if c == b'\r' || c == b'\n' { if c == b'\r' || c == b'\n' {
if len > 0 { if len > 0 {