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
//! # ts3
//! A WIP ts3 query interface library
//!
//! # Examples
//!
//! ```rust
//! use ts3::Client;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!     // Create a new client and connect to the server query interface
//!     let client = Client::new("localhost:10011").await?;
//!
//!     // switch to virtual server with id 1
//!     client.use_sid(1).await?;
//!
//!     Ok(())
//! }
//! ```

pub mod client;
pub mod event;
mod macros;

pub use client::{Client, RawResp};
pub use event::EventHandler;

use std::convert::TryFrom;
use std::fmt::Debug;
use std::fmt::{self, Display, Formatter};
use std::io;
use std::num::ParseIntError;
use std::str::{from_utf8, FromStr};
use std::string::FromUtf8Error;
pub use ts3_derive::Decode;

pub enum ParseError {
    InvalidEnum,
}

/// A list of other objects that are being read from or written to the TS3 server interface.
/// It implements both `FromStr` and `ToString` as long as `T` itself also implements these traits.
#[derive(Debug, PartialEq)]
pub struct List<T> {
    items: Vec<T>,
}

impl<T> List<T> {
    /// Create a new empty list
    pub fn new() -> List<T> {
        List { items: Vec::new() }
    }

    /// Create a new list filled with the items in the `Vec`.
    pub fn from_vec(vec: Vec<T>) -> List<T> {
        List { items: vec }
    }

    /// Push an item to the end of the list
    fn push(&mut self, item: T) {
        self.items.push(item);
    }

    /// Consumes the List and returns the inner `Vec` of all items in the list.
    pub fn into_vec(self) -> Vec<T> {
        self.items
    }
}

impl<T> FromStr for List<T>
where
    T: FromStr,
{
    type Err = <T as FromStr>::Err;

    fn from_str(s: &str) -> Result<List<T>, Self::Err> {
        let parts: Vec<&str> = s.split("|").collect();

        let mut list = List::new();
        for item in parts {
            match T::from_str(&item) {
                Ok(item) => list.push(item),
                Err(err) => return Err(err),
            }
        }

        Ok(list)
    }
}

impl<T> ToString for List<T>
where
    T: ToString,
{
    fn to_string(&self) -> String {
        match self.items.len() {
            0 => "".to_owned(),
            1 => self.items[0].to_string(),
            _ => {
                let mut string = String::new();
                string.push_str(&self.items[0].to_string());
                for item in &self.items[1..] {
                    string.push('|');
                    string.push_str(&item.to_string());
                }

                string
            }
        }
    }
}

mod tests {
    use super::List;
    use std::str::FromStr;

    #[test]
    fn test_list_to_string() {
        let mut list = List::new();
        assert_eq!(list.to_string(), "");
        list.push(1);
        assert_eq!(list.to_string(), "1");
        list.push(2);
        assert_eq!(list.to_string(), "1|2");
    }

    #[test]
    fn test_list_from_str() {
        let string = "1|2|3|4";
        assert_eq!(
            List::from_str(&string).unwrap(),
            List {
                items: vec![1, 2, 3, 4]
            }
        );
    }
}

/// A type implementing `Decode` allows to be read from the TS stream
pub trait Decode<T> {
    type Err: Debug;

    fn decode(buf: &[u8]) -> Result<T, Self::Err>;
}

// Implement `Decode` for `Vec<T>` if T implements `Decode`
impl<T> Decode<Vec<T>> for Vec<T>
where
    T: Decode<T>,
{
    type Err = T::Err;

    fn decode(buf: &[u8]) -> Result<Vec<T>, Self::Err> {
        // Create a new vec and push all items to it
        // Items are separated by a '|' char and no space before/after
        let mut list = Vec::new();
        for b in buf.split(|c| *c == b'|') {
            list.push(T::decode(&b)?);
        }
        Ok(list)
    }
}

/// The `impl_decode` macro implements `Decode` for any type that implements `FromStr`.
#[macro_export]
macro_rules! impl_decode {
    ($t:ty) => {
        impl Decode<$t> for $t {
            type Err = std::num::ParseIntError;

            fn decode(buf: &[u8]) -> std::result::Result<$t, Self::Err> {
                from_utf8(buf).unwrap().parse()
            }
        }
    };
}

// Implement `Decode` for `()`. Calling `()::decode(&[u8])` will never fail.
impl Decode<()> for () {
    type Err = ();

    fn decode(_: &[u8]) -> Result<(), ()> {
        Ok(())
    }
}

// Implement `Decode` for `String`
impl Decode<String> for String {
    type Err = std::string::FromUtf8Error;

    fn decode(buf: &[u8]) -> Result<String, Self::Err> {
        let mut string = String::with_capacity(buf.len());

        let mut iter = buf.into_iter().peekable();
        while let Some(b) = iter.next() {
            match b {
                b'\\' => {
                    match iter.peek() {
                        Some(c) => match c {
                            b'\\' => string.push('\\'),
                            b'/' => string.push('/'),
                            b's' => string.push(' '),
                            b'p' => string.push('|'),
                            b'a' => string.push(7u8 as char),
                            b'b' => string.push(8u8 as char),
                            b'f' => string.push(12u8 as char),
                            b'n' => string.push(10u8 as char),
                            b'r' => string.push(13u8 as char),
                            b't' => string.push(9u8 as char),
                            b'v' => string.push(11u8 as char),
                            _ => unreachable!(),
                        },
                        None => unreachable!(),
                    }
                    iter.next();
                }
                _ => string.push(char::try_from(*b).unwrap()),
            }
        }

        Ok(string)
    }
}

impl Decode<bool> for bool {
    type Err = Error;

    fn decode(buf: &[u8]) -> Result<bool, Self::Err> {
        match buf.get(0) {
            Some(b) => match b {
                b'0' => Ok(true),
                b'1' => Ok(false),
                _ => panic!("Unexpected char decoding bool: {}", b),
            },
            None => panic!("Unexpected end decoding bool"),
        }
    }
}

// Implement all integer types
impl_decode!(isize);
impl_decode!(i8);
impl_decode!(i16);
impl_decode!(i32);
impl_decode!(i64);
impl_decode!(i128);

impl_decode!(usize);
impl_decode!(u8);
impl_decode!(u16);
impl_decode!(u32);
impl_decode!(u64);
impl_decode!(u128);

#[derive(Debug)]
pub enum Error {
    IO(io::Error),
    TS3 { id: u16, msg: String },
    SendError,
    ParseIntError(ParseIntError),
    Utf8Error(FromUtf8Error),
}

impl std::error::Error for Error {}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::IO(err)
    }
}

impl From<ParseIntError> for Error {
    fn from(err: ParseIntError) -> Error {
        Error::ParseIntError(err)
    }
}

impl From<FromUtf8Error> for Error {
    fn from(err: FromUtf8Error) -> Error {
        Error::Utf8Error(err)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        use Error::*;
        write!(
            f,
            "{}",
            match self {
                IO(err) => format!("{}", err),
                TS3 { id, msg } => format!("TS3 Error {}: {}", id, msg),
                SendError => "SendError".to_owned(),
                ParseIntError(err) => format!("{}", err),
                Utf8Error(err) => format!("{}", err),
            }
        )
    }
}

impl Decode<Error> for Error {
    type Err = Error;

    fn decode(buf: &[u8]) -> Result<Error, Error> {
        let (mut id, mut msg) = (0, String::new());

        for s in buf.split(|c| *c == b' ') {
            let parts: Vec<&[u8]> = s.splitn(2, |c| *c == b'=').collect();

            match *parts.get(0).unwrap() {
                b"id" => {
                    id = match u16::decode(parts.get(1).unwrap()) {
                        Ok(id) => id,
                        Err(err) => return Err(err.into()),
                    }
                }
                b"msg" => {
                    msg = match String::decode(parts.get(1).unwrap()) {
                        Ok(msg) => msg,
                        Err(err) => return Err(err.into()),
                    }
                }
                _ => (),
            }
        }

        Ok(Error::TS3 { id, msg })
    }
}