mpd_protocol 1.0.3

Implementation of MPD client protocol
Documentation
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Tools for constructing MPD commands.
//!
//! For an overview of available commands, see the [MPD documentation].
//!
//! This does not perform any validations on commands beyond checking they appear well-formed, so
//! it should not be tied to any particular protocol version.
//!
//! [MPD documentation]: https://www.musicpd.org/doc/html/protocol.html#command-reference

use std::{
    borrow::Cow,
    error::Error,
    fmt::{self, Debug},
    time::Duration,
};

use bytes::{BufMut, Bytes, BytesMut};

/// Start a command list, separated with list terminators. Our parser can't separate messages when
/// the form of command list without terminators is used.
const COMMAND_LIST_BEGIN: &[u8] = b"command_list_ok_begin\n";

/// End a command list.
const COMMAND_LIST_END: &[u8] = b"command_list_end\n";

/// A single command, possibly including arguments.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Command(pub(crate) BytesMut);

impl Command {
    /// Start a new command.
    ///
    /// Same as [`Command::build`], but panics on error instead of returning a result.
    ///
    /// # Panics
    ///
    /// Panics where [`Command::build`] would return an error.
    #[track_caller]
    pub fn new(command: &str) -> Command {
        match Command::build(command) {
            Ok(c) => c,
            Err(e) => panic!("invalid command: {e}"),
        }
    }

    /// Start a new command.
    ///
    /// # Errors
    ///
    /// An error is returned when the command base is invalid.
    pub fn build(command: &str) -> Result<Command, CommandError> {
        match validate_command_part(command) {
            Ok(()) => Ok(Command(BytesMut::from(command))),
            Err(kind) => Err(CommandError {
                data: Bytes::copy_from_slice(command.as_bytes()),
                kind,
            }),
        }
    }

    /// Add an argument to the command.
    ///
    /// Same as [`Command::add_argument`], but panics on error and allows chaining.
    ///
    /// # Panics
    ///
    /// Panics where [`Command::add_argument`] would return an error.
    #[track_caller]
    pub fn argument<A: Argument>(mut self, argument: A) -> Command {
        if let Err(e) = self.add_argument(argument) {
            panic!("invalid argument: {e}");
        }

        self
    }

    /// Add an argument to the command.
    ///
    /// # Errors
    ///
    /// An error is returned when the argument is invalid (e.g. empty string or containing invalid
    /// characters such as newlines).
    pub fn add_argument<A: Argument>(&mut self, argument: A) -> Result<(), CommandError> {
        let len_without_arg = self.0.len();

        self.0.put_u8(b' ');
        argument.render(&mut self.0);

        if let Err(kind) = validate_argument(&self.0[len_without_arg + 1..]) {
            // Remove added invalid part again
            let data = self.0.split_off(len_without_arg + 1).freeze();
            self.0.truncate(len_without_arg);

            Err(CommandError { data, kind })
        } else {
            Ok(())
        }
    }
}

/// A non-empty list of commands.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CommandList(pub(crate) Vec<Command>);

#[allow(clippy::len_without_is_empty)]
impl CommandList {
    /// Create a command list from the given single command.
    ///
    /// Unless further commands are added, the command will not be wrapped into a list.
    pub fn new(first: Command) -> Self {
        CommandList(vec![first])
    }

    /// Add another command to the list.
    ///
    /// Same as [`CommandList::add`], but takes and returns `self` for chaining.
    pub fn command(mut self, command: Command) -> Self {
        self.add(command);
        self
    }

    /// Add another command to the list.
    pub fn add(&mut self, command: Command) {
        self.0.push(command);
    }

    /// Get the number of commands in this command list.
    ///
    /// This is never 0.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub(crate) fn render(mut self) -> BytesMut {
        if self.len() == 1 {
            let mut buf = self.0.pop().unwrap().0;
            buf.put_u8(b'\n');
            return buf;
        }

        // Calculate required length
        let required_length = COMMAND_LIST_BEGIN.len()
            + self.0.iter().map(|c| c.0.len() + 1).sum::<usize>()
            + COMMAND_LIST_END.len();

        let mut buf = BytesMut::with_capacity(required_length);

        buf.put_slice(COMMAND_LIST_BEGIN);
        for command in self.0 {
            buf.put_slice(&command.0);
            buf.put_u8(b'\n');
        }
        buf.put_slice(COMMAND_LIST_END);

        buf
    }
}

impl Extend<Command> for CommandList {
    fn extend<T: IntoIterator<Item = Command>>(&mut self, iter: T) {
        self.0.extend(iter);
    }
}

/// Escape a single argument, prefixing necessary characters (quotes and backslashes) with
/// backslashes.
///
/// Returns a borrowed [`Cow`] if the argument did not require escaping.
///
/// ```
/// # use mpd_protocol::command::escape_argument;
/// assert_eq!(escape_argument("foo'bar\""), "foo\\'bar\\\"");
/// ```
pub fn escape_argument(argument: &str) -> Cow<'_, str> {
    let needs_quotes = argument.contains(&[' ', '\t'][..]);
    let escape_count = argument.chars().filter(|c| should_escape(*c)).count();

    if escape_count == 0 && !needs_quotes {
        // The argument does not need to be quoted or escaped, return back an unmodified reference
        Cow::Borrowed(argument)
    } else {
        // The base length of the argument + a backslash for each escaped character + two quotes if
        // necessary
        let len = argument.len() + escape_count + if needs_quotes { 2 } else { 0 };
        let mut out = String::with_capacity(len);

        if needs_quotes {
            out.push('"');
        }

        for c in argument.chars() {
            if should_escape(c) {
                out.push('\\');
            }

            out.push(c);
        }

        if needs_quotes {
            out.push('"');
        }

        Cow::Owned(out)
    }
}

/// If the given character needs to be escaped
fn should_escape(c: char) -> bool {
    c == '\\' || c == '"' || c == '\''
}

fn validate_command_part(command: &str) -> Result<(), CommandErrorKind> {
    if command.is_empty() {
        return Err(CommandErrorKind::Empty);
    }

    if let Some((i, c)) = command
        .char_indices()
        .find(|(_, c)| !is_valid_command_char(*c))
    {
        Err(CommandErrorKind::InvalidCharacter(i, c))
    } else if is_command_list_command(command) {
        Err(CommandErrorKind::CommandList)
    } else {
        Ok(())
    }
}

/// Validate an argument.
fn validate_argument(argument: &[u8]) -> Result<(), CommandErrorKind> {
    match argument.iter().position(|&c| c == b'\n') {
        None => Ok(()),
        Some(i) => Err(CommandErrorKind::InvalidCharacter(i, '\n')),
    }
}

/// Commands can consist of alphabetic chars and underscores
fn is_valid_command_char(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_'
}

/// Returns `true` if the given command would start or end a command list.
fn is_command_list_command(command: &str) -> bool {
    command.starts_with("command_list")
}

/// Error returned when attempting to create invalid commands or arguments.
#[derive(Debug)]
pub struct CommandError {
    data: Bytes,
    kind: CommandErrorKind,
}

/// Error returned when attempting to construct an invalid command.
#[derive(Debug)]
enum CommandErrorKind {
    /// The command was empty (either an empty command or an empty list commands).
    Empty,
    /// The command string contained an invalid character at the contained position. This is
    /// context-dependent, as some characters are only invalid in certain sections of a command.
    InvalidCharacter(usize, char),
    /// Attempted to start or close a command list manually.
    CommandList,
}

impl Error for CommandError {}

impl fmt::Display for CommandError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            CommandErrorKind::Empty => write!(f, "empty command"),
            CommandErrorKind::InvalidCharacter(i, c) => {
                write!(
                    f,
                    "invalid character {:?} at position {} in {:?}",
                    c, i, self.data
                )
            }
            CommandErrorKind::CommandList => write!(
                f,
                "attempted to open or close a command list: {:?}",
                self.data
            ),
        }
    }
}

/// Things which can be used as arguments for commands.
pub trait Argument {
    /// Render the argument into the command buffer.
    ///
    /// Spaces before/after arguments are inserted automatically, but values need to be escaped
    /// manually. See [`escape_argument`].
    fn render(&self, buf: &mut BytesMut);
}

impl<A> Argument for &A
where
    A: Argument + ?Sized,
{
    fn render(&self, buf: &mut BytesMut) {
        (*self).render(buf);
    }
}

impl Argument for String {
    fn render(&self, buf: &mut BytesMut) {
        let arg = escape_argument(self);
        buf.put_slice(arg.as_bytes());
    }
}

impl Argument for str {
    fn render(&self, buf: &mut BytesMut) {
        let arg = escape_argument(self);
        buf.put_slice(arg.as_bytes());
    }
}

impl Argument for Cow<'_, str> {
    fn render(&self, buf: &mut BytesMut) {
        let arg = escape_argument(self);
        buf.put_slice(arg.as_bytes());
    }
}

impl Argument for bool {
    fn render(&self, buf: &mut BytesMut) {
        buf.put_u8(if *self { b'1' } else { b'0' });
    }
}

impl Argument for Duration {
    /// Song durations in the format MPD expects. Will round to third decimal place.
    fn render(&self, buf: &mut BytesMut) {
        use std::fmt::Write;
        write!(buf, "{:.3}", self.as_secs_f64()).unwrap();
    }
}

macro_rules! implement_integer_arg {
    ($($type:ty),+) => {
        $(
            impl $crate::command::Argument for $type {
                fn render(&self, buf: &mut ::bytes::BytesMut) {
                    use ::std::fmt::Write;
                    ::std::write!(buf, "{}", self).unwrap();
                }
            }
        )+
    }
}

implement_integer_arg!(u8, u16, u32, u64, usize);

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

    #[test]
    fn arguments() {
        let mut command = Command::new("foo");
        assert_eq!(command.0, "foo");

        command.add_argument("bar").unwrap();
        assert_eq!(command.0, "foo bar");

        // Invalid argument does not change the command
        let _e = command.add_argument("foo\nbar").unwrap_err();
        assert_eq!(command.0, "foo bar");
    }

    #[test]
    fn argument_escaping() {
        assert_eq!(escape_argument("status"), "status");
        assert_eq!(escape_argument("Joe's"), "Joe\\'s");
        assert_eq!(escape_argument("hello\\world"), "hello\\\\world");
        assert_eq!(escape_argument("foo bar"), r#""foo bar""#);
    }

    #[test]
    fn argument_rendering() {
        let mut buf = BytesMut::new();

        "foo\"bar".render(&mut buf);
        assert_eq!(buf, "foo\\\"bar");
        buf.clear();

        true.render(&mut buf);
        assert_eq!(buf, "1");
        buf.clear();

        false.render(&mut buf);
        assert_eq!(buf, "0");
        buf.clear();

        Duration::from_secs(2).render(&mut buf);
        assert_eq!(buf, "2.000");
        buf.clear();

        Duration::from_secs_f64(2.34567).render(&mut buf);
        assert_eq!(buf, "2.346");
        buf.clear();
    }
}