This commit is contained in:
2025-08-16 10:28:28 +02:00
parent 246304b9fa
commit 5eab3b080c
3 changed files with 54 additions and 33 deletions

View File

@@ -8,6 +8,7 @@ pub enum Protocol {
BulkString(String),
Null,
Array(Vec<Protocol>),
Error(String), // NEW
}
impl fmt::Display for Protocol {
@@ -45,7 +46,7 @@ impl Protocol {
#[inline]
pub fn err(msg: &str) -> Self {
Protocol::SimpleString(msg.to_string())
Protocol::Error(msg.to_string())
}
#[inline]
@@ -69,22 +70,19 @@ impl Protocol {
Protocol::BulkString(s) => s.to_string(),
Protocol::Null => "".to_string(),
Protocol::Array(s) => s.iter().map(|x| x.decode()).collect::<Vec<_>>().join(" "),
Protocol::Error(s) => s.to_string(),
}
}
pub fn encode(&self) -> String {
match self {
Protocol::SimpleString(s) => format!("+{}\r\n", s),
Protocol::BulkString(s) => format!("${}\r\n{}\r\n", s.len(), s),
Protocol::Array(ss) => {
format!("*{}\r\n", ss.len())
+ ss.iter()
.map(|x| x.encode())
.collect::<Vec<_>>()
.join("")
.as_str()
Protocol::BulkString(s) => format!("${}\r\n{}\r\n", s.len(), s),
Protocol::Array(ss) => {
format!("*{}\r\n", ss.len()) + &ss.iter().map(|x| x.encode()).collect::<String>()
}
Protocol::Null => "$-1\r\n".to_string(),
Protocol::Null => "$-1\r\n".to_string(),
Protocol::Error(s) => format!("-{}\r\n", s), // proper RESP error
}
}