wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! RESP encoding functions.

use std::io;

use bytes::{BufMut, BytesMut};

use super::frame::RespFrame;

/// Maximum recursion depth for nested RESP arrays.
///
/// This limit prevents stack overflow when encoding programmatically
/// constructed deeply nested arrays.
const MAX_RECURSION_DEPTH: usize = 64;

/// Compute the encoded length of a RESP frame.
pub fn encoded_len(frame: &RespFrame) -> Result<usize, io::Error> { encoded_len_at(frame, 0) }

/// Measure a frame recursively while enforcing the nesting safety limit.
/// Checked arithmetic turns a size overflow into an input error before the
/// encoder reserves or writes any destination capacity.
fn encoded_len_at(frame: &RespFrame, depth: usize) -> Result<usize, io::Error> {
    check_depth(depth)?;
    match frame {
        RespFrame::SimpleString(text) | RespFrame::Error(text) => encoded_line_len(text.len()),
        RespFrame::Integer(value) => encoded_line_len(digits_len_i64(*value)),
        RespFrame::BulkString(None) | RespFrame::Array(None) => Ok(5), // $-1 or *-1
        RespFrame::BulkString(Some(data)) => encoded_bulk_len(data.len()),
        RespFrame::Array(Some(items)) => encoded_array_len(items, depth),
    }
}

/// Reject nesting beyond the safety limit.
fn check_depth(depth: usize) -> Result<(), io::Error> {
    if depth > MAX_RECURSION_DEPTH {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "maximum recursion depth exceeded",
        ));
    }
    Ok(())
}

/// Length of a prefix byte, `body_len` bytes and the closing CRLF.
fn encoded_line_len(body_len: usize) -> Result<usize, io::Error> {
    checked_add(1, checked_add(body_len, 2)?)
}

/// Length of a non-null bulk string: `$<digits>\r\n<data>\r\n`.
fn encoded_bulk_len(data_len: usize) -> Result<usize, io::Error> {
    let len_digits = digits_len_usize(data_len);
    let head = checked_add(1, checked_add(len_digits, 2)?)?;
    let body = checked_add(data_len, 2)?;
    checked_add(head, body)
}

/// Length of a non-null array: its header plus every nested frame.
fn encoded_array_len(items: &[RespFrame], depth: usize) -> Result<usize, io::Error> {
    let count_digits = digits_len_usize(items.len());
    let mut total = checked_add(1, checked_add(count_digits, 2)?)?;
    for item in items {
        total = checked_add(total, encoded_len_at(item, depth + 1)?)?;
    }
    Ok(total)
}

/// Encode a RESP frame into the destination buffer.
pub fn encode_frame(frame: &RespFrame, dst: &mut BytesMut) -> Result<(), io::Error> {
    encode_frame_at(frame, dst, 0)
}

/// Append one frame and its nested children using RESP wire ordering.
/// The depth guard matches [`encoded_len_at`] so length validation and actual
/// emission reject the same recursively constructed input.
fn encode_frame_at(frame: &RespFrame, dst: &mut BytesMut, depth: usize) -> Result<(), io::Error> {
    if depth > MAX_RECURSION_DEPTH {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "maximum recursion depth exceeded",
        ));
    }
    match frame {
        RespFrame::SimpleString(text) => {
            dst.put_u8(b'+');
            dst.extend_from_slice(text.as_bytes());
            dst.extend_from_slice(b"\r\n");
        }
        RespFrame::Error(text) => {
            dst.put_u8(b'-');
            dst.extend_from_slice(text.as_bytes());
            dst.extend_from_slice(b"\r\n");
        }
        RespFrame::Integer(value) => {
            dst.put_u8(b':');
            let mut buf = itoa::Buffer::new();
            dst.extend_from_slice(buf.format(*value).as_bytes());
            dst.extend_from_slice(b"\r\n");
        }
        RespFrame::BulkString(None) => {
            dst.extend_from_slice(b"$-1\r\n");
        }
        RespFrame::BulkString(Some(data)) => {
            dst.put_u8(b'$');
            let mut buf = itoa::Buffer::new();
            dst.extend_from_slice(buf.format(data.len()).as_bytes());
            dst.extend_from_slice(b"\r\n");
            dst.extend_from_slice(data);
            dst.extend_from_slice(b"\r\n");
        }
        RespFrame::Array(None) => {
            dst.extend_from_slice(b"*-1\r\n");
        }
        RespFrame::Array(Some(items)) => {
            dst.put_u8(b'*');
            let mut buf = itoa::Buffer::new();
            dst.extend_from_slice(buf.format(items.len()).as_bytes());
            dst.extend_from_slice(b"\r\n");
            for item in items {
                encode_frame_at(item, dst, depth + 1)?;
            }
        }
    }
    Ok(())
}

/// Count decimal digits without allocating a temporary representation.
const fn digits_len_usize(mut value: usize) -> usize {
    let mut digits = 1;
    while value >= 10 {
        value = value.div_euclid(10);
        digits += 1;
    }
    digits
}

/// Count digits in a signed integer, including its possible minus sign.
const fn digits_len_i64(value: i64) -> usize {
    let mut digits = 1;
    let mut cursor = value.unsigned_abs();
    while cursor >= 10 {
        cursor = cursor.div_euclid(10);
        digits += 1;
    }
    if value < 0 { digits + 1 } else { digits }
}

#[cfg(test)]
mod tests {
    use super::digits_len_i64;

    /// Negative values must count their magnitude, not round toward negative
    /// infinity: `-99` is three characters and `-10` is three.
    #[test]
    fn digits_len_i64_matches_the_rendered_length() {
        for value in [i64::MIN, -100, -99, -10, -9, -1, 0, 1, 9, 10, 99, i64::MAX] {
            assert_eq!(digits_len_i64(value), value.to_string().len(), "{value}");
        }
    }

    /// Exact length and wire bytes for the signed boundaries.
    #[test]
    fn integer_frames_encode_to_their_measured_length() -> Result<(), std::io::Error> {
        use bytes::BytesMut;

        use super::{encode_frame, encoded_len};
        use crate::resp_codec_impl::frame::RespFrame;

        for (value, wire) in [
            (-99_i64, ":-99\r\n".to_owned()),
            (i64::MIN, format!(":{}\r\n", i64::MIN)),
        ] {
            let frame = RespFrame::Integer(value);
            let mut dst = BytesMut::new();
            encode_frame(&frame, &mut dst)?;
            assert_eq!(
                dst.as_ref(),
                wire.as_bytes(),
                "dst.as_ref() should equal wire.as_bytes()"
            );
            assert_eq!(
                encoded_len(&frame)?,
                wire.len(),
                "encoded_len(&frame)? should equal wire.len()"
            );
        }
        Ok(())
    }

    proptest::proptest! {
        /// The measured length equals the emitted bytes for any integer frame.
        #[test]
        fn encoded_len_matches_emitted_bytes(value in proptest::prelude::any::<i64>()) {
            use bytes::BytesMut;

            use super::{encode_frame, encoded_len};
            use crate::resp_codec_impl::frame::RespFrame;

            let frame = RespFrame::Integer(value);
            let mut dst = BytesMut::new();
            proptest::prop_assert!(encode_frame(&frame, &mut dst).is_ok());
            proptest::prop_assert_eq!(encoded_len(&frame).ok(), Some(dst.len()));
        }
    }

    proptest::proptest! {
        /// Any `i64` renders with exactly the length the helper reports.
        #[test]
        fn digits_len_i64_matches_for_any_value(value in proptest::prelude::any::<i64>()) {
            proptest::prop_assert_eq!(digits_len_i64(value), value.to_string().len());
        }
    }
}

/// Add encoded-size components and report overflow as a frame-size error.
fn checked_add(lhs: usize, rhs: usize) -> Result<usize, io::Error> {
    lhs.checked_add(rhs)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "frame too large"))
}