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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
use std::result;
use std::error;

use super::escaping::{escape, unescape};

pub const IRC_TRAILING: char = ':';
pub const IRC_TAG_START: char = '@';
pub const IRC_PREFIX_START: char = ':';
pub const IRC_TAG_VALUE_SEP: char = '=';
pub const IRC_TAG_VENDOR_SEP: char = '/';
pub const IRC_TAG_END_SEP: char = ';';
pub const IRC_PREFIX_USER_SEP: char = '!';
pub const IRC_PREFIX_HOST_SEP: char = '@';

pub type Result<T> = result::Result<T, ParseError>;

// CHECK FUNCTIONS
fn check_valid_key(ch: char) -> bool { ch.is_alphabetic() || ch.is_digit(10) || ch == '-' }

// CHAR HELPER FUNCTIONS
fn get_char_at(s: &str, ind: usize) -> char {
	s[ind..].chars().next().unwrap()
}

pub struct ParseError {
	message: &'static str,
	kind: ParseErrorKind,
}

impl ParseError {
	fn new_unexpected(msg: &'static str, ch: char) -> ParseError {
		ParseError {
			message: msg,
			kind: ParseErrorKind::Unexpected(ch)
		}
	}

	fn new_bad_syntax(msg: &'static str) -> ParseError {
		ParseError {
			message: msg,
			kind: ParseErrorKind::BadSyntax
		}
	}

	fn new_missing_command(msg: &'static str) -> ParseError {
		ParseError {
			message: msg,
			kind: ParseErrorKind::BadSyntax,
		}
	}
}

impl error::Error for ParseError {

}

impl Display for ParseError {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		f.write_str(self.message)?;
		f.write_str("; ")?;

		match &self.kind {
			ParseErrorKind::Unexpected(ch) => write!(f, "unexpected char '{}'", ch),
			ParseErrorKind::BadSyntax => f.write_str("bad syntax"),
			ParseErrorKind::MissingCommand => f.write_str("missing command"),
		}
	}
}

impl Debug for ParseError {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		<ParseError as Display>::fmt(self, f)
	}
}

pub enum ParseErrorKind {
	Unexpected(char),
	BadSyntax,
	MissingCommand,
}

/// A single IRC3 tag.
///
/// The [`vendor`] field of `Tag` is used to namespace tags.
/// This allows to differentiate between two equally named tags.
#[derive(PartialEq)]
pub struct Tag {
	key: String,
	vendor: Option<String>,
	value:  Option<String>,
}

impl Tag {
	pub fn new(key: &str, value: Option<&str>) -> Tag {
		Tag::new_with_vendor(key, value, None)
	}

	pub fn new_with_vendor(key: &str, value: Option<&str>, vendor: Option<&str>) -> Tag {
		Tag {
			key: String::from(key),
			vendor: match vendor {
				Some(s) => Some(String::from(s)),
				None => None,
			},
			value: match value {
				Some(s) => Some(String::from(s)),
				None => None,
			}
		}
	}

	pub fn key(&self) -> &str {
		&self.key
	}

	pub fn vendor(&self) -> Option<&str> {
		match &self.vendor {
			Some(s) => Some(s),
			None => None,
		}
	}

	pub fn value(&self) -> Option<&str> {
		match &self.value {
			Some(s) => Some(s),
			None => None,
		}
	}

	pub fn set_key(&mut self, key: &str) {
		self.key = String::from(key);
	}

	pub fn set_vendor(&mut self, vendor: &str) {
		self.vendor = Some(String::from(vendor));
	}

	pub fn set_value(&mut self, value: &str) {
		self.value = Some(String::from(value));
	}
}

impl Display for Tag {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		// turn the tag into the format used in the IRC 3.2 spec
		if let Some(ven) = &self.vendor {
			f.write_str(ven)?;
			f.write_str("/")?;
		}

		f.write_str(&self.key)?;

		if let Some(value) = &self.value {
			f.write_str("=")?;
			f.write_str(&escape(value))?;
		}

		Ok(())
	}
}

impl Debug for Tag {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		f.write_str(&self.key)?;
		if let Some(val) = &self.value { write!(f, "=\"{}\"", val)?; }
		if let Some(ven) = &self.vendor { write!(f, " ({})", ven)?; }

		Ok(())
	}
}

/// A prefix of an IRC message.
#[derive(PartialEq)]
pub struct Prefix {
	origin: String,
	user: Option<String>,
	host: Option<String>,
}

impl Prefix {
	pub fn new(origin: &str, user: Option<&str>, host: Option<&str>) -> Prefix {
		Prefix {
			origin: String::from(origin),
			user: match user {
				Some(s) => Some(String::from(s)),
				None => None,
			},
			host: match host {
				Some(s) => Some(String::from(s)),
				None => None,
			}
		}
	}

	pub fn parse(pre: &str) -> Prefix {
		Prefix {
			origin: match pre.find(IRC_PREFIX_USER_SEP) {
				Some(i) => String::from(&pre[..i]),
				None => match pre.find(IRC_PREFIX_HOST_SEP) {
					Some(i) => String::from(&pre[..i]),
					None => String::from(pre),
				}
			},
			user: match pre.find(IRC_PREFIX_USER_SEP) {
				Some(i) => match pre.find(IRC_PREFIX_HOST_SEP) {
					Some(j) => Some(String::from(&pre[(i+IRC_PREFIX_USER_SEP.len_utf8())..j])),
					None => Some(String::from(&pre[(i+IRC_PREFIX_USER_SEP.len_utf8())..])),
				},
				None => None,
			},
			host: match pre.find(IRC_PREFIX_HOST_SEP) {
				Some(i) => Some(String::from(&pre[(i+IRC_PREFIX_HOST_SEP.len_utf8())..])),
				None => None,
			}
		}
	}

	pub fn origin(&self) -> &str {
		&self.origin
	}

	pub fn user(&self) -> Option<&str> {
		match &self.user {
			Some(s) => Some(s),
			None => None,
		}
	}

	pub fn host(&self) -> Option<&str> {
		match &self.host {
			Some(s) => Some(s),
			None => None,
		}
	}

	pub fn set_origin(&mut self, s: &str) {
		self.origin = String::from(s);
	}

	pub fn set_user(&mut self, s: &str) {
		self.user = Some(String::from(s));
	}

	pub fn set_host(&mut self, s: &str) {
		self.host = Some(String::from(s));
	}
}

impl Display for Prefix {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		f.write_str(&self.origin)?;
		
		if let Some(user) = &self.user {
			f.write_str("!")?;
			f.write_str(user)?;
		}

		if let Some(host) = &self.host {
			f.write_str("@")?;
			f.write_str(host)?;
		}

		Ok(())
	}
}

impl Debug for Prefix {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		f.write_str("{")?;
		write!(f, "origin=\"{}\"", self.origin)?;
		if let Some(user) = &self.user {
			write!(f, ", user=\"{}\"", user)?;
		}
		if let Some(host) = &self.host {
			write!(f, ", host=\"{}\"", host)?;
		}
		f.write_str("}")
	}
}

/// An iterator over the tags of a raw IRC message.
pub struct TagsIter<'a> {
	cursor: usize,
	inner: &'a str,
}

impl<'a> TagsIter<'a> {
	pub fn new(tags: &'a str) -> TagsIter<'a> {
		TagsIter {
			cursor: 0,
			inner: tags,
		}
	}
}

impl<'a> Iterator for TagsIter<'a> {
	type Item = Result<Tag>;

	fn next(&mut self) -> Option<Self::Item> {
		if self.cursor >= self.inner.len() {
			return None
		}

		// start with a vendor
		let mut vendor: Option<String> = None;

		// reading metadata
		let mut has_value = false;

		// read key first
		let mut start = self.cursor;
		while self.cursor < self.inner.len() {
			let ch = get_char_at(self.inner, self.cursor);
			// check if this is a vendor string
			if ch == IRC_TAG_VENDOR_SEP {
				// set vendor string if it does not exist
				if vendor.is_none() {
					vendor = Some(String::from(&self.inner[start..self.cursor]));
					start = self.cursor + ch.len_utf8();
				} else {
					return Some(Err(ParseError::new_bad_syntax(
					"tags may only have one vendor")));
				}

				self.cursor += ch.len_utf8();
				continue;
			}

			// check if we need to break from reading the tag
			if ch == IRC_TAG_VALUE_SEP {
				has_value = true;
				break;
			}

			// check if the tag ends
			if ch == IRC_TAG_END_SEP {
				break;
			}

			// check if the character conforms to the standard
			if !check_valid_key(ch) {
				return Some(Err(ParseError::new_unexpected(
				"tags can only contain letters, digits or hyphens", ch)));
			}

			self.cursor += ch.len_utf8();
		}

		// write key range into a tag
		let tag = Tag{
			key: String::from(&self.inner[start..self.cursor]),
			vendor: vendor,
			value: if has_value {
				// skip over '='
				self.cursor += IRC_TAG_VALUE_SEP.len_utf8();

				// read value
				let start = self.cursor;
				while self.cursor < self.inner.len() {
					let ch = get_char_at(self.inner, self.cursor);

					if ch == IRC_TAG_END_SEP {
						break;
					}

					self.cursor += ch.len_utf8();
				}

				// clone tag
				Some(unescape(&self.inner[start..self.cursor]))
				// the escaping of values will occur during accesses to Tag
			} else {
				None
			},
		};

		// skip over semicolon
		self.cursor += IRC_TAG_END_SEP.len_utf8();

		Some(Ok(tag))
	}
}

/// Used to iterate over the contents of a raw IRC message's params
pub struct ParamsIter<'a> {
	cursor: usize,
	inner: &'a str,
}

impl<'a> ParamsIter<'a> {
	pub fn new(params: &'a str) -> ParamsIter<'a> {
		ParamsIter {
			cursor: 0,
			inner: params,
		}
	}
}

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

	fn next(&mut self) -> Option<Self::Item> {
		if self.cursor >= self.inner.len() {
			return None;
		}

		// reading metadata
		let mut trailing = false;

		let mut start = self.cursor;
		let mut offset: usize = 0;
		while self.cursor < self.inner.len() {
			let ch = get_char_at(self.inner, self.cursor);
			if ch.is_whitespace() && !trailing {
				offset += ch.len_utf8();
				// consume whitespace
				while self.cursor+offset < self.inner.len() {
					let ch = get_char_at(self.inner, self.cursor+offset);
					if !ch.is_whitespace() {
						break;
					}

					offset += ch.len_utf8();
				}

				break;
			}

			if start == self.cursor {
				// start of the parameter,
				if ch == IRC_TRAILING {
					trailing = true;
					start += ch.len_utf8();
				}
			}

			self.cursor += ch.len_utf8();
		}

		// return a result
		let slice = &self.inner[start..self.cursor];
		self.cursor += offset;
		Some(slice)
	}
}

/// A full IRC message that can be reprocessed back into its encoded form.
///
/// An IRC message can be parsed from a raw message, or it can built using
/// the [`new`] constructor and the builder functions [`with_tag`],
/// [`with_tag_vendor`], [`with_prefix`] and [`with_param`].
///
/// # Examples
/// ```rust
/// use irc3::Message;
///
/// fn main() {
/// 	const MSG: &'static str = ":dan!d@localhost PRIVMSG * :Hey guys, what's up?";
///
/// 	let built_message = Message::new("PRIVMSG")
/// 		.with_prefix("dan", Some("d"), Some("localhost"))
/// 		.with_param("*")
/// 		.with_param("Hey guys, what's up?");
/// 	
/// 	let parsed_message = Message::parse(MSG).unwrap();
///
/// 	assert!(built_message == parsed_message);
/// }
/// ```
#[derive(Debug, PartialEq)]
pub struct Message {
	tags: Vec<Tag>,
	prefix: Option<Prefix>,
	command: String,
	params: Vec<String>,
}

impl Message {
	pub fn new(command: &str) -> Message {
		Message {
			tags: Vec::new(),
			prefix: None,
			command: String::from(command),
			params: Vec::new(),
		}
	}

	pub fn parse<S: AsRef<str> + ?Sized>(s: &S) -> Result<Message> {
		let mut line = s.as_ref();

		if line.is_empty() {
			return Err(ParseError::new_missing_command("missing irc command!"))
		}

		Ok(Message {
			// check if the tags are present
			tags: if line.starts_with(IRC_TAG_START) {
				// tags are present, strip line of them!
				let mut split = line.splitn(2, char::is_whitespace);

				let tags = split.next().unwrap();
				line = match split.next() {
					Some(line) => line,
					None => return Err(ParseError::new_missing_command("missing irc command!")),
				};

				TagsIter::new(&tags[IRC_TAG_START.len_utf8()..]).filter_map(|r| match r {
					Ok(t) => Some(t),
					Err(_) => None,
				}).collect()
			} else {
				Vec::new()
			},
			// check if the prefix is present
			prefix: if line.starts_with(IRC_PREFIX_START) {
				// prefix is present!
				let mut split = line.splitn(2, char::is_whitespace);

				let prefix = split.next().unwrap();
				line = match split.next() {
					Some(line) => line,
					None => return Err(ParseError::new_missing_command("missing irc command!")),
				};

				Some(Prefix::parse(&prefix[IRC_PREFIX_START.len_utf8()..]))
			} else {
				None
			},
			// get the command (it must be present)
			command: {
				String::from(line.split(char::is_whitespace).next().unwrap())
			},
			params: {
				match line.splitn(2, char::is_whitespace).skip(1).next() {
					Some(line) => ParamsIter::new(line).map(|s| String::from(s)).collect(),
					None => Vec::new(),
				}
			}
		})
	}

	pub fn command(&self) -> &str {
		&self.command
	}

	pub fn has_prefix(&self) -> bool {
		self.prefix.is_some()
	}

	pub fn origin(&self) -> Option<&str> {
		match &self.prefix {
			Some(p) => Some(p.origin()),
			None => None,
		}
	}

	pub fn user(&self) -> Option<&str> {
		match &self.prefix {
			Some(p) => p.user(),
			None => None,
		}
	}

	pub fn host(&self) -> Option<&str> {
		match &self.prefix {
			Some(p) => p.host(),
			None => None,
		}
	}

	pub fn params(&self) -> std::slice::Iter<String> {
		self.params.iter()
	}

	pub fn param(&self, ind: usize) -> Option<&str> {
		match self.params.iter().skip(ind).next() {
			Some(s) => Some(s),
			None => None,
		}
	}

	pub fn tags(&self) -> std::slice::Iter<Tag> {
		self.tags.iter()
	}

	pub fn tag(&self, key: &str) -> Option<&Tag> {
		self.tags.iter().filter(|t| t.key() == key).next()
	}

	// Builder things
	pub fn with_prefix(mut self, origin: &str, user: Option<&str>, host: Option<&str>) -> Message {
		self.prefix = Some(Prefix::new(origin, user, host));
		self
	}

	pub fn with_tag(self, key: &str, value: Option<&str>) -> Message {
		self.with_tag_vendor(key, value, None)
	}

	pub fn with_tag_vendor(mut self, key: &str, value: Option<&str>, vendor: Option<&str>) -> Message {
		self.tags.push(Tag::new_with_vendor(key, value, vendor));
		self
	}

	pub fn with_param(mut self, param: &str) -> Message {
		self.params.push(String::from(param));
		self
	}
}

impl Display for Message {
	fn fmt(&self, f: &mut Formatter) -> result::Result<(), FmtError> {
		if self.tags.len() > 0 {
			f.write_str("@")?;
			for (i, t) in self.tags.iter().enumerate() {
				if i > 0 {
					f.write_str(";")?;
				}

				write!(f, "{}", t)?;
			}
			f.write_str(" ")?;
		}

		if let Some(prefix) = &self.prefix {
			write!(f, "{}", prefix)?;
			f.write_str(" ")?;
		}

		f.write_str(&self.command)?;

		if self.params.len() > 0 {
			f.write_str(" ")?;

			for (i, p) in self.params.iter().enumerate() {
				if i > 0 {
					f.write_str(" ")?;
				}

				// if this is the last parameter, do trailing
				if i >= self.params.len() - 1 {
					// try to write a trailing
					if p.split(char::is_whitespace).count() > 1 {
						f.write_str(":")?;
						f.write_str(p)?;
					} else {
						f.write_str(p)?;
					}
				} else {
					f.write_str(p)?;
				}
			}
		}

		Ok(())
	}
}