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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! Complete responses.

pub(crate) mod error;
pub mod frame;

use bytes::BytesMut;
use fxhash::FxHashSet;
use tracing::trace;

use std::iter::FusedIterator;
use std::option;
use std::slice;
use std::sync::Arc;
use std::vec;

pub use error::Error;
pub use frame::Frame;

/// Response to a command, consisting of an abitrary amount of [frames], which are responses to
/// individual commands, and optionally a single [error].
///
/// Since an error terminates a command list, there can only be one error in a response.
///
/// [frames]: frame::Frame
/// [error]: error::Error
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Response {
    /// The sucessful responses.
    frames: Vec<Frame>,
    /// The error, if one occured.
    error: Option<Error>,
}

#[allow(clippy::len_without_is_empty)]
impl Response {
    /// Construct a new response.
    ///
    /// ```
    /// # use mpd_protocol::response::{Response, Frame};
    /// let r = Response::new(vec![Frame::empty()], None);
    /// assert_eq!(1, r.len());
    /// assert!(r.is_success());
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if it is attempted to construct an empty response (i.e. both `frames` and `error`
    /// are empty). This should not occur during normal operation.
    ///
    /// ```should_panic
    /// # use mpd_protocol::response::Response;
    /// // This panics:
    /// Response::new(Vec::new(), None);
    /// ```
    pub fn new(mut frames: Vec<Frame>, error: Option<Error>) -> Self {
        assert!(
            !frames.is_empty() || error.is_some(),
            "attempted to construct an empty (no frames or error) response"
        );

        frames.reverse(); // We want the frames in reverse-chronological order (i.e. oldest last).
        Self { frames, error }
    }

    /// Construct a new "empty" response. This is the simplest possible succesful response,
    /// consisting of a single empty frame.
    ///
    /// ```
    /// # use mpd_protocol::response::Response;
    /// let r = Response::empty();
    /// assert_eq!(1, r.len());
    /// assert!(r.is_success());
    /// ```
    pub fn empty() -> Self {
        Self::new(vec![Frame::empty()], None)
    }

    /// Returns `true` if the response resulted in an error.
    ///
    /// Even if this returns `true`, there may still be succesful frames in the response when the
    /// response is to a command list.
    ///
    /// ```
    /// # use mpd_protocol::response::{Response, Error};
    /// let r = Response::new(Vec::new(), Some(Error::default()));
    /// assert!(r.is_error());
    /// ```
    pub fn is_error(&self) -> bool {
        self.error.is_some()
    }

    /// Returns `true` if the response was entirely succesful (i.e. no errors).
    ///
    /// ```
    /// # use mpd_protocol::response::{Response, Frame};
    /// let r = Response::new(vec![Frame::empty()], None);
    /// assert!(r.is_success());
    /// ```
    pub fn is_success(&self) -> bool {
        !self.is_error()
    }

    /// Get the number of succesful frames in the response.
    ///
    /// May be 0 if the response only consists of an error.
    ///
    /// ```
    /// # use mpd_protocol::response::Response;
    /// let r = Response::empty();
    /// assert_eq!(r.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    /// Create an iterator over references to the frames in the response.
    ///
    /// ```
    /// # use mpd_protocol::response::{Frame, Response};
    /// let r = Response::empty();
    /// let mut iter = r.frames();
    ///
    /// assert_eq!(Some(Ok(&Frame::empty())), iter.next());
    /// ```
    pub fn frames(&self) -> FramesRef<'_> {
        FramesRef {
            frames: self.frames.iter(),
            error: self.error.as_ref().into_iter(),
        }
    }

    /// Treat the response as consisting of a single frame or error.
    ///
    /// Frames or errors beyond the first, if they exist, are silently discarded.
    ///
    /// ```
    /// # use mpd_protocol::response::{Frame, Response};
    /// let r = Response::empty();
    /// assert_eq!(Ok(Frame::empty()), r.single_frame());
    /// ```
    pub fn single_frame(self) -> Result<Frame, Error> {
        // There is always at least one frame
        self.into_iter().next().unwrap()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct ResponseBuilder {
    field_keys: FxHashSet<Arc<str>>,
    current_frame: Option<Frame>,
    frames: Vec<Frame>,
}

impl ResponseBuilder {
    pub(crate) fn new() -> Self {
        Self {
            field_keys: FxHashSet::default(),
            current_frame: Some(Frame::empty()),
            frames: Vec::new(),
        }
    }

    pub(crate) fn push_field(&mut self, key: &str, value: String) {
        let key = if let Some(v) = self.field_keys.get(key) {
            Arc::clone(v)
        } else {
            let v = Arc::from(key);
            self.field_keys.insert(Arc::clone(&v));
            v
        };

        self.current_frame().fields.push_field(key, value);
    }

    pub(crate) fn push_binary(&mut self, binary: BytesMut) {
        self.current_frame().binary = Some(binary);
    }

    pub(crate) fn finish_frame(&mut self) {
        let frame = self.current_frame.take().unwrap_or_else(Frame::empty);
        trace_frame_completed(&frame);
        self.frames.push(frame);
    }

    pub(crate) fn finish(mut self) -> Response {
        if let Some(frame) = self.current_frame {
            trace_frame_completed(&frame);
            self.frames.push(frame);
        }

        Response {
            frames: self.frames,
            error: None,
        }
    }

    pub(crate) fn error(mut self, error: Error) -> Response {
        if let Some(frame) = self.current_frame {
            trace_frame_completed(&frame);
            self.frames.push(frame);
        }

        Response {
            frames: self.frames,
            error: Some(error),
        }
    }

    fn current_frame(&mut self) -> &mut Frame {
        self.current_frame.get_or_insert_with(Frame::empty)
    }
}

fn trace_frame_completed(frame: &Frame) {
    trace!(
        fields = frame.fields_len(),
        has_binary = frame.has_binary(),
        "completed frame"
    );
}

impl Default for ResponseBuilder {
    fn default() -> Self {
        ResponseBuilder::new()
    }
}

/// Iterator over frames in a response, as returned by [`Response::frames`].
#[derive(Clone, Debug)]
pub struct FramesRef<'a> {
    frames: slice::Iter<'a, Frame>,
    error: option::IntoIter<&'a Error>,
}

impl<'a> Iterator for FramesRef<'a> {
    type Item = Result<&'a Frame, &'a Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(frame) = self.frames.next() {
            Some(Ok(frame))
        } else if let Some(error) = self.error.next() {
            Some(Err(error))
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let (mut len, _) = self.frames.size_hint();
        len += self.error.size_hint().0;

        (len, Some(len))
    }
}

impl<'a> FusedIterator for FramesRef<'a> {}
impl<'a> ExactSizeIterator for FramesRef<'a> {}

impl<'a> IntoIterator for &'a Response {
    type Item = Result<&'a Frame, &'a Error>;
    type IntoIter = FramesRef<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.frames()
    }
}

/// Iterator over frames in a response, as returned by [`IntoIterator`] implementation on
/// [`Response`].
#[derive(Clone, Debug)]
pub struct Frames {
    frames: vec::IntoIter<Frame>,
    error: Option<Error>,
}

impl Iterator for Frames {
    type Item = Result<Frame, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(f) = self.frames.next() {
            Some(Ok(f))
        } else if let Some(e) = self.error.take() {
            Some(Err(e))
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        // .len() returns the number of succesful frames, add 1 if there is also an error
        let len = self.frames.len() + if self.error.is_some() { 1 } else { 0 };

        (len, Some(len))
    }
}

impl FusedIterator for Frames {}
impl ExactSizeIterator for Frames {}

impl IntoIterator for Response {
    type Item = Result<Frame, Error>;
    type IntoIter = Frames;

    fn into_iter(self) -> Self::IntoIter {
        Frames {
            frames: self.frames.into_iter(),
            error: self.error,
        }
    }
}

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

    #[test]
    fn owned_frames_iter() {
        let r = Response::new(
            vec![Frame::empty(), Frame::empty(), Frame::empty()],
            Some(Error::default()),
        );

        let mut iter = r.into_iter();

        assert_eq!((4, Some(4)), iter.size_hint());
        assert_eq!(Some(Ok(Frame::empty())), iter.next());

        assert_eq!((3, Some(3)), iter.size_hint());
        assert_eq!(Some(Ok(Frame::empty())), iter.next());

        assert_eq!((2, Some(2)), iter.size_hint());
        assert_eq!(Some(Ok(Frame::empty())), iter.next());

        assert_eq!((1, Some(1)), iter.size_hint());
        assert_eq!(Some(Err(Error::default())), iter.next());

        assert_eq!((0, Some(0)), iter.size_hint());
    }

    #[test]
    fn borrowed_frames_iter() {
        let r = Response::new(
            vec![Frame::empty(), Frame::empty(), Frame::empty()],
            Some(Error::default()),
        );

        let mut iter = r.frames();

        assert_eq!((4, Some(4)), iter.size_hint());
        assert_eq!(Some(Ok(&Frame::empty())), iter.next());

        assert_eq!((3, Some(3)), iter.size_hint());
        assert_eq!(Some(Ok(&Frame::empty())), iter.next());

        assert_eq!((2, Some(2)), iter.size_hint());
        assert_eq!(Some(Ok(&Frame::empty())), iter.next());

        assert_eq!((1, Some(1)), iter.size_hint());
        assert_eq!(Some(Err(&Error::default())), iter.next());

        assert_eq!((0, Some(0)), iter.size_hint());
    }
}