aboutsummaryrefslogtreecommitdiff
path: root/src/index.rs
blob: 27bb56b3c837efec1a09a7e0f6ba42596b320bdd (plain)
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
use std::collections::{HashSet, HashMap};
use std::fs::File;
use std::io::{Write, BufReader, BufRead};
use walkdir::*;
use std::thread;
use std::option::Option::None;
use crate::vector::FileVector;
use crate::dictionary::Dictionary;
use crate::filecache::FileCache;
use crate::searchresult::SearchResult;
use crate::filecounter::filecount;
use crate::text;
use crate::splitter;
use crate::vector;

/// Represents a Index which is ether generated
/// or read from a file.
#[derive(Clone, Debug)]
pub struct Index {
    dictionary : Dictionary,
    filecache : Vec<FileCache>,
}

impl Default for Index {
    fn default() -> Self {
        Self::empty()
    }
}

impl Index {
    pub fn empty() -> Self {
        Self {
            dictionary : Dictionary::new(),
            filecache : Vec::new()
        }
    }

    pub fn generate(input_path : &str, callback : impl Fn(u64, u64)) -> Self {
        let mut dict = Dictionary::new();
        let mut filecache : Vec<FileCache> = Vec::new();
        let mut nof = 0;
        let mut counter = 0;

        thread::scope(|s| {
            let mut nof_handle : Option<_> = Some(s.spawn(|| filecount(input_path)));

            for entry in WalkDir::new(input_path)
                .into_iter()
                .filter_map(|e| e.ok()) {
                counter += 1;
                if entry.path().is_file() {
                    let content : String = text::extract_text(entry.path().to_str().unwrap());

                    if content.is_empty() {
                        continue
                    }

                    let words : Vec<String> = splitter::split_to_words(content);

                    for word in words.iter() {
                        dict.set(word.clone());
                    }

                    let fv = dict.vectorize_word_list(words.clone());
                    filecache.push(FileCache {
                        path : entry.path().to_str().unwrap().to_string(),
                        vector : fv
                    });


                }
                match nof_handle {
                    Some(t) => {
                        nof = t.join().unwrap();
                        nof_handle = None;
                    }
                    None => {
                        callback(counter, nof);
                    }
                }
            }

            callback(nof, nof);
        });

        Self {
            dictionary : dict,
            filecache
        }
    }

    pub fn from_file(path : String) -> Self {
        let index_file = File::open(path).expect("could not open index file");
        let reader = BufReader::new(index_file);
        let mut filecache : Vec<FileCache> = Vec::new();
        let mut dict = Dictionary::new();


        for line in reader.lines() {
            let l = line.unwrap();
            if l.starts_with('#') {
                dict = Dictionary::from_line(l.strip_prefix('#').unwrap());
            } else {
                filecache.push(FileCache::from_line(l));
            }
        }

        Self {
            dictionary : dict,
            filecache
        }
    }

    pub fn merge(a : Index, b : Index) -> Self {
        let mut a_hash : HashSet<FileCache> = HashSet::new();
        let mut diff : Vec<FileCache> = Vec::new();
        let mut dict = a.dictionary.clone();
        let mut filecache = a.filecache.clone();

        for file in a.filecache.iter() {
            a_hash.insert(file.clone());
        }

        for file in b.filecache.iter() {
            if !a_hash.contains(file) {
                diff.push(file.clone());
            }
        }

        for (word, _) in b.dictionary.iter() {
            dict.set(word.clone());
        }

        let mut b_id_to_word : HashMap<u64, String> = HashMap::new();

        for (value, id) in b.dictionary.iter() {
            b_id_to_word.insert(*id, value.clone());
        }

        for file in diff {
            let mut words = Vec::new();

            for (word_id, i) in file.vector.iter() {
                for _ in 0..*i {
                    words.push(b_id_to_word.get(word_id).unwrap().clone());
                }
            }

            filecache.push(FileCache {
                path : file.path.clone(),
                vector: dict.vectorize_word_list(words)
            });
        }

        Self {
            dictionary: dict,
            filecache
        }
    }

    pub fn search(&self, search_args : Vec<String>) -> Vec<SearchResult> {
        let mut v : FileVector = FileVector::new();

        for arg in search_args {
            if let Some(value) = self.dictionary.get(arg.to_string()) {
                v.insert(*value, 1);
            }
        }

        let mut results : Vec<SearchResult> = Vec::new();

        for filecache in self.filecache.iter() {
            let mut r = SearchResult { priority : 0, path : filecache.path.clone() };
            r.priority = vector::scalar_product(&v, &filecache.vector);
            if r.priority > 0 {
                results.push(r);
            }
        }
        results.sort_by(|a, b| b.priority.cmp(&a.priority));
        results
    }

    pub fn save(&self, output : String) {
        let mut index_file = File::create(output).unwrap();

        for file in self.filecache.iter() {
            writeln!(
                index_file,
                "{}, {}",
                file.path .replace(',', "\0"),
                file.vector.stringify()
                ).ok();
        }

        let dict_list : Vec<String> = self.dictionary.to_list();
        writeln!(index_file, "#{}", dict_list.join(",")).ok();
    }
}