Stub out reading registers and memory

This commit is contained in:
2025-01-01 18:15:41 -05:00
parent 9519897711
commit d016538408
5 changed files with 97 additions and 24 deletions
+42 -11
View File
@@ -1,4 +1,5 @@
use anyhow::{bail, Result};
use atoi::FromRadix16;
use tokio::io::{AsyncRead, AsyncReadExt as _};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -6,11 +7,32 @@ pub enum RequestKind {
Signal,
Command,
}
impl RequestKind {
fn name(self) -> &'static str {
match self {
Self::Signal => "Signal",
Self::Command => "Command",
}
}
}
#[derive(Debug)]
pub struct Request<'a> {
pub kind: RequestKind,
body: &'a str,
buffer: &'a [u8],
}
impl std::fmt::Debug for Request<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_tuple(self.kind.name());
match self.kind {
RequestKind::Signal => ds.field(&self.buffer),
RequestKind::Command => match std::str::from_utf8(self.buffer) {
Ok(str) => ds.field(&str),
Err(_) => ds.field(&self.buffer),
},
};
ds.finish()
}
}
impl<'a> Request<'a> {
@@ -31,10 +53,9 @@ impl<'a> Request<'a> {
if char == 0x03 {
// This is how the client "cancels an in-flight request"
buffer.push(char);
let body = std::str::from_utf8(buffer)?;
return Ok(Self {
kind: RequestKind::Signal,
body,
buffer,
});
}
if char != b'$' {
@@ -61,24 +82,34 @@ impl<'a> Request<'a> {
let mut checksum_bytes = [b'0'; 2];
reader.read_exact(&mut checksum_bytes).await?;
let checksum_str = std::str::from_utf8(&checksum_bytes)?;
let real_checksum = u8::from_str_radix(checksum_str, 16)?;
if checksum != real_checksum {
let (real_checksum, 2) = u8::from_radix_16(&checksum_bytes) else {
bail!("invalid checksum");
};
if checksum != real_checksum {
bail!("mismatched checksum");
}
let body = std::str::from_utf8(buffer)?;
Ok(Self {
kind: RequestKind::Command,
body,
buffer,
})
}
pub fn match_str(&mut self, prefix: &str) -> bool {
if let Some(new_body) = self.body.strip_prefix(prefix) {
self.body = new_body;
if let Some(new_buffer) = self.buffer.strip_prefix(prefix.as_bytes()) {
self.buffer = new_buffer;
return true;
}
false
}
pub fn match_hex<I: FromRadix16>(&mut self) -> Option<I> {
match I::from_radix_16(self.buffer) {
(_, 0) => None,
(val, used) => {
self.buffer = self.buffer.split_at(used).1;
Some(val)
}
}
}
}