pircolate 0.2.1

Parser and interface for IRCv3 messages.
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! The command module contains everything needed to perform strongly typed access
//! to commands associated with a message.

use std::ops::Range;
use std::slice::Iter;

/// An implementation of Iterator that iterates over the arguments of a `Message`.
#[derive(Clone)]
pub struct ArgumentIter<'a> {
    source: &'a str,
    iter: Iter<'a, Range<usize>>,
}

impl<'a> ArgumentIter<'a> {
    // This is intended for internal usage and thus hidden.
    #[doc(hidden)]
    pub fn new(source: &'a str, iter: Iter<'a, Range<usize>>) -> ArgumentIter<'a> {
        ArgumentIter {
            source: source,
            iter: iter,
        }
    }
}

impl<'a> Iterator for ArgumentIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|range| &self.source[range.clone()])
    }
}

impl<'a> DoubleEndedIterator for ArgumentIter<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter
            .next_back()
            .map(|range| &self.source[range.clone()])
    }
}

/// The `Command` trait is a trait that's implemented by types wishing to provide command
/// parsing capability for usage with the `Message::command` method.
pub trait Command<'a> {
    /// Provides the name of the command to be matched. Examples include `PRIVMSG` or `PING`.
    fn name() -> &'static str;

    /// This method takes in an iterator of arguments associated with a `Message` and attempts
    /// to parse the arguments into a matched `Command`.  If no match is found, None is returned.
    fn parse(arguments: ArgumentIter<'a>) -> Option<Self>
    where
        Self: Sized;

    /// A default implementation that takes in the given command name and arguments and attempts to match
    /// the command and parse the arguments into a strongly typed representation. If there is no match
    /// or the parse fails, it returns `None`.
    fn try_match(command: &str, arguments: ArgumentIter<'a>) -> Option<Self>
    where
        Self: Sized,
    {
        if command == Self::name() {
            Self::parse(arguments)
        } else {
            None
        }
    }
}

/// A macro for simplifying the process of matching commands.
///
/// # Examples
///
/// Match all PING commands.
///
/// ```
/// # #[macro_use] extern crate pircolate;
/// #
/// # use pircolate::message;
/// # use pircolate::command::Ping;
/// #
/// # fn main() {
/// #   let msg = message::Message::try_from("TEST bob :hello, world!".to_owned()).unwrap();
/// command_match! {
///     msg => {
///         Ping(source) => println!("{}", source),
///         _ => ()
///     }
/// };
/// # }
/// ```
#[macro_export]
macro_rules! command_match {
    (@message=$message:expr => $command:pat => $body:expr) => {{
        let $command = $message;
        $body
    }};

    (@message=$message:expr => $command:pat => $body:expr, $($rest:tt)*) => {
        match $message.command() {
            Some($command) => $body,
            _ => command_match!(@message=$message => $($rest)*)
        }
    };

    ($message:expr => { $($rest:tt)* }) => {{
        let message = $message;
        command_match!(@message=message => $($rest)*)
    }};
}

/// A macro for creating implementations of basic commands with up to four
/// &str arguments.
///
/// # Examples
///
/// Simple command "TEST" with two &str arguments.
///
/// ```
/// # #[macro_use] extern crate pircolate;
/// #
/// # use pircolate::message;
/// # use pircolate::command::Ping;
/// #
/// command! {
///   /// Some command!
///   ("TEST" => Test(user, message))
/// }
/// #
/// # fn main() {
/// #   let msg = message::Message::try_from("TEST bob :hello, world!".to_owned()).unwrap();
/// if let Some(Test(user, message)) = msg.command::<Test>() {
///     println!("<{}> {}", user, message);
/// }
/// # }
/// ```
#[macro_export]
macro_rules! command {
    ($(#[$meta:meta])* ($command:expr => $command_name:ident())) => {
        $(#[$meta])*
        pub struct $command_name;

        impl<'a> $crate::command::Command<'a> for $command_name {
            fn name() -> &'static str {
                $command
            }

            fn parse(_: $crate::command::ArgumentIter<'a>) -> Option<$command_name> {
                Some($command_name)
            }
        }
    };

    ($(#[$meta:meta])* ($command:expr => $command_name:ident($($name:ident),+))) => {
        $(#[$meta])*

        pub struct $command_name<'a>($(pub expand_param!($name)),+);

        impl<'a> $crate::command::Command<'a> for $command_name<'a> {
            fn name() -> &'static str {
                $command
            }

            fn parse(mut arguments: $crate::command::ArgumentIter<'a>) -> Option<$command_name> {
                $(
                    let $name = match arguments.next() {
                        Some(value) => value,
                        None => return None
                    };
                )+

                Some($command_name($($name),*))
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! expand_param {
    ($i:ident) =>  { &'a str };
}

command! { 
    /// Represents a PING command.  The first element is the host.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate pircolate;
    /// # use pircolate::message;
    /// # use pircolate::command::Ping;
    /// #
    /// # fn main() {
    /// # let msg = message::server::ping("test.host.com").unwrap();
    /// if let Some(Ping(host)) = msg.command::<Ping>() {
    ///     println!("PING from {}", host);
    /// }
    /// # }
    /// ```
    ("PING" => Ping(host)) 
}

command! {
    /// Represents a PONG command. The first element is the host.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate pircolate;
    /// # use pircolate::message;
    /// # use pircolate::command::Pong;
    /// #
    /// # fn main() {
    /// # let msg = message::client::pong("test.host.com").unwrap();
    /// if let Some(Pong(host)) = msg.command::<Pong>() {
    ///    println!("PONG from {}.", host);
    /// }
    /// # }
    /// ```
    ("PONG" => Pong(host))
}

command! {
    /// Represents a PRIVMSG command.  The first element is the target of the message and
    /// the second eleement is the message.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate pircolate;
    /// # use pircolate::message;
    /// # use pircolate::command::PrivMsg;
    /// #
    /// # fn main() {
    /// # let msg = message::client::priv_msg("memelord", "memes are great").unwrap();
    /// if let Some(PrivMsg(user, message)) = msg.command::<PrivMsg>() {
    ///     println!("<{}> {}.", user, message);
    /// }
    /// # }
    /// ```
    ("PRIVMSG" => PrivMsg(target, message))
}

// command! {
//     ("JOIN" => Join(channel))
// }

// command! {
//     ("PART" => Part(channel))
// }

command! { 
    /// Represents a WELCOME numeric. The first element is the unsername and the second element is the welcome message.
    ("001" => Welcome(user, message))
}

command! {
    /// Represents a YOURHOST numeric. The first element is the unsername and the second element is the yourhost message.
    ("002" => YourHost(user, message))
}

command!{
    /// Represents a CREATED numeric. The first element is the unsername and the second element is the created message.
    ("003" => Created(user, message))
}

command!{
    /// Represents a MYINFO numeric. The first element is the username and the second element is the server info message.
    ("004" => ServerInfo(user, message))
}

#[derive(PartialEq, Debug)]
pub enum NamesReplyChannelType {
    Secret,
    Private,
    Other,
}

pub struct NamesReply<'a>(pub NamesReplyChannelType, pub &'a str, pub Vec<&'a str>);

impl<'a> Command<'a> for NamesReply<'a> {
    fn name() -> &'static str {
        "353"
    }

    fn parse(arguments: ArgumentIter<'a>) -> Option<NamesReply<'a>> {
        // NOTE: Since the first parameter is optional, it's just easier to extract
        // components in reverse.
        let mut arguments = arguments.rev();

        let names = match arguments.next() {
            Some(names) => names.split_whitespace(),
            None => return None,
        };

        let channel = match arguments.next() {
            Some(channel) => channel,
            None => return None,
        };

        let channel_type = match arguments.next() {
            Some(channel_type) => {
                match channel_type {
                    "@" => NamesReplyChannelType::Secret,
                    "*" => NamesReplyChannelType::Private,
                    _ => NamesReplyChannelType::Other,
                }
            }
            None => NamesReplyChannelType::Other,
        };

        Some(NamesReply(channel_type, channel, names.collect()))
    }
}

pub struct EndNamesReply<'a>(pub &'a str, pub &'a str);

impl<'a> Command<'a> for EndNamesReply<'a> {
    fn name() -> &'static str {
        "366"
    }

    fn parse(arguments: ArgumentIter<'a>) -> Option<EndNamesReply<'a>> {
        // NOTE: Some servers are bad and include non-standard args at the start.
        // So the parameters are extracted in reverse to compensate.
        let mut arguments = arguments.rev();

        let message = match arguments.next() {
            Some(message) => message,
            None => return None,
        };

        let channel = match arguments.next() {
            Some(channel) => channel,
            None => return None,
        };

        Some(EndNamesReply(channel, message))
    }
}

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

    #[test]
    fn test_ping_command() {
        let message = server::ping("test.host.com").unwrap();
        let Ping(host) = message.command::<Ping>().unwrap();

        assert_eq!("test.host.com", host);
    }

    #[test]
    fn test_pong_command() {
        let message = client::pong("test.host.com").unwrap();
        let Pong(host) = message.command::<Pong>().unwrap();

        assert_eq!("test.host.com", host);
    }

    #[test]
    fn test_privmsg_command() {
        let message = client::priv_msg("#channel", "This is a message!").unwrap();
        let PrivMsg(target, message) = message.command::<PrivMsg>().unwrap();

        assert_eq!("#channel", target);
        assert_eq!("This is a message!", message);
    }

    #[test]
    fn test_welcome_command() {
        let msg = server::welcome("robots", "our overlords").unwrap();
        let Welcome(username, message) = msg.command::<Welcome>().unwrap();

        assert_eq!("robots", username);
        assert_eq!("our overlords", message);
    }

    #[test]
    fn test_your_host_command() {
        let msg = server::your_host("robots", "our overlords").unwrap();
        let YourHost(username, message) = msg.command::<YourHost>().unwrap();

        assert_eq!("robots", username);
        assert_eq!("our overlords", message);
    }

    #[test]
    fn test_created_command() {
        let msg = server::created("robots", "our overlords").unwrap();
        let Created(username, message) = msg.command::<Created>().unwrap();

        assert_eq!("robots", username);
        assert_eq!("our overlords", message);
    }

    #[test]
    fn test_server_info_command() {
        let msg = server::server_info("robots", "our overlords").unwrap();
        let ServerInfo(username, message) = msg.command::<ServerInfo>().unwrap();

        assert_eq!("robots", username);
        assert_eq!("our overlords", message);
    }

    #[test]
    fn test_names_reply_command() {
        let msg: Message = "353 = #test :robot1 robot2 robot3".parse().unwrap();
        let NamesReply(channel_type, channel, users) = msg.command::<NamesReply>().unwrap();

        let expected_users = vec!["robot1", "robot2", "robot3"];

        assert_eq!(NamesReplyChannelType::Other, channel_type);
        assert_eq!("#test", channel);
        assert_eq!(expected_users, users);
    }

    #[test]
    fn test_command_match_with_single_branchj() {
        let message = client::priv_msg("#channel", "This is a message!").unwrap();

        command_match! {
            message => {
                PrivMsg(target, message) => {
                    assert_eq!(target, "#channel");
                    assert_eq!(message, "This is a message!");
                },
                _ => {
                    panic!("Command was not matched.")
                }
            }
        }
    }

    #[test]
    fn test_command_match_with_multiple_branches() {
        let message = client::priv_msg("#channel", "This is a message!").unwrap();

        command_match! {
            message => {
                Ping(_) => panic!("Command was inadvertently matched."),
                Pong(_) => panic!("Command was inadvertently matched."),
                Welcome(_, _) => panic!("Command was inadvertently matched."),
                PrivMsg(target, message) => {
                    assert_eq!(target, "#channel");
                    assert_eq!(message, "This is a message!");
                },
                _ => {
                    panic!("Command was not matched.")
                }
            }
        }
    }
}