1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use crate::RespType;
use bytes::{Buf, BufMut, Bytes, BytesMut};

pub const EMPTY_ARRAY: Array = Array(Bytes::from_static(b"*0\r\n"));
pub const NULL_ARRAY: Array = Array(Bytes::from_static(b"*-1\r\n"));

#[derive(Debug, PartialEq)]
pub struct Array(Bytes);

impl Array {
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    #[inline]
    pub fn bytes(&self) -> Bytes {
        self.0.clone()
    }

    #[inline]
    pub fn to_vec(&self) -> Vec<u8> {
        let length = self.0.len();
        let mut vector = Vec::<u8>::with_capacity(length);
        unsafe {
            vector.set_len(length - 3);
        }
        self.bytes().copy_to_slice(vector.as_mut_slice());
        vector
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self == EMPTY_ARRAY
    }

    #[inline]
    pub fn is_null(&self) -> bool {
        self == NULL_ARRAY
    }
}

impl<'a> PartialEq<Array> for &'a Array {
    fn eq(&self, other: &Array) -> bool {
        self.0 == other.bytes()
    }
    fn ne(&self, other: &Array) -> bool {
        self.0 != other.bytes()
    }
}

pub struct ArrayBuilder {
    inner: Vec<RespType>,
}

impl ArrayBuilder {
    #[inline]
    pub fn new() -> ArrayBuilder {
        ArrayBuilder {
            inner: Vec::<RespType>::new(),
        }
    }

    #[inline]
    pub fn add(&mut self, value: RespType) -> &Self {
        self.inner.push(value);
        self
    }

    #[inline]
    pub fn build(&self) -> Array {
        let length = self.inner.len();
        if length == 0 {
            EMPTY_ARRAY
        } else {
            let length_string = length.to_string();
            let mut total_bytes = length_string.len() + 3;
            for element in &self.inner {
                total_bytes += element.len();
            }
            let mut bytes = BytesMut::with_capacity(total_bytes);
            bytes.put_u8(0x2a); // "*"
            bytes.put_slice(length_string.as_bytes());
            bytes.put_u8(0x0d); // CR
            bytes.put_u8(0x0a); // LF
            for element in &self.inner {
                bytes.put(element.bytes());
            }
            Array(bytes.freeze())
        }
    }
}

#[cfg(test)]
mod tests_array {
    use crate::{ArrayBuilder, BulkString, Error, Integer, RespType, SimpleString, EMPTY_ARRAY};
    use bytes::Bytes;

    #[test]
    fn build_empty_array() {
        let array_builder = ArrayBuilder::new();
        assert_eq!(array_builder.build(), EMPTY_ARRAY)
    }

    #[test]
    fn build_array_with_error() {
        let mut array_builder = ArrayBuilder::new();
        array_builder.add(RespType::Error(Error::new(b"Invalid value.")));
        let array = array_builder.build();
        assert_eq!(
            array.bytes(),
            Bytes::from_static(b"*1\r\n-Invalid value.\r\n")
        )
    }

    #[test]
    fn build_array() {
        let mut array_builder = ArrayBuilder::new();
        array_builder.add(RespType::SimpleString(SimpleString::new(b"foo")));
        assert_eq!(
            array_builder.build().bytes(),
            Bytes::from_static(b"*1\r\n+foo\r\n")
        );
        array_builder.add(RespType::BulkString(BulkString::new(b"bar")));
        assert_eq!(
            array_builder.build().bytes(),
            Bytes::from_static(b"*2\r\n+foo\r\n$3\r\nbar\r\n")
        );
        array_builder.add(RespType::Integer(Integer::new(-100)));
        assert_eq!(
            array_builder.build().bytes(),
            Bytes::from_static(b"*3\r\n+foo\r\n$3\r\nbar\r\n:-100\r\n")
        );
        let mut subarray_builder = ArrayBuilder::new();
        subarray_builder.add(RespType::SimpleString(SimpleString::new(b"foo")));
        subarray_builder.add(RespType::SimpleString(SimpleString::new(b"bar")));
        let subarray = subarray_builder.build();
        assert_eq!(
            subarray.bytes(),
            Bytes::from_static(b"*2\r\n+foo\r\n+bar\r\n")
        );
        array_builder.add(RespType::Array(subarray));
        assert_eq!(
            array_builder.build().bytes(),
            Bytes::from_static(b"*4\r\n+foo\r\n$3\r\nbar\r\n:-100\r\n*2\r\n+foo\r\n+bar\r\n")
        );
    }
}