use crate::{Error, ParseError, Value, tagged};
#[derive(Debug, Clone, PartialEq)]
pub struct Instructions {
pub(crate) list: Vec<Value>,
}
impl Instructions {
pub fn from_json(text: &str) -> Result<Instructions, Error> {
match &mut tagged::decode(text)? {
Value::List(list) => Ok(Instructions {
list: core::mem::take(list),
}),
_ => Err(ParseError::new(
"not_an_instruction_list",
"an instruction list is a JSON array",
)
.into()),
}
}
pub fn to_json(&self) -> Result<String, Error> {
tagged::encode(&Value::List(self.list.clone()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_list_is_an_instruction_list() {
let read = Instructions::from_json(r#"[["load","x"],5,[]]"#).unwrap();
assert_eq!(read.list.len(), 3);
for text in [r#"{"a":1}"#, "5", "null", r#""x""#] {
let refused = Instructions::from_json(text)
.err()
.map(|error| (error.type_name().to_owned(), error.reason().to_owned()));
assert_eq!(
refused,
Some((
"ParseError".to_owned(),
"not_an_instruction_list".to_owned()
)),
"{text}"
);
}
assert_eq!(
Instructions::from_json("[").unwrap_err().reason(),
"malformed_json"
);
}
#[test]
fn to_json_writes_what_from_json_reads() {
let text = r#"[["lit",{"$type":"undefined"}],["lit",[{"$type":"date","value":"2026-01-02"},{"$type":"datetime","value":"2026-01-02T03:04:05.500000Z"},1.5]],["lit",{"$type":"duration","value":{"days":3,"hours":0,"minutes":0,"months":0,"seconds":0,"weeks":0,"years":0}}],["call","f",2]]"#;
let read = Instructions::from_json(text).unwrap();
assert_eq!(read.to_json().unwrap(), text);
assert_eq!(
Instructions::from_json("[]").unwrap().to_json().unwrap(),
"[]"
);
}
}