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
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::Write;
use std::option::Option;

use super::error::Error;

use crate::escaped::{escape_char, unescape_char};

#[derive(Debug, PartialEq, Default)]
pub struct Message<'a> {
    pub tags: BTreeMap<&'a str, Cow<'a, str>>,
    pub prefix: Option<&'a str>,
    pub command: &'a str,
    pub params: Vec<&'a str>,
}

fn parse_tags<'a>(input: &'a str) -> Result<BTreeMap<&'a str, Cow<'a, str>>, Error> {
    let mut tags = BTreeMap::new();

    for tag_data in input.split(';') {
        let mut pieces = tag_data.splitn(2, '=');
        let tag_name = pieces
            .next()
            .ok_or_else(|| Error::TagError("missing tag name".to_string()))?;
        let raw_tag_value = pieces.next().unwrap_or("");

        // If the value doesn't contain any escaped characters, we can return
        // the string as-is.
        if !raw_tag_value.contains('\\') {
            tags.insert(tag_name, Cow::Borrowed(raw_tag_value));
            continue;
        }

        let mut tag_value = String::new();
        let mut tag_value_chars = raw_tag_value.chars();
        while let Some(c) = tag_value_chars.next() {
            if c == '\\' {
                if let Some(escaped_char) = tag_value_chars.next() {
                    tag_value.push(unescape_char(escaped_char));
                }
            } else {
                tag_value.push(c);
            }
        }

        tags.insert(tag_name, Cow::Owned(tag_value));
    }

    Ok(tags)
}

impl<'a> TryFrom<&'a str> for Message<'a> {
    type Error = Error;

    fn try_from(input: &'a str) -> Result<Self, Self::Error> {
        // We want a mutable input so we can jump through it as we parse the
        // message. Note that this shadows the input param on purpose so it
        // cannot accidentally be used later.
        let mut input = input;

        // Possibly chop off the ending \r\n where either of those characters is
        // optional.
        if input.ends_with('\n') {
            input = &input[..input.len() - 1];
        }
        if input.ends_with('\r') {
            input = &input[..input.len() - 1];
        }

        let mut tags = BTreeMap::new();
        let mut prefix = None;

        if input.get(..1) == Some("@") {
            // Find the first space so we can split on it.
            if let Some(loc) = input.find(' ') {
                let tag_data = &input[1..loc];
                tags = parse_tags(tag_data)?;

                // Update input to point to everything after the space
                input = &input[loc..];
            } else {
                return Err(Error::TagError("failed to parse tag data".to_string()));
            }

            // Trim up to the next valid character.
            input = input.trim_start_matches(' ');
        }

        if input.get(..1) == Some(":") {
            // Find the first space so we can split on it.
            if let Some(loc) = input.find(' ') {
                prefix = Some(&input[1..loc]);

                // Update input to point to everything after the space
                input = &input[loc..];
            } else {
                return Err(Error::PrefixError(
                    "failed to parse prefix data".to_string(),
                ));
            }

            // Note that we don't trim spaces here because that's handled by
            // param parsing.
        }

        // Parse out the params
        let mut params = Vec::new();
        loop {
            // Drop any leading spaces
            input = input.trim_start_matches(' ');

            match input.get(..1) {
                // If a param started with a :, that means the rest of the input
                // is a single trailing param.
                Some(":") => {
                    params.push(&input[1..]);
                    break;
                }

                // Anything else is a normal param.
                Some(_) => {
                    match input.find(' ') {
                        Some(loc) => {
                            params.push(&input[..loc]);
                            // Update input to point to everything after the space
                            input = &input[loc..];
                        }

                        // If we couldn't find a space, the rest of the string
                        // is the param.
                        None => {
                            params.push(input);
                            break;
                        }
                    }
                }

                // If we didn't get anything, this means we're at the end of the
                // string.
                None => {
                    break;
                }
            }
        }

        if params.is_empty() {
            return Err(Error::CommandError("missing command".to_string()));
        }

        // Take the first param as the command. Note that we've already checked
        // if params is empty, so we can unwrap this safely.
        let (command, params) = params.split_first().unwrap();

        Ok(Message {
            tags,
            prefix,
            command,
            params: params.to_vec(),
        })
    }
}

impl<'a> fmt::Display for Message<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.tags.is_empty() {
            f.write_char('@')?;

            for (i, (k, v)) in self.tags.iter().enumerate() {
                // We need to insert a separator for everything other than the
                // first value.
                if i != 0 {
                    f.write_char(';')?;
                }

                f.write_str(k)?;
                if v.is_empty() {
                    continue;
                }

                f.write_char('=')?;

                for c in v.chars() {
                    match escape_char(c) {
                        Some(escaped_str) => f.write_str(escaped_str)?,
                        None => f.write_char(c)?,
                    }
                }
            }

            f.write_char(' ')?;
        }

        if let Some(prefix) = &self.prefix {
            f.write_char(':')?;
            f.write_str(prefix)?;
            f.write_char(' ')?;
        }

        f.write_str(&self.command)?;

        if let Some((last, params)) = self.params.split_last() {
            for param in params {
                f.write_char(' ')?;
                f.write_str(param)?;
            }

            f.write_str(" :")?;
            f.write_str(last)?;
        }

        Ok(())
    }
}