Skip to main content

turnloop_redis/
resp.rs

1//! Bounded RESP2/RESP3 codec. An allocation-free validation pass precedes result
2//! materialization, so fragmented input never creates temporary result trees.
3use std::io::Write;
4
5#[derive(Debug, Clone, PartialEq)]
6pub enum Value {
7    Simple(Vec<u8>),
8    Error(Vec<u8>),
9    Bulk(Vec<u8>),
10    Integer(i64),
11    Double(f64),
12    Boolean(bool),
13    Null,
14    Array(Vec<Value>),
15    Map(Vec<(Value, Value)>),
16    Set(Vec<Value>),
17    Push(Vec<Value>),
18    Verbatim(Vec<u8>),
19    BigNumber(Vec<u8>),
20    Attribute(Vec<(Value, Value)>, Box<Value>),
21}
22impl Value {
23    pub fn bytes(&self) -> Option<&[u8]> {
24        match self {
25            Self::Simple(v)
26            | Self::Error(v)
27            | Self::Bulk(v)
28            | Self::Verbatim(v)
29            | Self::BigNumber(v) => Some(v),
30            _ => None,
31        }
32    }
33    pub fn items(&self) -> Option<&[Value]> {
34        match self {
35            Self::Array(v) | Self::Set(v) | Self::Push(v) => Some(v),
36            _ => None,
37        }
38    }
39    pub fn integer(&self) -> Option<i64> {
40        if let Self::Integer(v) = self {
41            Some(*v)
42        } else {
43            None
44        }
45    }
46    /// UTF-8 replacement semantics for ioredis string replies. Buffer variants
47    /// should use `bytes` directly, preserving arbitrary binary content.
48    pub fn text(&self) -> Option<std::borrow::Cow<'_, str>> {
49        self.bytes().map(String::from_utf8_lossy)
50    }
51}
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum DecodeError {
54    Incomplete,
55    Invalid,
56    Limit,
57    StreamingUnsupported,
58}
59impl std::fmt::Display for DecodeError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        write!(f, "RESP {self:?}")
62    }
63}
64impl std::error::Error for DecodeError {}
65#[derive(Debug, Clone, Copy)]
66pub struct Limits {
67    pub bytes: usize,
68    pub items: usize,
69    pub depth: usize,
70}
71impl Default for Limits {
72    fn default() -> Self {
73        Self {
74            bytes: 16 * 1024 * 1024,
75            items: 1_000_000,
76            depth: 64,
77        }
78    }
79}
80fn line<'a>(input: &'a [u8], p: &mut usize) -> Result<&'a [u8], DecodeError> {
81    let tail = input.get(*p..).ok_or(DecodeError::Incomplete)?;
82    let end = tail
83        .iter()
84        .position(|b| *b == b'\n')
85        .ok_or(DecodeError::Incomplete)?;
86    if end == 0 || tail[end - 1] != b'\r' {
87        return Err(DecodeError::Invalid);
88    }
89    let result = &tail[..end - 1];
90    *p += end + 1;
91    Ok(result)
92}
93fn number(v: &[u8]) -> Result<i64, DecodeError> {
94    if v.is_empty()
95        || v[0] == b'+'
96        || v.iter()
97            .enumerate()
98            .any(|(i, b)| !b.is_ascii_digit() && !(i == 0 && *b == b'-'))
99    {
100        return Err(DecodeError::Invalid);
101    }
102    std::str::from_utf8(v)
103        .map_err(|_| DecodeError::Invalid)?
104        .parse()
105        .map_err(|_| DecodeError::Invalid)
106}
107fn node(
108    input: &[u8],
109    p: &mut usize,
110    depth: usize,
111    budget: &mut usize,
112    limits: Limits,
113    build: bool,
114) -> Result<Value, DecodeError> {
115    if depth > limits.depth || *budget == 0 {
116        return Err(DecodeError::Limit);
117    }
118    *budget -= 1;
119    let kind = *input.get(*p).ok_or(DecodeError::Incomplete)?;
120    *p += 1;
121    let head = line(input, p)?;
122    let copy = || if build { head.to_vec() } else { Vec::new() };
123    Ok(match kind {
124        b'+' => Value::Simple(copy()),
125        b'-' => Value::Error(copy()),
126        b':' => Value::Integer(number(head)?),
127        b',' => Value::Double(match head {
128            b"inf" | b"+inf" => f64::INFINITY,
129            b"-inf" => f64::NEG_INFINITY,
130            b"nan" => f64::NAN,
131            _ => std::str::from_utf8(head)
132                .map_err(|_| DecodeError::Invalid)?
133                .parse()
134                .map_err(|_| DecodeError::Invalid)?,
135        }),
136        b'(' => {
137            let digits = head
138                .strip_prefix(b"-")
139                .or_else(|| head.strip_prefix(b"+"))
140                .unwrap_or(head);
141            if digits.is_empty() || !digits.iter().all(u8::is_ascii_digit) {
142                return Err(DecodeError::Invalid);
143            }
144            Value::BigNumber(copy())
145        }
146        b'#' => match head {
147            b"t" => Value::Boolean(true),
148            b"f" => Value::Boolean(false),
149            _ => return Err(DecodeError::Invalid),
150        },
151        b'_' if head.is_empty() => Value::Null,
152        b'$' | b'!' | b'=' => {
153            if head == b"?" {
154                return Err(DecodeError::StreamingUnsupported);
155            }
156            let len = number(head)?;
157            if len == -1 && kind == b'$' {
158                return Ok(Value::Null);
159            }
160            let len = usize::try_from(len).map_err(|_| DecodeError::Invalid)?;
161            if len > limits.bytes {
162                return Err(DecodeError::Limit);
163            }
164            let end = p.checked_add(len).ok_or(DecodeError::Limit)?;
165            let end_crlf = end.checked_add(2).ok_or(DecodeError::Limit)?;
166            let bytes = input.get(*p..end).ok_or(DecodeError::Incomplete)?;
167            if input.get(end..end_crlf).ok_or(DecodeError::Incomplete)? != b"\r\n" {
168                return Err(DecodeError::Invalid);
169            }
170            if kind == b'=' && (len < 4 || bytes[3] != b':') {
171                return Err(DecodeError::Invalid);
172            }
173            *p = end_crlf;
174            let value = if build { bytes.to_vec() } else { Vec::new() };
175            match kind {
176                b'$' => Value::Bulk(value),
177                b'!' => Value::Error(value),
178                _ => Value::Verbatim(value),
179            }
180        }
181        b'*' | b'~' | b'>' | b'%' | b'|' => {
182            if head == b"?" {
183                return Err(DecodeError::StreamingUnsupported);
184            }
185            let count = number(head)?;
186            if count == -1 && kind == b'*' {
187                return Ok(Value::Null);
188            }
189            let count = usize::try_from(count).map_err(|_| DecodeError::Invalid)?;
190            let pairs = kind == b'%' || kind == b'|';
191            let total = count
192                .checked_mul(if pairs { 2 } else { 1 })
193                .ok_or(DecodeError::Limit)?;
194            if total > *budget {
195                return Err(DecodeError::Limit);
196            }
197            let mut values = if build && !pairs {
198                Vec::with_capacity(count)
199            } else {
200                Vec::new()
201            };
202            let mut entries = if build && pairs {
203                Vec::with_capacity(count)
204            } else {
205                Vec::new()
206            };
207            for _ in 0..count {
208                let a = node(input, p, depth + 1, budget, limits, build)?;
209                if pairs {
210                    let b = node(input, p, depth + 1, budget, limits, build)?;
211                    if build {
212                        entries.push((a, b));
213                    }
214                } else if build {
215                    values.push(a);
216                }
217            }
218            match kind {
219                b'*' => Value::Array(values),
220                b'~' => Value::Set(values),
221                b'>' => Value::Push(values),
222                b'%' => Value::Map(entries),
223                _ => {
224                    let value = node(input, p, depth + 1, budget, limits, build)?;
225                    if build {
226                        Value::Attribute(entries, Box::new(value))
227                    } else {
228                        Value::Null
229                    }
230                }
231            }
232        }
233        _ => return Err(DecodeError::Invalid),
234    })
235}
236/// Validate and locate a complete frame without allocating its result.
237pub fn frame_len(input: &[u8], limits: Limits) -> Result<Option<usize>, DecodeError> {
238    let mut end = 0;
239    match node(input, &mut end, 0, &mut { limits.items }, limits, false) {
240        Err(DecodeError::Incomplete) if input.len() <= limits.bytes => return Ok(None),
241        Err(DecodeError::Incomplete) => return Err(DecodeError::Limit),
242        Err(e) => return Err(e),
243        Ok(_) => {}
244    }
245    if end > limits.bytes {
246        return Err(DecodeError::Limit);
247    }
248    Ok(Some(end))
249}
250pub fn decode(input: &[u8], limits: Limits) -> Result<Option<(Value, usize)>, DecodeError> {
251    let Some(end) = frame_len(input, limits)? else {
252        return Ok(None);
253    };
254    let mut pos = 0;
255    let value = node(input, &mut pos, 0, &mut { limits.items }, limits, true)?;
256    Ok(Some((value, end)))
257}
258/// Append directly to reusable transport/replay storage; no temporary strings.
259pub fn encode_command(args: &[&[u8]], output: &mut Vec<u8>) {
260    write!(output, "*{}\r\n", args.len()).expect("Vec writes cannot fail");
261    for arg in args {
262        write!(output, "${}\r\n", arg.len()).expect("Vec writes cannot fail");
263        output.extend_from_slice(arg);
264        output.extend_from_slice(b"\r\n");
265    }
266}
267
268/// Borrowed pub/sub message fields; used before general materialization so
269/// routing messages allocates only their returned channel/pattern/payload.
270pub struct MessageRef<'a> {
271    pub pattern: Option<&'a [u8]>,
272    pub channel: &'a [u8],
273    pub payload: &'a [u8],
274}
275pub fn message(
276    input: &[u8],
277    limits: Limits,
278) -> Result<Option<(MessageRef<'_>, usize)>, DecodeError> {
279    if !matches!(input.first(), Some(b'>' | b'*')) {
280        return Ok(None);
281    }
282    let Some(end) = frame_len(input, limits)? else {
283        return Ok(None);
284    };
285    let mut pos = 1;
286    let count = number(line(input, &mut pos)?)?;
287    if count != 3 && count != 4 {
288        return Ok(None);
289    }
290    fn bytes<'a>(input: &'a [u8], pos: &mut usize) -> Option<&'a [u8]> {
291        let kind = *input.get(*pos)?;
292        *pos += 1;
293        let head = line(input, pos).ok()?;
294        match kind {
295            b'+' => Some(head),
296            b'$' => {
297                let len = usize::try_from(number(head).ok()?).ok()?;
298                let data = input.get(*pos..pos.checked_add(len)?)?;
299                *pos += len + 2;
300                Some(data)
301            }
302            _ => None,
303        }
304    }
305    let tag = bytes(input, &mut pos);
306    let pattern = match (count, tag) {
307        (3, Some(b"message")) => None,
308        (4, Some(b"pmessage")) => Some(bytes(input, &mut pos).ok_or(DecodeError::Invalid)?),
309        _ => return Ok(None),
310    };
311    let channel = bytes(input, &mut pos).ok_or(DecodeError::Invalid)?;
312    let payload = bytes(input, &mut pos).ok_or(DecodeError::Invalid)?;
313    Ok(Some((
314        MessageRef {
315            pattern,
316            channel,
317            payload,
318        },
319        end,
320    )))
321}