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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use rmpv::Value;
use serde::de::DeserializeOwned;

use crate::{errors::DecodingError, utils::extract_iproto_data, Error};

/// Tuple, returned from `call` and `eval` requests.
#[derive(Clone, Debug, PartialEq)]
pub struct CallResponse(pub(crate) rmpv::Value);

impl CallResponse {
    /// Decode first element of the tuple, dropping everything else.
    ///
    /// This is useful if function doesn't return an error.
    pub fn decode_first<T>(self) -> Result<T, DecodingError>
    where
        T: DeserializeOwned,
    {
        let first = self
            .into_data_tuple()?
            .into_iter()
            .next()
            .ok_or_else(|| DecodingError::invalid_tuple_length(1, 0))?;
        Ok(rmpv::ext::from_value(first)?)
    }

    /// Decode first 2 elements of the tuple, dropping everything else.
    pub fn decode_two<T1, T2>(self) -> Result<(T1, T2), DecodingError>
    where
        T1: DeserializeOwned,
        T2: DeserializeOwned,
    {
        let mut tuple_iter = self.into_data_tuple()?.into_iter();
        if tuple_iter.len() < 2 {
            return Err(DecodingError::invalid_tuple_length(2, tuple_iter.len()));
        }
        // SAFETY: this should be safe since we just checked tuple length
        let first = tuple_iter
            .next()
            .expect("tuple_iter should have length >= 2");
        let second = tuple_iter
            .next()
            .expect("tuple_iter should have length >= 2");
        Ok((
            rmpv::ext::from_value(first)?,
            rmpv::ext::from_value(second)?,
        ))
    }

    /// Decode first two elements of the tuple into result, where
    /// either first element deserialized into `T` and returned as `Ok(T)`
    /// or second element returned as `Err(Error::CallEval)`.
    ///
    /// If second element is `nil` or not present, first element will be returned,
    /// otherwise second element will be returned as error.
    pub fn decode_result<T>(self) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        let mut tuple_iter = self.into_data_tuple()?.into_iter();
        let first = tuple_iter
            .next()
            .ok_or_else(|| DecodingError::invalid_tuple_length(1, 0))?;
        let second = tuple_iter.next();
        match second {
            Some(Value::Nil) | None => {
                Ok(rmpv::ext::from_value(first).map_err(DecodingError::from)?)
            }
            Some(err) => Err(Error::CallEval(err)),
        }
    }

    /// Decode entire response into type.
    ///
    /// Note that currently every response would be a tuple, so be careful what type
    /// you are specifying.
    pub fn decode_full<T>(self) -> Result<T, DecodingError>
    where
        T: DeserializeOwned,
    {
        Ok(rmpv::ext::from_value(extract_iproto_data(self.0)?)?)
    }

    fn into_data_tuple(self) -> Result<Vec<Value>, DecodingError> {
        match extract_iproto_data(self.0)? {
            Value::Array(x) => Ok(x),
            rest => Err(DecodingError::type_mismatch("array", rest.to_string())),
        }
    }
}

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

    use crate::codec::consts::keys::DATA;

    use super::*;

    fn build_tuple_response(data: Vec<Value>) -> Value {
        Value::Map(vec![(DATA.into(), Value::Array(data))])
    }

    #[test]
    fn decode_first() {
        let resp = build_tuple_response(vec![Value::Boolean(true)]);
        assert_matches!(CallResponse(resp).decode_first(), Ok(true));
    }

    #[test]
    fn decode_first_err_len() {
        let resp = build_tuple_response(vec![]);
        assert_matches!(CallResponse(resp).decode_first::<()>(), Err(_));
    }

    #[test]
    fn decode_first_err_wrong_type() {
        let resp = build_tuple_response(vec![Value::Boolean(true)]);
        assert_matches!(CallResponse(resp).decode_first::<String>(), Err(_));
    }

    #[test]
    fn decode_two() {
        let resp = build_tuple_response(vec![Value::Boolean(true), Value::Boolean(false)]);
        assert_matches!(CallResponse(resp).decode_two(), Ok((true, false)));
    }

    #[test]
    fn decode_two_err_len() {
        let resp = build_tuple_response(vec![]);
        assert_matches!(CallResponse(resp).decode_two::<(), ()>(), Err(_));

        let resp = build_tuple_response(vec![Value::Boolean(true)]);
        assert_matches!(CallResponse(resp).decode_two::<(), ()>(), Err(_));
    }

    #[test]
    fn decode_result_ok() {
        let resp = build_tuple_response(vec![Value::Boolean(true)]);
        assert_matches!(CallResponse(resp).decode_result(), Ok(true));

        let resp = build_tuple_response(vec![Value::Boolean(true), Value::Nil]);
        assert_matches!(CallResponse(resp).decode_result(), Ok(true));
    }

    #[test]
    fn decode_result_err_present() {
        let resp = build_tuple_response(vec![Value::Boolean(true), Value::Boolean(false)]);
        assert_matches!(
            CallResponse(resp).decode_result::<bool>(),
            Err(Error::CallEval(Value::Boolean(false)))
        );
    }

    #[test]
    fn decode_result_err_wrong_type() {
        let resp = build_tuple_response(vec![Value::Boolean(true), Value::Nil]);
        assert_matches!(CallResponse(resp).decode_result::<String>(), Err(_));
    }

    #[test]
    fn decode_full() {
        let resp = build_tuple_response(vec![Value::Boolean(true), Value::Boolean(false)]);
        assert_matches!(CallResponse(resp).decode_full(), Ok((true, Some(false))));
    }
}