mpd_protocol-1.0.3/.cargo_vcs_info.json0000644000000001520000000000100135340ustar { "git": { "sha1": "c56e165ced2147a6227ec78cca708991c0f9c280" }, "path_in_vcs": "mpd_protocol" }mpd_protocol-1.0.3/CHANGELOG.md000064400000000000000000000044201046102023000141370ustar 00000000000000# 1.0.3 (2024-02-28) - Dependency updates. # 1.0.2 (2023-10-30) - Dependency updates # 1.0.1 (2023-07-01) - Internal improvements, dependency updates # 1.0.0 (2022-08-27) - Redesign and simplify the `Argument` trait - Make `CommandError` type opaque - API changes: - Rename `Frame::get_binary` to `Frame::take_binary` - Rename `Response::single_frame` to `Response::into_single_frame` - Remove `Response` root reexport # 0.13.0 (2021-12-09) - Redesign connection interface. - Instead of standalone functions for the synchronous API and a `Codec` implementation for the asynchronous API, connections are now represented as structs with either synchronous or asynchronous methods (`Connection` and `AsyncConnection`). As a result, the asynchronous API no longer consists of a `Sink` for commands and a corresponding `Stream` of responses, but individual methods that either write commands or read a response. # 0.12.1 (2021-05-13) - No external changes (only doc fixes) # 0.12.0 (2021-05-13) - Make async functionality optional by moving it behind the default-off `async` feature flag. Without it, the `tokio` dependencies are removed. - Rename error type from `MpdCodecError` to `MpdProtocolError` to reflect the above change. - Remove raw message contents from `InvalidMessage` error variant. - API changes: - Remove `Response::new()` and `Response::empty()` methods - Rename `Response::len()` to `Response::successful_frames()` - Remove `Frame::empty()` - Add `DoubleEndedIterator` implementations for response frame iterators - Internal improvements. # 0.11.0 (2021-01-01) - Update to `tokio` 1.0. # 0.10.1 (2020-11-20) - Update to `nom` 6. # 0.10.0 (2020-11-02) - Update `tokio-util` and `bytes` crates. # 0.9.0 (2020-10-23) - Update to tokio 0.3 - Provide basic functions for sending and receiving using synchronous IO - Don't depend on nom features we don't actually use - Reword error messages to follow API guidelines # 0.8.1 (2020-08-05) - Change license to MIT or Apache 2.0 # 0.8.0 (2020-08-02) - Rewritten parser that incrementally builds up a response - Explicit connection method that creates a codec instead of handling the handshake internally - Overhauled Frame APIs - Removed `command_list` macro - Many smaller changes mpd_protocol-1.0.3/Cargo.toml0000644000000027160000000000100115420ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "mpd_protocol" version = "1.0.3" description = "Implementation of MPD client protocol" readme = "README.md" keywords = [ "mpd", "protocol", "client", ] categories = ["network-programming"] license = "MIT OR Apache-2.0" repository = "https://github.com/elomatreb/mpd_client" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [[bench]] name = "parse_response" harness = false [dependencies.ahash] version = "0.8.9" [dependencies.bytes] version = "1.5.0" [dependencies.nom] version = "7.1.3" [dependencies.tokio] version = "1.36.0" features = ["io-util"] optional = true [dependencies.tracing] version = "0.1.40" [dev-dependencies.assert_matches] version = "1.5.0" [dev-dependencies.criterion] version = "0.5.1" [dev-dependencies.tokio] version = "1.36.0" features = [ "io-util", "rt", "rt-multi-thread", "macros", "net", ] [dev-dependencies.tokio-test] version = "0.4.3" [features] async = ["tokio"] mpd_protocol-1.0.3/Cargo.toml.orig000064400000000000000000000016361046102023000152230ustar 00000000000000[package] name = "mpd_protocol" version = "1.0.3" edition = "2021" license = "MIT OR Apache-2.0" description = "Implementation of MPD client protocol" repository = "https://github.com/elomatreb/mpd_client" readme = "README.md" keywords = ["mpd", "protocol", "client"] categories = ["network-programming"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] async = ["tokio"] [dependencies] ahash = "0.8.9" bytes = "1.5.0" nom = "7.1.3" tokio = { version = "1.36.0", features = ["io-util"], optional = true } tracing = "0.1.40" [dev-dependencies] assert_matches = "1.5.0" criterion = "0.5.1" tokio = { version = "1.36.0", features = [ "io-util", "rt", "rt-multi-thread", "macros", "net", ] } tokio-test = "0.4.3" [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] [[bench]] name = "parse_response" harness = false mpd_protocol-1.0.3/LICENSE-APACHE000064400000000000000000000251371046102023000142620ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. mpd_protocol-1.0.3/LICENSE-MIT000064400000000000000000000020371046102023000137640ustar 00000000000000Copyright (c) 2020 Ole Bertram Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. mpd_protocol-1.0.3/README.md000064400000000000000000000015561046102023000136140ustar 00000000000000# `mpd_protocol` Implementation of the client protocol for [MPD]. ## Features - Protocol support including binary responses and command lists - Support for traditional blocking IO as well as asynchronous IO (through [Tokio], requires the `async` feature flag) - Utilities for assembling commands and escaping arguments ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. #### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [MPD]: https://musicpd.org [Tokio]: https://tokio.rs mpd_protocol-1.0.3/benches/.gitignore000064400000000000000000000000161046102023000157220ustar 00000000000000long.response mpd_protocol-1.0.3/benches/parse_response.rs000064400000000000000000000011131046102023000173270ustar 00000000000000use criterion::{black_box, criterion_group, criterion_main, Criterion}; use mpd_protocol::Connection; // NOTE: Benchmark requires `--cfg criterion` to be set to build correctly. const LONG_RESPONSE: &[u8] = include_bytes!("long.response"); pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("long response", |b| { b.iter(|| { let mut connection = Connection::new_internal(black_box(LONG_RESPONSE)); let _ = connection.receive().unwrap(); }) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); mpd_protocol-1.0.3/src/command.rs000064400000000000000000000265101046102023000151050ustar 00000000000000//! 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 { 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(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(&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); #[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::() + 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 for CommandList { fn extend>(&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 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(); } } mpd_protocol-1.0.3/src/connection.rs000064400000000000000000000542571046102023000156370ustar 00000000000000use std::io::{self, Read, Write}; use bytes::{BufMut, BytesMut}; #[cfg(feature = "async")] use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tracing::{debug, error, info, trace}; use crate::{ command::{Command, CommandList}, parser, response::{Response, ResponseBuilder, ResponseFieldCache}, MpdProtocolError, }; /// Default receive buffer size const DEFAULT_BUFFER_CAPACITY: usize = 4096; /// A **blocking** connection to an MPD server. #[derive(Debug)] pub struct Connection { io: IO, protocol_version: Box, field_cache: ResponseFieldCache, recv_buf: BytesMut, total_received: usize, } impl Connection { #[cfg(any(fuzzing, criterion))] #[allow(dead_code)] #[doc(hidden)] pub fn new_internal(io: IO) -> Connection { Connection { io, protocol_version: Box::from(""), field_cache: ResponseFieldCache::new(), recv_buf: BytesMut::zeroed(DEFAULT_BUFFER_CAPACITY), total_received: 0, } } /// Connect to an MPD server synchronously. #[tracing::instrument(skip_all, err)] pub fn connect(mut io: IO) -> Result, MpdProtocolError> where IO: Read, { let mut recv_buf = BytesMut::zeroed(DEFAULT_BUFFER_CAPACITY); let mut total_read = 0; let protocol_version = loop { let (data, amount_read) = read_to_buffer(&mut io, &mut recv_buf, &mut total_read)?; if amount_read == 0 { return Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "unexpected end of file while receiving greeting", ))); } match parser::greeting(data) { Ok((_, version)) => { info!(?version, "connected successfully"); break Box::from(version); } Err(e) if e.is_incomplete() => { // The response was valid *so far*, try another read trace!("greeting incomplete"); } Err(_) => { error!("invalid greeting"); return Err(MpdProtocolError::InvalidMessage); } } }; Ok(Connection { io, protocol_version, field_cache: ResponseFieldCache::new(), recv_buf, total_received: 0, }) } /// Send a command. /// /// # Errors /// /// This will return an error if writing to the given IO resource fails. #[tracing::instrument(skip(self), err)] pub fn send(&mut self, mut command: Command) -> Result<(), MpdProtocolError> where IO: Write, { command.0.put_u8(b'\n'); self.io.write_all(&command.0)?; debug!(length = command.0.len(), "sent command"); Ok(()) } /// Send a command list. /// /// # Errors /// /// This will return an error if writing to the given IO resource fails. #[tracing::instrument(skip(self), err)] pub fn send_list(&mut self, command_list: CommandList) -> Result<(), MpdProtocolError> where IO: Write, { let buf = command_list.render(); self.io.write_all(&buf)?; debug!(length = buf.len(), "sent command list"); Ok(()) } /// Receive a response from the server. /// /// This will return `Ok(Some(..))` when a complete response has been received, or `Ok(None)` if /// the connection is closed cleanly. /// /// # Errors /// /// This will return an error if: /// /// - Reading from the given IO resource returns an error /// - Malformed response data is received /// - The connection is closed while a response is in progress #[tracing::instrument(skip(self), err)] pub fn receive(&mut self) -> Result, MpdProtocolError> where IO: Read, { let mut response_builder = ResponseBuilder::new(&mut self.field_cache); loop { // Split off the read part of the receive buffer let buf_size = self.recv_buf.len(); let remaining = self.recv_buf.split_off(self.total_received); // Try to parse response data from the initialized section of the buffer, removing the // consumed parts from the buffer let maybe_parsed = response_builder.parse(&mut self.recv_buf)?; // Update the length of the initialized section to the remaining length self.total_received = self.recv_buf.len(); // Join back the remaining data with the main buffer, and readjust the length self.recv_buf.unsplit(remaining); self.recv_buf.resize(buf_size, 0); if let Some(response) = maybe_parsed { debug!( frames = response.successful_frames(), error = response.is_error(), fields = response.field_count(), "received complete response" ); break Ok(Some(response)); } let (_, amount_read) = read_to_buffer(&mut self.io, &mut self.recv_buf, &mut self.total_received)?; if amount_read == 0 { break if response_builder.is_frame_in_progress() || self.total_received != 0 { error!("EOF while receiving response"); Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "unexpected end of file while receiving response", ))) } else { debug!("clean EOF while receiving response"); Ok(None) }; } } } /// Send a command and receive its response. /// /// This is essentially a shorthand for [`Connection::send`] followed by [`Connection::receive`]. /// /// # Errors /// /// This will return an error if: /// /// - Writing to or reading from the connection returns an error /// - Malformed response data is received /// - The connection is closed #[tracing::instrument(skip(self), err)] pub fn command(&mut self, command: Command) -> Result where IO: Read + Write, { self.send(command)?; if let Some(r) = self.receive()? { Ok(r) } else { error!("connection was closed without a response to the command"); Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "connection was closed without a response to the command", ))) } } /// Send a command list and receive its response(s). /// /// This is essentially a shorthand for [`Connection::send_list`] followed by [`Connection::receive`]. /// /// # Errors /// /// This will return an error if: /// /// - Writing to or reading from the connection returns an error /// - Malformed response data is received /// - The connection is closed #[tracing::instrument(skip(self), err)] pub fn command_list(&mut self, command_list: CommandList) -> Result where IO: Read + Write, { self.send_list(command_list)?; if let Some(r) = self.receive()? { Ok(r) } else { error!("connection was closed without a response to the command"); Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "connection was closed without a response to the command", ))) } } /// Returns the protocol version the server is using. pub fn protocol_version(&self) -> &str { &self.protocol_version } /// Extract the connection instance. pub fn into_inner(self) -> IO { self.io } } fn read_to_buffer<'a, R: Read>( mut io: R, buf: &'a mut BytesMut, total: &mut usize, ) -> Result<(&'a [u8], usize), io::Error> { let read = io.read(&mut buf[*total..])?; trace!(read); *total += read; if buf.len() == *total { trace!("need to grow buffer"); buf.resize(buf.len() * 2, 0); } Ok((&buf[..*total], read)) } /// An **asynchronous** connection to an MPD server. #[cfg(feature = "async")] #[cfg_attr(docsrs, doc(cfg(feature = "async")))] #[derive(Debug)] pub struct AsyncConnection(Connection); #[cfg(feature = "async")] impl AsyncConnection { /// Connect to an MPD server asynchronously. /// /// # Errors /// /// This will return an error if: /// /// - Reading from the given IO resource returns an error /// - A malformed greeting is received /// - The connection is closed before a complete greeting could be read #[cfg_attr(docsrs, doc(cfg(feature = "async")))] #[tracing::instrument(skip_all, err)] pub async fn connect(mut io: IO) -> Result, MpdProtocolError> where IO: AsyncRead + Unpin, { let mut recv_buf = BytesMut::with_capacity(DEFAULT_BUFFER_CAPACITY); let protocol_version = loop { let read = io.read_buf(&mut recv_buf).await?; trace!(read); if read == 0 { return Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "unexpected end of file while receiving greeting", ))); } match parser::greeting(&recv_buf) { Ok((_, version)) => { info!(?version, "connected successfully"); break Box::from(version); } Err(e) if e.is_incomplete() => { // The response was valid *so far*, try another read trace!("greeting incomplete"); } Err(_) => { error!("invalid greeting"); return Err(MpdProtocolError::InvalidMessage); } } }; recv_buf.clear(); Ok(AsyncConnection(Connection { io, protocol_version, field_cache: ResponseFieldCache::new(), recv_buf, total_received: 0, })) } /// Send a command. /// /// # Errors /// /// This will return an error if writing to the given IO resource fails. #[cfg_attr(docsrs, doc(cfg(feature = "async")))] #[tracing::instrument(skip(self), err)] pub async fn send(&mut self, mut command: Command) -> Result<(), MpdProtocolError> where IO: AsyncWrite + Unpin, { command.0.put_u8(b'\n'); self.0.io.write_all(&command.0).await?; debug!(length = command.0.len(), "sent command"); Ok(()) } /// Send a command list. /// /// # Errors /// /// This will return an error if writing to the given IO resource fails. #[cfg_attr(docsrs, doc(cfg(feature = "async")))] #[tracing::instrument(skip(self), err)] pub async fn send_list(&mut self, command_list: CommandList) -> Result<(), MpdProtocolError> where IO: AsyncWrite + Unpin, { let buf = command_list.render(); self.0.io.write_all(&buf).await?; debug!(length = buf.len(), "sent command"); Ok(()) } /// Receive a response from the server. /// /// This will return `Ok(Some(..))` when a complete response has been received, or `Ok(None)` if /// the connection is closed cleanly. /// /// # Errors /// /// This will return an error if: /// /// - Reading from the given IO resource returns an error /// - Malformed response data is received /// - The connection is closed while a response is in progress #[cfg_attr(docsrs, doc(cfg(feature = "async")))] #[tracing::instrument(skip(self), err)] pub async fn receive(&mut self) -> Result, MpdProtocolError> where IO: AsyncRead + Unpin, { let mut response_builder = ResponseBuilder::new(&mut self.0.field_cache); loop { if let Some(response) = response_builder.parse(&mut self.0.recv_buf)? { debug!( frames = response.successful_frames(), fields = response.field_count(), error = response.is_error(), "received complete response" ); break Ok(Some(response)); } let read = self.0.io.read_buf(&mut self.0.recv_buf).await?; trace!(read); if read == 0 { break if response_builder.is_frame_in_progress() || !self.0.recv_buf.is_empty() { error!("EOF while receiving response"); Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "unexpected end of file while receiving response", ))) } else { debug!("clean EOF while receiving"); Ok(None) }; } } } /// Send a command and receive its response. /// /// This is essentially a shorthand for [`AsyncConnection::send`] followed by /// [`AsyncConnection::receive`]. /// /// # Errors /// /// This will return an error if: /// /// - Writing to or reading from the connection returns an error /// - Malformed response data is received /// - The connection is closed #[tracing::instrument(skip(self), err)] pub async fn command(&mut self, command: Command) -> Result where IO: AsyncRead + AsyncWrite + Unpin, { self.send(command).await?; if let Some(r) = self.receive().await? { Ok(r) } else { error!("connection was closed without a response to the command"); Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "connection was closed without a response to the command", ))) } } /// Send a command list and receive its response(s). /// /// This is essentially a shorthand for [`AsyncConnection::send_list`] followed by /// [`AsyncConnection::receive`]. /// /// # Errors /// /// This will return an error if: /// /// - Writing to or reading from the connection returns an error /// - Malformed response data is received /// - The connection is closed #[tracing::instrument(skip(self), err)] pub async fn command_list( &mut self, command_list: CommandList, ) -> Result where IO: AsyncRead + AsyncWrite + Unpin, { self.send_list(command_list).await?; if let Some(r) = self.receive().await? { Ok(r) } else { error!("connection was closed without a response to the command"); Err(MpdProtocolError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "connection was closed without a response to the command", ))) } } /// Returns the protocol version the server is using. pub fn protocol_version(&self) -> &str { &self.0.protocol_version } /// Extract the connection instance. pub fn into_inner(self) -> IO { self.0.io } } #[cfg(test)] mod tests_sync { use assert_matches::assert_matches; use super::*; fn new_conn(io: IO) -> Connection { Connection { io, field_cache: ResponseFieldCache::new(), protocol_version: Box::from(""), recv_buf: BytesMut::zeroed(DEFAULT_BUFFER_CAPACITY), total_received: 0, } } #[test] fn connect() { let io: &[u8] = b"OK MPD 0.23.3\n"; let connection = Connection::connect(io).unwrap(); assert_eq!(connection.protocol_version(), "0.23.3"); } #[test] fn connect_eof() { let io: &[u8] = b"OK MPD 0.23.3"; let connection = Connection::connect(io).unwrap_err(); assert_matches!(connection, MpdProtocolError::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof); } #[test] fn connect_invalid() { let io: &[u8] = b"foobar\n"; let connection = Connection::connect(io).unwrap_err(); assert_matches!(connection, MpdProtocolError::InvalidMessage); } #[test] fn send() { let mut io = Vec::new(); let mut connection = new_conn(&mut io); connection .send(Command::new("foo").argument("bar")) .unwrap(); assert_eq!(io, b"foo bar\n"); } #[test] fn send_list() { let mut io = Vec::new(); let mut connection = new_conn(&mut io); let list = CommandList::new(Command::new("foo")).command(Command::new("bar")); connection.send_list(list).unwrap(); assert_eq!( io, b"command_list_ok_begin\n\ foo\n\ bar\n\ command_list_end\n" ); } #[test] fn receive() { let io: &[u8] = b"foo: bar\nOK\n"; let mut connection = new_conn(io); let response = connection.receive(); assert_matches!(response, Ok(Some(_))); } #[test] fn receive_eof() { let io: &[u8] = b"foo: bar\nOK"; let mut connection = new_conn(io); let response = connection.receive(); assert_matches!(response, Err(MpdProtocolError::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof); } } #[cfg(test)] #[cfg(feature = "async")] mod tests_async { use assert_matches::assert_matches; use tokio_test::io::Builder as MockBuilder; use super::*; fn new_conn(io: IO) -> AsyncConnection { AsyncConnection(Connection { io, field_cache: ResponseFieldCache::new(), protocol_version: Box::from(""), recv_buf: BytesMut::new(), total_received: 0, }) } #[tokio::test] async fn connect() { let io = MockBuilder::new().read(b"OK MPD 0.23.3\n").build(); let connection = AsyncConnection::connect(io).await.unwrap(); assert_eq!(connection.protocol_version(), "0.23.3"); } #[tokio::test] async fn connect_split_read() { let io = MockBuilder::new() .read(b"OK MPD 0.23.3") .read(b"\n") .build(); let connection = AsyncConnection::connect(io).await.unwrap(); assert_eq!(connection.protocol_version(), "0.23.3"); } #[tokio::test] async fn connect_eof() { let io = MockBuilder::new().read(b"OK MPD 0.23.3").build(); // no newline let connection = AsyncConnection::connect(io).await.unwrap_err(); assert_matches!(connection, MpdProtocolError::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof); } #[tokio::test] async fn connect_invalid() { let io = MockBuilder::new().read(b"OK foobar\n").build(); let connection = AsyncConnection::connect(io).await.unwrap_err(); assert_matches!(connection, MpdProtocolError::InvalidMessage); } #[tokio::test] async fn send_single() { let io = MockBuilder::new().write(b"status\n").build(); let mut connection = new_conn(io); connection.send(Command::new("status")).await.unwrap(); } #[tokio::test] async fn send_list() { let list = CommandList::new(Command::new("foo")).command(Command::new("bar")); let io = MockBuilder::new() .write( b"command_list_ok_begin\n\ foo\n\ bar\n\ command_list_end\n", ) .build(); let mut connection = new_conn(io); connection.send_list(list).await.unwrap(); } #[tokio::test] async fn send_list_single() { let list = CommandList::new(Command::new("foo")); let io = MockBuilder::new().write(b"foo\n").build(); // skips command list wrapping let mut connection = new_conn(io); connection.send_list(list).await.unwrap(); } #[tokio::test] async fn receive() { let io = MockBuilder::new().read(b"foo: bar\nOK\n").build(); let mut connection = new_conn(io); let response = connection.receive().await.unwrap(); assert_matches!(response, Some(response) if response.is_success()); } #[tokio::test] async fn receive_split_read() { let io = MockBuilder::new().read(b"foo: bar\nOK").read(b"\n").build(); let mut connection = new_conn(io); let response = connection.receive().await.unwrap(); assert_matches!(response, Some(response) if response.is_success()); } #[tokio::test] async fn receive_eof_clean() { let io = MockBuilder::new().build(); let mut connection = new_conn(io); let response = connection.receive().await.unwrap(); assert_eq!(response, None); } #[tokio::test] async fn receive_eof() { let io = MockBuilder::new().read(b"foo: bar\n").build(); let mut connection = new_conn(io); let error = connection.receive().await.unwrap_err(); assert_matches!(error, MpdProtocolError::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof); } #[tokio::test] async fn receive_multiple() { let io = MockBuilder::new().read(b"OK\nOK\n").build(); let mut connection = new_conn(io); let response = connection.receive().await.unwrap(); assert_matches!(response, Some(response) if response.is_success()); let response = connection.receive().await.unwrap(); assert_matches!(response, Some(response) if response.is_success()); let response = connection.receive().await.unwrap(); assert_matches!(response, None); } #[tokio::test] async fn command() { let io = MockBuilder::new() .write(b"foo\n") .read(b"bar: baz\nOK\n") .build(); let mut connection = new_conn(io); let resp = connection.command(Command::new("foo")).await.unwrap(); assert_eq!(resp.field_count(), 1); } } mpd_protocol-1.0.3/src/lib.rs000064400000000000000000000031651046102023000142360ustar 00000000000000#![warn( missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub )] #![deny(rustdoc::broken_intra_doc_links)] #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] //! Implementation of the client protocol for [MPD]. Supports binary responses and command lists. //! //! # Crate Features //! //! | Feature | Description | //! |---------|---------------------------------| //! | `async` | Async support, based on [Tokio] | //! //! [MPD]: https://musicpd.org //! [Tokio]: https://tokio.rs pub mod command; pub mod response; mod connection; mod parser; use std::{error::Error, fmt, io}; #[cfg(feature = "async")] pub use self::connection::AsyncConnection; pub use self::{ command::{Command, CommandList}, connection::Connection, }; /// Unrecoverable errors. #[derive(Debug)] pub enum MpdProtocolError { /// IO error occurred Io(io::Error), /// A message could not be parsed successfully. InvalidMessage, } impl fmt::Display for MpdProtocolError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { MpdProtocolError::Io(_) => write!(f, "IO error"), MpdProtocolError::InvalidMessage => write!(f, "invalid message"), } } } #[doc(hidden)] impl From for MpdProtocolError { fn from(e: io::Error) -> Self { MpdProtocolError::Io(e) } } impl Error for MpdProtocolError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { MpdProtocolError::Io(e) => Some(e), MpdProtocolError::InvalidMessage => None, } } } mpd_protocol-1.0.3/src/parser.rs000064400000000000000000000165561046102023000147740ustar 00000000000000//! Parser for MPD responses. use std::{ str::{self, from_utf8, FromStr}, sync::Arc, }; use nom::{ branch::alt, bytes::streaming::{tag, take, take_until, take_while, take_while1}, character::{ is_alphabetic, streaming::{char, digit1, newline}, }, combinator::{cut, map, map_res, opt}, sequence::{delimited, separated_pair, terminated, tuple}, IResult, }; use crate::response::{Error, ResponseFieldCache}; #[derive(Debug, PartialEq, Eq)] pub(crate) enum ParsedComponent { EndOfFrame, EndOfResponse, Error(Error), Field { key: Arc, value: String }, BinaryField { data_length: usize }, } #[derive(Debug, PartialEq, Eq)] struct RawError<'raw> { code: u64, command_index: u64, current_command: Option<&'raw str>, message: &'raw str, } impl ParsedComponent { pub(crate) fn parse<'i>( i: &'i [u8], field_cache: &'_ mut ResponseFieldCache, ) -> IResult<&'i [u8], ParsedComponent> { alt(( map(tag("OK\n"), |_| ParsedComponent::EndOfResponse), map(tag("list_OK\n"), |_| ParsedComponent::EndOfFrame), map(error, |e| ParsedComponent::Error(e.into_owned_error())), map(binary_field, |bin| ParsedComponent::BinaryField { data_length: bin.len(), }), map(key_value_field, |(k, v)| ParsedComponent::Field { key: field_cache.insert(k), value: String::from(v), }), ))(i) } } impl RawError<'_> { fn into_owned_error(self) -> Error { Error { code: self.code, command_index: self.command_index, current_command: self.current_command.map(Box::from), message: Box::from(self.message), } } } /// Recognize a server greeting, returning the protocol version. pub(crate) fn greeting(i: &[u8]) -> IResult<&[u8], &str> { delimited( tag("OK MPD "), map_res(take_while1(|c| c != b'\n'), from_utf8), newline, )(i) } /// Recognize and parse an unsigned ASCII-encoded number fn number(i: &[u8]) -> IResult<&[u8], O> { map_res(map_res(digit1, from_utf8), str::parse)(i) } /// Parse an error response. fn error(i: &[u8]) -> IResult<&[u8], RawError<'_>> { let (remaining, ((code, index), command, message)) = delimited( tag("ACK "), tuple(( terminated(error_code_and_index, char(' ')), terminated(error_current_command, char(' ')), map_res(take_while(|b| b != b'\n'), from_utf8), )), newline, )(i)?; Ok(( remaining, RawError { code, message, command_index: index, current_command: command, }, )) } /// Recognize `[@]`. fn error_code_and_index(i: &[u8]) -> IResult<&[u8], (u64, u64)> { delimited( char('['), separated_pair(number, char('@'), number), char(']'), )(i) } /// Recognize the current command in an error, `None` if empty. fn error_current_command(i: &[u8]) -> IResult<&[u8], Option<&str>> { delimited( char('{'), opt(map_res( take_while1(|b| is_alphabetic(b) || b == b'_'), from_utf8, )), char('}'), )(i) } /// Recognize a single key-value pair fn key_value_field(i: &[u8]) -> IResult<&[u8], (&str, &str)> { separated_pair( map_res( take_while1(|b| is_alphabetic(b) || b == b'_' || b == b'-'), from_utf8, ), tag(": "), map_res(field_value, from_utf8), )(i) } fn field_value(i: &[u8]) -> IResult<&[u8], &[u8]> { let (i, value) = take_until("\n")(i)?; Ok((&i[1..], value)) } /// Recognize the header of a binary section fn binary_prefix(i: &[u8]) -> IResult<&[u8], usize> { delimited(tag("binary: "), number, newline)(i) } /// Recognize a binary field fn binary_field(i: &[u8]) -> IResult<&[u8], &[u8]> { let (i, length) = binary_prefix(i)?; cut(terminated(take(length), newline))(i) } #[cfg(test)] mod test { use nom::{Err as NomErr, Needed}; use super::*; const EMPTY: &[u8] = &[]; #[test] fn greeting() { assert_eq!(super::greeting(b"OK MPD 0.21.11\n"), Ok((EMPTY, "0.21.11"))); assert!(super::greeting(b"OK MPD 0.21.11") .unwrap_err() .is_incomplete()); } #[test] fn end_markers() { let keys = &mut ResponseFieldCache::new(); assert_eq!( ParsedComponent::parse(b"OK\n", keys), Ok((EMPTY, ParsedComponent::EndOfResponse)) ); assert_eq!( ParsedComponent::parse(b"OK", keys), Err(NomErr::Incomplete(Needed::new(1))) ); assert_eq!( ParsedComponent::parse(b"list_OK\n", keys), Ok((EMPTY, ParsedComponent::EndOfFrame)) ); assert_eq!( ParsedComponent::parse(b"list_OK", keys), Err(NomErr::Incomplete(Needed::new(1))) ); } #[test] fn parse_error() { let keys = &mut ResponseFieldCache::new(); let no_command = b"ACK [5@0] {} unknown command \"foo\"\n"; let with_command = b"ACK [2@0] {random} Boolean (0/1) expected: foo\n"; assert_eq!( ParsedComponent::parse(no_command, keys), Ok(( EMPTY, ParsedComponent::Error(Error { code: 5, command_index: 0, current_command: None, message: Box::from("unknown command \"foo\""), }) )) ); assert_eq!( ParsedComponent::parse(with_command, keys), Ok(( EMPTY, ParsedComponent::Error(Error { code: 2, command_index: 0, current_command: Some(Box::from("random")), message: Box::from("Boolean (0/1) expected: foo"), }), )) ); } #[test] fn field() { let keys = &mut ResponseFieldCache::new(); assert_eq!( ParsedComponent::parse(b"foo: OK\n", keys), Ok(( EMPTY, ParsedComponent::Field { key: Arc::from("foo"), value: String::from("OK"), } )) ); assert_eq!( ParsedComponent::parse(b"foo_bar: hello world list_OK\n", keys), Ok(( EMPTY, ParsedComponent::Field { key: Arc::from("foo_bar"), value: String::from("hello world list_OK"), } )) ); assert!(ParsedComponent::parse(b"asdf: fooo", keys) .unwrap_err() .is_incomplete()); } #[test] fn binary_field() { let keys = &mut ResponseFieldCache::new(); assert_eq!( ParsedComponent::parse(b"binary: 6\nFOOBAR\n", keys), Ok((EMPTY, ParsedComponent::BinaryField { data_length: 6 })) ); assert_eq!( ParsedComponent::parse(b"binary: 6\nF", keys), Err(NomErr::Incomplete(Needed::new(5))) ); assert_eq!( ParsedComponent::parse(b"binary: 12\n", keys), Err(NomErr::Incomplete(Needed::new(12))) ); } } mpd_protocol-1.0.3/src/response/frame.rs000064400000000000000000000216371046102023000164240ustar 00000000000000//! A successful response to a command. use std::{fmt, iter::FusedIterator, slice, sync::Arc, vec}; use bytes::BytesMut; /// A successful response to a command. /// /// Consists of zero or more key-value pairs, where the keys are not unique, and optionally a /// single binary blob. #[derive(Clone, PartialEq, Eq)] pub struct Frame { pub(super) fields: FieldsContainer, pub(super) binary: Option, } impl Frame { /// Create an empty frame (0 key-value pairs). pub(crate) fn empty() -> Self { Self { fields: FieldsContainer(Vec::new()), binary: None, } } /// Get the number of key-value pairs in this response frame. pub fn fields_len(&self) -> usize { self.fields().count() } /// Returns `true` if the frame is entirely empty, i.e. contains 0 key-value pairs and no /// binary blob. pub fn is_empty(&self) -> bool { self.fields_len() == 0 && !self.has_binary() } /// Returns `true` if the frame contains a binary blob. /// /// If the binary blob has been removed using [`Frame::take_binary`], this will return `false`. pub fn has_binary(&self) -> bool { self.binary.is_some() } /// Returns an iterator over all key-value pairs in this frame, in the order they appear in the /// response. /// /// If keys have been removed using [`Frame::get`], they will not appear. pub fn fields(&self) -> Fields<'_> { Fields(self.fields.0.iter()) } /// Find the first key-value pair with the given key, and return a reference to its value. /// /// The key is case-sensitive. pub fn find(&self, key: K) -> Option<&str> where K: AsRef, { self.fields() .find_map(|(k, v)| if k == key.as_ref() { Some(v) } else { None }) } /// Returns a reference to the binary blob in this frame, if there is one. /// /// If the binary blob has been removed using [`Frame::take_binary`], this will return `None`. pub fn binary(&self) -> Option<&[u8]> { self.binary.as_deref() } /// Find the first key-value pair with the given key, and return its value. /// /// The key is case-sensitive. This removes it from the list of fields in this frame. pub fn get(&mut self, key: K) -> Option where K: AsRef, { self.fields.0.iter_mut().find_map(|field| { let k = match field.as_ref() { None => return None, Some((k, _)) => k, }; if k.as_ref() == key.as_ref() { field.take().map(|(_, v)| v) } else { None } }) } /// Get the binary blob contained in this frame, if present. /// /// This will remove it from the frame, future calls to this method will return `None`. pub fn take_binary(&mut self) -> Option { self.binary.take() } } impl fmt::Debug for Frame { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Frame(")?; let alternate = f.alternate(); let mut map = f.debug_map(); let mut map = map.entries(self.fields()); if let Some(b) = &self.binary { map = if alternate { map.entry(&"debug", &b) } else { map.entry(&"debug", &format!("<{} bytes>", b.len())) }; } map.finish()?; write!(f, ")") } } #[derive(Clone, PartialEq, Eq)] pub(super) struct FieldsContainer(Vec, String)>>); impl FieldsContainer { pub(super) fn push_field(&mut self, key: Arc, value: String) { self.0.push(Some((key, value))); } } /// Iterator returned by the [`Frame::fields`] method. #[derive(Debug)] pub struct Fields<'a>(slice::Iter<'a, Option<(Arc, String)>>); impl<'a> Iterator for Fields<'a> { type Item = (&'a str, &'a str); fn next(&mut self) -> Option { match self.0.next() { None => None, Some(None) => self.next(), Some(Some((k, v))) => Some((k.as_ref(), v.as_ref())), } } } impl DoubleEndedIterator for Fields<'_> { fn next_back(&mut self) -> Option { match self.0.next_back() { None => None, Some(None) => self.next_back(), Some(Some((k, v))) => Some((k.as_ref(), v.as_ref())), } } } impl FusedIterator for Fields<'_> {} impl<'a> IntoIterator for &'a Frame { type Item = (&'a str, &'a str); type IntoIter = Fields<'a>; fn into_iter(self) -> Self::IntoIter { self.fields() } } /// Iterator returned by the [`IntoIterator`] implementation on [`Frame`]. #[derive(Debug)] pub struct IntoIter { iter: vec::IntoIter, String)>>, binary: Option, } impl IntoIter { /// Get the binary blob contained in this frame, if present. /// /// This will remove it from the frame, future calls to this method will return `None`. pub fn take_binary(&mut self) -> Option { self.binary.take() } } impl Iterator for IntoIter { type Item = (Arc, String); fn next(&mut self) -> Option { match self.iter.next() { None => None, Some(None) => self.next(), Some(value) => value, } } } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option { match self.iter.next_back() { None => None, Some(None) => self.next_back(), Some(value) => value, } } } impl FusedIterator for IntoIter {} impl IntoIterator for Frame { type Item = (Arc, String); type IntoIter = IntoIter; fn into_iter(self) -> Self::IntoIter { IntoIter { iter: self.fields.0.into_iter(), binary: self.binary, } } } #[cfg(test)] mod tests { use super::*; #[test] fn length() { let frame = Frame::empty(); assert_eq!(frame.fields_len(), 0); let frame = Frame { fields: FieldsContainer(vec![ Some((Arc::from("hello"), String::from("world"))), Some((Arc::from("foo"), String::from("bar"))), ]), binary: Some(BytesMut::from("hello world")), }; assert_eq!(frame.fields_len(), 2); } #[test] fn binary() { let mut frame = Frame { fields: FieldsContainer(Vec::new()), binary: Some(BytesMut::from("hello world")), }; assert!(frame.has_binary()); assert!(!frame.is_empty()); assert_eq!(frame.take_binary(), Some(BytesMut::from("hello world"))); assert_eq!(frame.take_binary(), None); assert!(!frame.has_binary()); } #[test] fn accessors() { let mut frame = Frame { fields: FieldsContainer(vec![ Some((Arc::from("hello"), String::from("first value"))), Some((Arc::from("foo"), String::from("bar"))), Some((Arc::from("hello"), String::from("second value"))), ]), binary: None, }; assert_eq!(frame.find("hello"), Some("first value")); assert_eq!(frame.find("404"), None); assert_eq!(frame.find("HELLO"), None); // case-sensitive assert_eq!(frame.get("hello"), Some(String::from("first value"))); assert_eq!(frame.get("hello"), Some(String::from("second value"))); assert_eq!(frame.get("hello"), None); assert_eq!(frame.get("Foo"), None); // case-sensitive } #[test] fn iter() { let frame = Frame { fields: FieldsContainer(vec![ Some((Arc::from("hello"), String::from("first value"))), Some((Arc::from("foo"), String::from("bar"))), Some((Arc::from("hello"), String::from("second value"))), ]), binary: None, }; let mut iter = frame.fields(); assert_eq!(iter.next(), Some(("hello", "first value"))); assert_eq!(iter.next(), Some(("foo", "bar"))); assert_eq!(iter.next(), Some(("hello", "second value"))); assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } #[test] fn owned_iter() { let frame = Frame { fields: FieldsContainer(vec![ Some((Arc::from("hello"), String::from("first value"))), Some((Arc::from("foo"), String::from("bar"))), Some((Arc::from("hello"), String::from("second value"))), ]), binary: None, }; let mut iter = frame.into_iter(); assert_eq!(iter.next(), Some(("hello".into(), "first value".into()))); assert_eq!(iter.next(), Some(("foo".into(), "bar".into()))); assert_eq!(iter.next(), Some(("hello".into(), "second value".into()))); assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } } mpd_protocol-1.0.3/src/response/mod.rs000064400000000000000000000503101046102023000160770ustar 00000000000000//! Complete responses. pub mod frame; use std::{collections::HashSet, fmt, iter::FusedIterator, mem, slice, sync::Arc, vec}; use bytes::{Buf, BytesMut}; use tracing::trace; pub use self::frame::Frame; use crate::{parser::ParsedComponent, MpdProtocolError}; /// Response to a command, consisting of an arbitrary amount of [frames][Frame], which are /// responses to individual commands, and optionally a single [error][Error]. /// /// Since an error terminates a command list, there can only be one error in a response. #[derive(Clone, PartialEq, Eq)] pub struct Response { /// The successful responses. frames: Vec, /// The error, if one occurred. error: Option, } impl Response { /// Construct a new "empty" response. This is the simplest possible successful response, /// consisting of a single empty frame. pub(crate) fn empty() -> Self { Self { frames: vec![Frame::empty()], error: None, } } /// Returns `true` if the response contains an error. /// /// Even if this returns `true`, there may still be successful frames in the response when the /// response is to a command list. pub fn is_error(&self) -> bool { self.error.is_some() } /// Returns `true` if the response was entirely successful (i.e. no errors). pub fn is_success(&self) -> bool { !self.is_error() } /// Get the number of successful frames in the response. /// /// May be 0 if the response only consists of an error. pub fn successful_frames(&self) -> usize { self.frames.len() } /// Create an iterator over references to the frames in the response. /// /// This yields `Result`s, with successful frames becoming `Ok()`s and an error becoming a /// (final) `Err()`. pub fn frames(&self) -> FramesRef<'_> { FramesRef { frames: self.frames.iter(), error: self.error.as_ref(), } } /// Extract the first frame or error from the response. /// /// Any additional frames are discarded. This is useful for responses to single commands. pub fn into_single_frame(self) -> Result { // There is always at least one frame self.into_iter().next().unwrap() } pub(crate) fn field_count(&self) -> usize { self.frames.iter().map(Frame::fields_len).sum() } } impl fmt::Debug for Response { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Response(")?; f.debug_list() .entries(&self.frames) .entries(&self.error) .finish()?; write!(f, ")") } } /// A cache for field names used in responses. #[derive(Clone, Debug)] pub(crate) struct ResponseFieldCache(HashSet, ahash::RandomState>); impl ResponseFieldCache { /// Returns a new, empty cache. pub(crate) fn new() -> ResponseFieldCache { ResponseFieldCache(HashSet::default()) } /// Insert a field name into the cache or retrieve a reference to an already existing entry. pub(crate) fn insert(&mut self, key: &str) -> Arc { if let Some(k) = self.0.get(key) { Arc::clone(k) } else { let k = Arc::from(key); self.0.insert(Arc::clone(&k)); k } } } #[derive(Debug)] pub(crate) struct ResponseBuilder<'a> { field_cache: &'a mut ResponseFieldCache, state: ResponseState, } #[derive(Clone, Debug, PartialEq, Eq)] enum ResponseState { Initial, InProgress { current: Frame, }, ListInProgress { current: Frame, completed_frames: Vec, }, } impl<'a> ResponseBuilder<'a> { pub(crate) fn new(field_cache: &'a mut ResponseFieldCache) -> Self { Self { field_cache, state: ResponseState::Initial, } } pub(crate) fn parse( &mut self, src: &mut BytesMut, ) -> Result, MpdProtocolError> { while !src.is_empty() { let (remaining, component) = match ParsedComponent::parse(src, self.field_cache) { Err(e) if e.is_incomplete() => break, Err(_) => return Err(MpdProtocolError::InvalidMessage), Ok(p) => p, }; let msg_end = src.len() - remaining.len(); let mut msg = src.split_to(msg_end); match component { ParsedComponent::Field { key, value } => self.field(key, value), ParsedComponent::BinaryField { data_length } => { msg.advance(msg.len() - (data_length + 1)); msg.truncate(data_length); self.binary(msg); } ParsedComponent::Error(e) => return Ok(Some(self.error(e))), ParsedComponent::EndOfFrame => self.finish_frame(), ParsedComponent::EndOfResponse => return Ok(Some(self.finish())), } } Ok(None) } pub(crate) fn is_frame_in_progress(&self) -> bool { self.state != ResponseState::Initial } fn field(&mut self, key: Arc, value: String) { trace!(?key, ?value, "parsed field"); match &mut self.state { ResponseState::Initial => { let mut frame = Frame::empty(); frame.fields.push_field(key, value); self.state = ResponseState::InProgress { current: frame }; } ResponseState::InProgress { current } | ResponseState::ListInProgress { current, .. } => { current.fields.push_field(key, value); } } } fn binary(&mut self, binary: BytesMut) { trace!(length = binary.len(), "parsed binary field"); match &mut self.state { ResponseState::Initial => { let mut frame = Frame::empty(); frame.binary = Some(binary); self.state = ResponseState::InProgress { current: frame }; } ResponseState::InProgress { current } | ResponseState::ListInProgress { current, .. } => { current.binary = Some(binary); } } } fn finish_frame(&mut self) { trace!("finished command list frame"); let completed_frames = match mem::replace(&mut self.state, ResponseState::Initial) { ResponseState::Initial => vec![Frame::empty()], ResponseState::InProgress { current } => vec![current], ResponseState::ListInProgress { current, mut completed_frames, } => { completed_frames.push(current); completed_frames } }; self.state = ResponseState::ListInProgress { current: Frame::empty(), completed_frames, }; } fn finish(&mut self) -> Response { trace!("finished response"); match mem::replace(&mut self.state, ResponseState::Initial) { ResponseState::Initial => Response::empty(), ResponseState::InProgress { current } => Response { frames: vec![current], error: None, }, ResponseState::ListInProgress { completed_frames, .. } => Response { frames: completed_frames, error: None, }, } } fn error(&mut self, error: Error) -> Response { trace!(?error, "parsed error"); match mem::replace(&mut self.state, ResponseState::Initial) { ResponseState::Initial | ResponseState::InProgress { .. } => Response { frames: Vec::new(), error: Some(error), }, ResponseState::ListInProgress { completed_frames, .. } => Response { frames: completed_frames, error: Some(error), }, } } } /// 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<&'a Error>, } impl<'a> Iterator for FramesRef<'a> { type Item = Result<&'a Frame, &'a Error>; fn next(&mut self) -> Option { if let Some(frame) = self.frames.next() { Some(Ok(frame)) } else { self.error.take().map(Err) } } fn size_hint(&self) -> (usize, Option) { // .len() returns the number of successful 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<'a> DoubleEndedIterator for FramesRef<'a> { fn next_back(&mut self) -> Option { if let Some(e) = self.error.take() { Some(Err(e)) } else { self.frames.next_back().map(Ok) } } } 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, error: Option, } impl Iterator for Frames { type Item = Result; fn next(&mut self) -> Option { if let Some(f) = self.frames.next() { Some(Ok(f)) } else { self.error.take().map(Err) } } fn size_hint(&self) -> (usize, Option) { // .len() returns the number of successful 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 DoubleEndedIterator for Frames { fn next_back(&mut self) -> Option { if let Some(e) = self.error.take() { Some(Err(e)) } else { self.frames.next_back().map(Ok) } } } impl FusedIterator for Frames {} impl ExactSizeIterator for Frames {} impl IntoIterator for Response { type Item = Result; type IntoIter = Frames; fn into_iter(self) -> Self::IntoIter { Frames { frames: self.frames.into_iter(), error: self.error, } } } /// A response to a command indicating an error. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Error { /// Error code. See [the MPD source][mpd-error-def] for a list of of possible values. /// /// [mpd-error-def]: https://github.com/MusicPlayerDaemon/MPD/blob/master/src/protocol/Ack.hxx#L30 pub code: u64, /// Index of command in a command list that caused this error. 0 when not in a command list. pub command_index: u64, /// Command that returned the error, if applicable. pub current_command: Option>, /// Message describing the error. pub message: Box, } #[cfg(test)] mod test { use assert_matches::assert_matches; use super::*; fn frame(fields: [(&str, &str); N], binary: Option<&[u8]>) -> Frame { let mut out = Frame::empty(); for &(k, v) in &fields { out.fields.push_field(k.into(), v.into()); } out.binary = binary.map(BytesMut::from); out } #[test] fn owned_frames_iter() { let r = Response { frames: vec![Frame::empty(), Frame::empty(), Frame::empty()], error: 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 { frames: vec![Frame::empty(), Frame::empty(), Frame::empty()], error: 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()); } #[test] fn simple_response() { let mut io = BytesMut::from("foo: bar\nOK"); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_eq!(builder.state, ResponseState::Initial); // Consume fields assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::InProgress { current: frame([("foo", "bar")], None) } ); assert_eq!(io, "OK"); // No complete message, do not consume buffer assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::InProgress { current: frame([("foo", "bar")], None) } ); assert_eq!(io, "OK"); io.extend_from_slice(b"\n"); // Response now complete assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![frame([("foo", "bar")], None)], error: None }) ); assert_eq!(builder.state, ResponseState::Initial); assert_eq!(io, ""); } #[test] fn response_with_binary() { let mut io = BytesMut::from("foo: bar\nbinary: 6\nOK\n"); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::InProgress { current: frame([("foo", "bar")], None) } ); assert_eq!(io, "binary: 6\nOK\n"); io.extend_from_slice(b"OK\n\n"); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::InProgress { current: frame([("foo", "bar")], Some(b"OK\nOK\n")), } ); assert_eq!(io, ""); io.extend_from_slice(b"OK\n"); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![frame([("foo", "bar")], Some(b"OK\nOK\n"))], error: None, }) ); assert_eq!(builder.state, ResponseState::Initial); } #[test] fn empty_response() { let mut io = BytesMut::from("OK"); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!(builder.state, ResponseState::Initial); io.extend_from_slice(b"\n"); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![Frame::empty()], error: None, }) ); } #[test] fn error() { let mut io = BytesMut::from("ACK [5@0] {} unknown command \"foo\""); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!(builder.state, ResponseState::Initial); io.extend_from_slice(b"\n"); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![], error: Some(Error { code: 5, command_index: 0, current_command: None, message: Box::from("unknown command \"foo\""), }), }) ); assert_eq!(builder.state, ResponseState::Initial); } #[test] fn multiple_messages() { let mut io = BytesMut::from("foo: bar\nOK\nhello: world\nOK\n"); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![frame([("foo", "bar")], None)], error: None }) ); assert_eq!(io, "hello: world\nOK\n"); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![frame([("hello", "world")], None)], error: None }) ); assert_eq!(io, ""); } #[test] fn command_list() { let mut io = BytesMut::from("foo: bar\n"); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::InProgress { current: frame([("foo", "bar")], None) } ); io.extend_from_slice(b"list_OK\n"); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::ListInProgress { current: Frame::empty(), completed_frames: vec![frame([("foo", "bar")], None)], } ); io.extend_from_slice(b"list_OK\n"); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::ListInProgress { current: Frame::empty(), completed_frames: vec![frame([("foo", "bar")], None), Frame::empty()], } ); io.extend_from_slice(b"OK\n"); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![frame([("foo", "bar")], None), Frame::empty()], error: None }) ); assert_eq!(builder.state, ResponseState::Initial); } #[test] fn command_list_error() { let mut io = BytesMut::from("list_OK\n"); let mut field_cache = ResponseFieldCache::new(); let mut builder = ResponseBuilder::new(&mut field_cache); assert_matches!(builder.parse(&mut io), Ok(None)); assert_eq!( builder.state, ResponseState::ListInProgress { current: Frame::empty(), completed_frames: vec![Frame::empty()], } ); io.extend_from_slice(b"ACK [5@1] {} unknown command \"foo\"\n"); assert_eq!( builder.parse(&mut io).unwrap(), Some(Response { frames: vec![Frame::empty()], error: Some(Error { code: 5, command_index: 1, current_command: None, message: Box::from("unknown command \"foo\""), }), }) ); assert_eq!(builder.state, ResponseState::Initial); } #[test] fn key_interning() { let mut io = BytesMut::from("foo: bar\nfoo: baz\nOK\n"); let mut field_cache = ResponseFieldCache::new(); let mut resp = ResponseBuilder::new(&mut field_cache) .parse(&mut io) .expect("incomplete") .expect("invalid"); let mut fields = resp.frames.pop().unwrap().into_iter(); let (a, _) = fields.next().unwrap(); let (b, _) = fields.next().unwrap(); assert!(Arc::ptr_eq(&a, &b)); } }