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
use super::Message;
use num::Integer;
use std::fmt::Write;

impl Message {
    /// Create an empty packet
    pub fn new() -> Self {
        Message::default()
    }

    /// Create from raw vector of u32
    pub fn from_raw_slice(raw: &[u32]) -> Self {
        Message {
            raw: raw.to_vec(),
            duty_cycle: None,
            carrier: None,
        }
    }

    /// Concatenate two messages. Self must have a trailing gap.
    pub fn extend(&mut self, other: &Message) {
        assert!(self.raw.is_empty() || self.has_trailing_gap());

        if self.carrier.is_none() {
            self.carrier = other.carrier;
        }

        if self.duty_cycle.is_none() {
            self.duty_cycle = other.duty_cycle;
        }

        self.raw.extend_from_slice(&other.raw);
    }

    /// Do we have a trailing gap
    pub fn has_trailing_gap(&self) -> bool {
        let len = self.raw.len();

        len > 0 && (len % 2) == 0
    }

    /// Remove any trailing gap
    pub fn remove_trailing_gap(&mut self) {
        if self.has_trailing_gap() {
            self.raw.pop();
        }
    }

    /// Print the flash and gap information as an raw ir string
    pub fn print_rawir(&self) -> String {
        let mut s = String::new();

        self.raw.iter().enumerate().for_each(|(i, v)| {
            write!(
                s,
                "{}{}{}",
                if i == 0 { "" } else { " " },
                if i.is_even() { "+" } else { "-" },
                v
            )
            .unwrap()
        });

        s
    }

    /// Parse a raw IR string of the form `+9000 -45000 +2250`
    pub fn parse(s: &str) -> Result<Self, String> {
        let mut raw = Vec::new();
        let mut flash = true;

        for e in s.split(|c: char| c.is_whitespace() || c == ',') {
            if e.is_empty() {
                continue;
            }

            let mut chars = e.chars().peekable();

            match chars.peek() {
                Some('+') => {
                    if !flash {
                        return Err("unexpected ‘+’ encountered".to_string());
                    }
                    chars.next();
                }
                Some('-') => {
                    if flash {
                        return Err("unexpected ‘-’ encountered".to_string());
                    }
                    chars.next();
                }
                Some(ch) if !ch.is_numeric() => {
                    return Err(format!("unexpected ‘{ch}’ encountered"));
                }
                _ => (),
            }

            let v = chars.collect::<String>();

            let v = v.parse().map_err(|_| format!("invalid number ‘{v}’"))?;

            if v == 0 {
                return Err("nonsensical 0 length".to_string());
            }

            raw.push(v);

            flash = !flash;
        }

        if raw.is_empty() {
            return Err("missing length".to_string());
        }

        Ok(Message {
            raw,
            carrier: None,
            duty_cycle: None,
        })
    }

    /// Parse pulse/space text. This format is produces by lirc's mode2 tool.
    /// Some lirc drivers sometimes produce consecutive pulses or spaces, rather
    /// than alternating. These are automatically folded into one.
    ///
    /// The return value is the line number and the error string.
    pub fn parse_mode2(s: &str) -> Result<Message, (usize, String)> {
        let mut res = Vec::new();
        let mut carrier = None;
        let mut line_no = 0;

        for line in s.lines() {
            line_no += 1;

            let mut words = line.split_whitespace();

            let is_pulse = match words.next() {
                Some("pulse") => true,
                Some("space") => false,
                Some("timeout") => false,
                Some("carrier") => {
                    match words.next() {
                        Some(w) => match w.parse() {
                            Ok(c) => {
                                if carrier.is_some() && carrier != Some(c) {
                                    return Err((
                                        line_no,
                                        String::from("carrier specified more than once"),
                                    ));
                                }

                                if c < 0 {
                                    return Err((
                                        line_no,
                                        format!("negative carrier {c} does not make sense"),
                                    ));
                                }

                                carrier = Some(c);
                            }
                            Err(_) => {
                                return Err((
                                    line_no,
                                    format!("carrier argument ‘{w}’ is not a number"),
                                ));
                            }
                        },
                        None => return Err((line_no, String::from("missing carrier value"))),
                    }

                    if let Some(w) = words.next() {
                        if !w.starts_with('#') && !w.starts_with("//") {
                            return Err((line_no, format!("unexpected ‘{w}’")));
                        }
                    }

                    continue;
                }
                Some(w) => {
                    if !w.starts_with('#') && !w.starts_with("//") {
                        return Err((line_no, format!("unexpected ‘{w}’")));
                    }
                    continue;
                }
                None => {
                    continue;
                }
            };

            let value = match words.next() {
                Some(w) => match w.parse() {
                    Ok(0) => {
                        return Err((line_no, "nonsensical 0 duration".to_string()));
                    }
                    Ok(n) => {
                        if n > 0xff_ff_ff {
                            return Err((line_no, format!("duration ‘{w}’ too long")));
                        }
                        n
                    }
                    Err(_) => {
                        return Err((line_no, format!("invalid duration ‘{w}’")));
                    }
                },
                None => {
                    return Err((line_no, "missing duration".to_string()));
                }
            };

            if let Some(trailing) = words.next() {
                return Err((line_no, format!("unexpected ‘{trailing}’")));
            }

            if is_pulse {
                if res.len() % 2 == 1 {
                    // two consecutive pulses should be folded
                    *res.last_mut().unwrap() += value;
                } else {
                    res.push(value);
                }
            } else if res.len() % 2 == 0 {
                // two consecutive spaces should be folded, but leading spaces are ignored
                if let Some(last) = res.last_mut() {
                    *last += value;
                }
            } else {
                res.push(value);
            }
        }

        if res.is_empty() {
            if line_no == 0 {
                line_no = 1;
            }
            return Err((line_no, "missing pulse".to_string()));
        }

        Ok(Message {
            duty_cycle: None,
            carrier,
            raw: res,
        })
    }
}

#[test]
fn parse_mode2() {
    assert_eq!(
        Message::parse_mode2("").err(),
        Some((1, "missing pulse".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 0").err(),
        Some((1, "nonsensical 0 duration".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse").err(),
        Some((1, "missing duration".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse abc").err(),
        Some((1, "invalid duration ‘abc’".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 1\npulse 2").unwrap().raw,
        vec!(3u32)
    );
    assert_eq!(
        Message::parse_mode2("space 1\r\nspace 2\npulse 1\npulse 2")
            .unwrap()
            .raw,
        vec!(3u32)
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\npulse 21\nspace 10\nspace 50")
            .unwrap()
            .raw,
        vec!(121u32, 60u32)
    );
    assert_eq!(
        Message::parse_mode2("polse 100\nspace 10\nspace 50").err(),
        Some((1, "unexpected ‘polse’".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\npulse 50")
            .unwrap()
            .raw,
        vec!(100u32, 10u32, 50u32)
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\npulse 50\nspace 34134134").err(),
        Some((4, "duration ‘34134134’ too long".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\npulse 50 foobar\nspace 34134134").err(),
        Some((3, "unexpected ‘foobar’".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\ncarrier foobar\nspace 34134134").err(),
        Some((3, "carrier argument ‘foobar’ is not a number".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\ncarrier\nspace 34134134").err(),
        Some((3, "missing carrier value".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\ncarrier 500 x\nspace 34134134").err(),
        Some((3, "unexpected ‘x’".to_string()))
    );
    assert_eq!(
        Message::parse_mode2("pulse 100\nspace 10\npulse 50\ncarrier 500 // hiya\ntimeout 100000")
            .unwrap(),
        Message {
            carrier: Some(500),
            duty_cycle: None,
            raw: vec!(100u32, 10u32, 50u32, 100000u32)
        }
    );
}

#[test]
fn parse_test() {
    assert_eq!(
        Message::parse("+100 +100"),
        Err("unexpected ‘+’ encountered".to_string())
    );

    assert_eq!(
        Message::parse("+100 -100 -1"),
        Err("unexpected ‘-’ encountered".to_string())
    );

    assert_eq!(
        Message::parse("+100 -100"),
        Ok(Message {
            raw: vec!(100, 100),
            duty_cycle: None,
            carrier: None
        })
    );

    assert_eq!(Message::parse(""), Err("missing length".to_string()));

    assert_eq!(Message::parse("+a"), Err("invalid number ‘a’".to_string()));

    assert_eq!(
        Message::parse("+0"),
        Err("nonsensical 0 length".to_string())
    );

    assert_eq!(
        Message::parse("100  \n100\r +1"),
        Ok(Message {
            raw: vec!(100u32, 100u32, 1u32),
            duty_cycle: None,
            carrier: None
        })
    );
    assert_eq!(
        Message::parse("100,100,+1,-20000"),
        Ok(Message {
            raw: vec!(100u32, 100u32, 1u32, 20000u32),
            duty_cycle: None,
            carrier: None
        })
    );
}

#[test]
fn print_test() {
    let m = Message {
        raw: vec![100, 50, 75],
        carrier: None,
        duty_cycle: None,
    };

    assert_eq!(m.print_rawir(), "+100 -50 +75");
}