Rename the CLI crate and executable to cli

This commit is contained in:
2026-12-03 04:30:27 +08:00
parent 763b46f43e
commit c0b8a0f229
7 changed files with 16 additions and 16 deletions
+41
View File
@@ -0,0 +1,41 @@
use anyhow::Result;
use exchange::Exchange;
use serde_json::{json, Value};
use std::io::{BufRead, Write};
pub(crate) fn serve(
engine: &mut Exchange,
input: impl BufRead,
mut output: impl Write,
) -> Result<()> {
for line in input.lines() {
let line = line?;
let result = serde_json::from_str::<Value>(&line)
.map_err(anyhow::Error::from)
.and_then(|v| engine.execute(v));
let reply = result.unwrap_or_else(|e| json!({"error":e.to_string()}));
serde_json::to_writer(&mut output, &reply)?;
writeln!(output)?;
output.flush()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_line_does_not_discard_next_request() {
let mut e = Exchange::open(":memory:").unwrap();
let mut out = Vec::new();
serve(&mut e, &b"broken\n{\"op\":\"state\"}\n"[..], &mut out).unwrap();
let replies: Vec<Value> = std::str::from_utf8(&out)
.unwrap()
.lines()
.map(|line| serde_json::from_str(line).unwrap())
.collect();
assert_eq!(replies.len(), 2);
assert!(replies[0]["error"].is_string());
assert_eq!(replies[1]["orders"], json!([]));
}
}