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
use crate::{Filter, Joinable, RunOptions};
use std::sync::mpsc::{self, Sender, Receiver};
use std::thread::{JoinHandle};
use bodyfile::Bodyfile3Line;
use std::convert::TryFrom;

pub struct BodyfileDecoder {
    worker: Option<JoinHandle<()>>,
    rx: Option<Receiver<Bodyfile3Line>>,
}

impl Filter<String, Bodyfile3Line> for BodyfileDecoder {
    fn with_receiver(reader: Receiver<String>, options: RunOptions) -> Self {
        let (tx, rx): (Sender<Bodyfile3Line>, Receiver<Bodyfile3Line>) = mpsc::channel();
        Self {
            worker: Some(std::thread::spawn(move || {
                Self::worker(reader, tx, options)
            })),
            rx: Some(rx),
        }
    }

    fn worker(reader: Receiver<String>, tx: Sender<Bodyfile3Line>, options: RunOptions) {
        loop {
            let mut line = match reader.recv() {
                Err(_) => {break;}
                Ok(l) => l
            };

            if line.starts_with('#') { continue; }
            Self::trim_newline(&mut line);

            let bf_line = match Bodyfile3Line::try_from(line.as_ref()) {
                Err(e) => {
                    if options.strict_mode {
                        log::warn!("bodyfile parser error: {}", e);
                        panic!("failed while parsing: {:?}", line);
                    } else {
                        log::warn!("bodyfile parser error: {}", e);
                        #[cfg(debug_assertions)]
                        log::warn!("failed line was: {:?}", line);
                    }
                    continue;
                }
                Ok(l) => l
            };

            if let Err(_) = tx.send(bf_line) {
                break;
            }
        }
    }

    fn get_receiver(&mut self) -> Receiver<Bodyfile3Line> {
        self.rx.take().unwrap()
    }
}

impl BodyfileDecoder {
    fn trim_newline(s: &mut String) {
        if s.ends_with('\n') {
            s.pop();
            if s.ends_with('\r') {
                s.pop();
            }
        }
    }
}

impl Joinable<()> for BodyfileDecoder {
    fn join(&mut self) -> std::thread::Result<()> {
        self.worker.take().unwrap().join()
    }
}