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
use crossbeam_channel::{Receiver, Sender};
use matcher::{Match, Matcher};
use memmap::Mmap;
use pipeline::{Pipeline, PipelineInfo};
use pipeline_finder::PathInfo;
use std::fs::File;
use std::io::{Error, Read};
use std::ops::Deref;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use util::{catch, decode_error};

// ---------------------------------------------------------------------------------------------------------------------
// PathMatch
// ---------------------------------------------------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct PathMatch {
    pub path: PathBuf,
    pub matches: Vec<Match>,
}

// ---------------------------------------------------------------------------------------------------------------------
// PipelineMatcher
// ---------------------------------------------------------------------------------------------------------------------

pub struct PipelineMatcher<T: Matcher> {
    pub skip_binary: bool,
    pub print_skipped: bool,
    pub binary_check_bytes: usize,
    pub mmap_bytes: u64,
    pub infos: Vec<String>,
    pub errors: Vec<String>,
    time_beg: Instant,
    time_bsy: Duration,
    matcher: T,
    keyword: Vec<u8>,
}

impl<T: Matcher> PipelineMatcher<T> {
    pub fn new(matcher: T, keyword: &[u8]) -> Self {
        PipelineMatcher {
            skip_binary: true,
            print_skipped: false,
            binary_check_bytes: 128,
            mmap_bytes: 1024 * 1024,
            infos: Vec::new(),
            errors: Vec::new(),
            time_beg: Instant::now(),
            time_bsy: Duration::new(0, 0),
            matcher: matcher,
            keyword: Vec::from(keyword),
        }
    }

    fn search_path(&mut self, info: PathInfo) -> PathMatch {
        let path_org = info.path.clone();

        let result = catch::<_, PathMatch, Error>(|| {
            let mmap;
            let mut buf = Vec::new();
            let src = if info.len > self.mmap_bytes {
                let file = try!(File::open(&info.path));
                mmap = try!(unsafe { Mmap::map(&file) });
                mmap.deref()
            } else {
                let mut f = try!(File::open(&info.path));
                try!(f.read_to_end(&mut buf));
                &buf[..]
            };

            if self.skip_binary {
                let mut is_binary = false;
                let check_bytes = if self.binary_check_bytes < src.len() {
                    self.binary_check_bytes
                } else {
                    src.len()
                };
                for i in 0..check_bytes {
                    if src[i] <= 0x08 {
                        is_binary = true;
                        break;
                    }
                }
                if is_binary {
                    if self.print_skipped {
                        self.infos.push(format!("Skipped: {:?} ( binary file )\n", info.path));
                    }
                    return Ok(PathMatch {
                        path: info.path.clone(),
                        matches: Vec::new(),
                    });
                }
            }

            let ret = self.matcher.search(src, &self.keyword);

            Ok(PathMatch {
                path: info.path.clone(),
                matches: ret,
            })
        });

        match result {
            Ok(x) => x,
            Err(e) => {
                self.errors
                    .push(format!("Error: {} @ {:?}\n", decode_error(e.kind()), path_org));
                PathMatch {
                    path: info.path.clone(),
                    matches: Vec::new(),
                }
            }
        }
    }
}

impl<T: Matcher> Pipeline<PathInfo, PathMatch> for PipelineMatcher<T> {
    fn setup(&mut self, id: usize, rx: Receiver<PipelineInfo<PathInfo>>, tx: Sender<PipelineInfo<PathMatch>>) {
        self.infos = Vec::new();
        self.errors = Vec::new();
        let mut seq_beg_arrived = false;

        loop {
            match rx.recv() {
                Ok(PipelineInfo::SeqDat(x, p)) => {
                    watch_time!(self.time_bsy, {
                        let ret = self.search_path(p);
                        let _ = tx.send(PipelineInfo::SeqDat(x, ret));
                    });
                }

                Ok(PipelineInfo::SeqBeg(x)) => {
                    if !seq_beg_arrived {
                        self.time_beg = Instant::now();
                        let _ = tx.send(PipelineInfo::SeqBeg(x));
                        seq_beg_arrived = true;
                    }
                }

                Ok(PipelineInfo::SeqEnd(x)) => {
                    for i in &self.infos {
                        let _ = tx.send(PipelineInfo::MsgInfo(id, i.clone()));
                    }
                    for e in &self.errors {
                        let _ = tx.send(PipelineInfo::MsgErr(id, e.clone()));
                    }

                    let _ = tx.send(PipelineInfo::MsgTime(id, self.time_bsy, self.time_beg.elapsed()));
                    let _ = tx.send(PipelineInfo::SeqEnd(x));
                    break;
                }

                Ok(PipelineInfo::MsgInfo(i, e)) => {
                    let _ = tx.send(PipelineInfo::MsgInfo(i, e));
                }
                Ok(PipelineInfo::MsgErr(i, e)) => {
                    let _ = tx.send(PipelineInfo::MsgErr(i, e));
                }
                Ok(PipelineInfo::MsgTime(i, t0, t1)) => {
                    let _ = tx.send(PipelineInfo::MsgTime(i, t0, t1));
                }
                Err(_) => break,
            }
        }
    }
}

// ---------------------------------------------------------------------------------------------------------------------
// Test
// ---------------------------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crossbeam_channel::unbounded;
    use matcher::QuickSearchMatcher;
    use pipeline::{Pipeline, PipelineInfo};
    use pipeline_finder::PathInfo;
    use std::path::PathBuf;
    use std::thread;

    #[test]
    fn pipeline_matcher() {
        let qs = QuickSearchMatcher::new();
        let mut matcher = PipelineMatcher::new(qs, &"amber".to_string().into_bytes());

        let (in_tx, in_rx) = unbounded();
        let (out_tx, out_rx) = unbounded();
        thread::spawn(move || {
            matcher.setup(0, in_rx, out_tx);
        });

        let _ = in_tx.send(PipelineInfo::SeqBeg(0));
        let _ = in_tx.send(PipelineInfo::SeqDat(
            0,
            PathInfo {
                path: PathBuf::from("./src/ambs.rs"),
                len: 1,
            },
        ));
        let _ = in_tx.send(PipelineInfo::SeqDat(
            1,
            PathInfo {
                path: PathBuf::from("./src/ambr.rs"),
                len: 1,
            },
        ));
        let _ = in_tx.send(PipelineInfo::SeqDat(
            2,
            PathInfo {
                path: PathBuf::from("./src/util.rs"),
                len: 1,
            },
        ));
        let _ = in_tx.send(PipelineInfo::SeqEnd(3));

        let mut ret = Vec::new();
        loop {
            match out_rx.recv().unwrap() {
                PipelineInfo::SeqDat(_, x) => ret.push(x),
                PipelineInfo::SeqEnd(_) => break,
                _ => (),
            }
        }

        for r in ret {
            if r.path == PathBuf::from("./src/ambs.rs") {
                assert!(!r.matches.is_empty());
            }
            if r.path == PathBuf::from("./src/ambr.rs") {
                assert!(!r.matches.is_empty());
            }
            if r.path == PathBuf::from("./src/util.rs") {
                assert!(r.matches.is_empty());
            }
        }
    }
}