resp_protocol/
lib.rs

1use bytes::Bytes;
2
3mod array;
4mod bulk_string;
5mod error;
6mod integer;
7mod simple_string;
8
9pub use array::{Array, ArrayBuilder, EMPTY_ARRAY, NULL_ARRAY};
10pub use bulk_string::{BulkString, EMPTY_BULK_STRING, NULL_BULK_STRING};
11pub use error::Error;
12pub use integer::Integer;
13pub use simple_string::SimpleString;
14
15#[derive(Debug, Clone)]
16pub enum RespError {
17    InvalidFirstChar,
18    InvalidLength,
19    InvalidLengthSeparator,
20    InvalidNullValue,
21    InvalidValue,
22    InvalidTerminate,
23    LengthsNotMatch,
24}
25
26impl std::fmt::Display for RespError {
27    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
28        match self {
29            RespError::InvalidFirstChar => {
30                write!(f, "Invalid first char.")
31            }
32            RespError::InvalidLength => {
33                write!(f, "Invalid length.")
34            }
35            RespError::InvalidLengthSeparator => {
36                write!(f, "Invalid length separator.")
37            }
38            RespError::InvalidValue => {
39                write!(f, "Invalid value.")
40            }
41            RespError::InvalidNullValue => {
42                write!(f, "Invalid null value.")
43            }
44            RespError::LengthsNotMatch => {
45                write!(f, "Lengths do not match.")
46            }
47            RespError::InvalidTerminate => {
48                write!(f, "Invalid terminate.")
49            }
50        }
51    }
52}
53
54impl std::error::Error for RespError {}
55
56#[derive(Debug, Clone)]
57pub enum RespType {
58    SimpleString(SimpleString),
59    Error(Error),
60    Integer(Integer),
61    BulkString(BulkString),
62    Array(Array),
63}
64
65impl RespType {
66    fn len(&self) -> usize {
67        match self {
68            RespType::SimpleString(simple_string) => simple_string.len(),
69            RespType::Error(error) => error.len(),
70            RespType::Integer(integer) => integer.len(),
71            RespType::BulkString(bulk_string) => bulk_string.len(),
72            RespType::Array(array) => array.len(),
73        }
74    }
75
76    fn bytes(&self) -> Bytes {
77        match self {
78            RespType::SimpleString(simple_string) => simple_string.bytes(),
79            RespType::Error(error) => error.bytes(),
80            RespType::Integer(integer) => integer.bytes(),
81            RespType::BulkString(bulk_string) => bulk_string.bytes(),
82            RespType::Array(array) => array.bytes(),
83        }
84    }
85}