use crate::error::{Error, Result};
pub(crate) fn push_u32(bytes: &mut Vec<u8>, value: u32) {
bytes.extend_from_slice(&value.to_le_bytes());
}
pub(crate) fn push_string(bytes: &mut Vec<u8>, value: &str) {
push_u32(bytes, value.len() as u32);
bytes.extend_from_slice(value.as_bytes());
}
pub(crate) fn push_strings(bytes: &mut Vec<u8>, values: &[String]) {
push_u32(bytes, values.len() as u32);
for value in values {
push_string(bytes, value);
}
}
pub(crate) struct Reader<'a> {
bytes: &'a [u8],
position: usize,
what: &'static str,
error: fn(String) -> Error,
}
impl<'a> Reader<'a> {
pub(crate) fn new(bytes: &'a [u8], what: &'static str, error: fn(String) -> Error) -> Self {
Self {
bytes,
position: 0,
what,
error,
}
}
pub(crate) fn error(&self, problem: impl std::fmt::Display) -> Error {
(self.error)(format!("the {} {problem}", self.what))
}
pub(crate) fn position(&self) -> usize {
self.position
}
pub(crate) fn remaining(&self) -> usize {
self.bytes.len() - self.position
}
pub(crate) fn take(&mut self, length: usize) -> Result<&'a [u8]> {
let end = self
.position
.checked_add(length)
.filter(|end| *end <= self.bytes.len())
.ok_or_else(|| {
self.error(format_args!(
"ends early: {length} bytes expected at {}, {} left",
self.position,
self.remaining()
))
})?;
let taken = &self.bytes[self.position..end];
self.position = end;
Ok(taken)
}
fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
let mut array = [0; N];
array.copy_from_slice(self.take(N)?);
Ok(array)
}
pub(crate) fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?[0])
}
pub(crate) fn u32(&mut self) -> Result<u32> {
Ok(u32::from_le_bytes(self.array()?))
}
pub(crate) fn u64(&mut self) -> Result<u64> {
Ok(u64::from_le_bytes(self.array()?))
}
pub(crate) fn f64(&mut self) -> Result<f64> {
Ok(f64::from_le_bytes(self.array()?))
}
pub(crate) fn string(&mut self) -> Result<String> {
let length = self.u32()? as usize;
let bytes = self.take(length)?;
String::from_utf8(bytes.to_vec()).map_err(|_| self.error("has a string that is not UTF-8"))
}
pub(crate) fn strings(&mut self) -> Result<Vec<String>> {
let count = self.u32()?;
let mut values = Vec::new();
for _ in 0..count {
values.push(self.string()?);
}
Ok(values)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn reader(bytes: &[u8]) -> Reader<'_> {
Reader::new(bytes, "test bytes", Error::Chunker)
}
#[test]
fn numbers_and_strings_come_back_as_they_were_written() {
let mut bytes = Vec::new();
push_u32(&mut bytes, 0x0102_0304);
push_string(&mut bytes, "文節");
push_strings(&mut bytes, &["a".to_string(), String::new()]);
assert_eq!(bytes[..4], [4, 3, 2, 1]);
assert_eq!(bytes[4..8], [6, 0, 0, 0]);
let mut reader = reader(&bytes);
assert_eq!(reader.u32().unwrap(), 0x0102_0304);
assert_eq!(reader.string().unwrap(), "文節");
assert_eq!(reader.strings().unwrap(), ["a", ""]);
assert_eq!(reader.remaining(), 0);
}
#[test]
fn bytes_that_end_early_or_are_not_utf8_are_errors() {
let message = reader(&[1, 2, 3]).u32().unwrap_err().to_string();
assert!(
message.contains("the test bytes ends early: 4 bytes expected at 0, 3 left"),
"{message}"
);
let message = reader(&[2, 0, 0, 0, 0xff, 0xfe])
.string()
.unwrap_err()
.to_string();
assert!(message.contains("not UTF-8"), "{message}");
let mut bytes = Vec::new();
push_u32(&mut bytes, u32::MAX);
assert!(reader(&bytes).strings().is_err());
}
}