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
use std::collections::HashMap;

use linked_hash_map::LinkedHashMap;

use crate::infograph::docs::{Doc, Element, Query};
use std::rc::Rc;

struct Index {
    index: HashMap<String, usize>,
    num_queries: usize,
    num_hits: usize,
    allocated_memory: usize,
}

pub struct IndexInfo {
    pub name: String,
    pub num_entries: usize,
    pub num_queries: usize,
    pub num_hits: usize,
    pub allocated_memory: usize,
}

pub struct Table<'a> {
    doc: &'a Doc,
    query_cache: LinkedHashMap<String, Rc<Query>>,
    auto_cache: LinkedHashMap<(String, String), Element<'a>>,
    indices: HashMap<String, Index>,
    num_queries: usize,
    num_index_hits: usize,
    num_auto_cache_hits: usize,
    num_query_cache_hits: usize,
    num_table_scans: usize,
}

impl<'a> Table<'a> {
    pub fn new(doc: &'a Doc) -> Self {
        Table {
            doc,
            query_cache: LinkedHashMap::with_capacity(128),
            auto_cache: LinkedHashMap::with_capacity(1024),
            indices: HashMap::with_capacity(3),
            num_queries: 0,
            num_index_hits: 0,
            num_auto_cache_hits: 0,
            num_query_cache_hits: 0,
            num_table_scans: 0,
        }
    }

    pub fn add_index(&mut self, query: impl AsRef<str>) {
        let compiled_query = self.doc.compile(query.as_ref());
        let mut index = Index {
            index: HashMap::with_capacity(self.len()),
            num_queries: 0,
            num_hits: 0,
            allocated_memory: 0,
        };

        index.allocated_memory += index.index.capacity() * 11 / 10
            * (std::mem::size_of::<usize>() + std::mem::size_of::<String>());

        let root = self.doc.root();

        for position in 0..root.len() {
            let element = root.at(position);
            if let Some(key) = compiled_query.execute(element).as_str() {
                index.allocated_memory += key.len();
                index.index.insert(key.to_owned(), position);
            }
        }

        self.indices.insert(query.as_ref().to_owned(), index);
    }

    pub fn query(&mut self, query: impl AsRef<str>, value: impl AsRef<str>) -> Option<Element> {
        let query_string = query.as_ref();
        let value_string = value.as_ref();

        self.num_queries += 1;

        if let Some(index) = self.indices.get_mut(query_string) {
            Table::query_index(self.doc, index, value_string)
        } else if let Some(result) = self
            .auto_cache
            .get_refresh(&(query_string.to_string(), value_string.to_string()))
        {
            self.num_auto_cache_hits += 1;
            Some(result.clone())
        } else {
            self.num_table_scans += 1;
            self.table_scan(query_string, value_string)
        }
    }

    fn query_index(doc: &'a Doc, index: &mut Index, value_string: &str) -> Option<Element<'a>> {
        index.num_queries += 1;

        if let Some(position) = index.index.get(value_string) {
            index.num_hits += 1;
            Some(doc.root().at(*position))
        } else {
            None
        }
    }

    fn compile_query(&mut self, query_string: &str) -> Rc<Query> {
        if let Some(query) = self.query_cache.get_refresh(query_string) {
            self.num_query_cache_hits += 1;

            query.clone()
        } else {
            let query = Rc::new(self.doc.compile(query_string));
            self.query_cache
                .insert(query_string.to_owned(), query.clone());

            if self.query_cache.len() == self.query_cache.capacity() {
                self.query_cache.pop_front();
            }

            query
        }
    }

    fn table_scan(&mut self, query_string: &str, value_string: &str) -> Option<Element> {
        let query = self.compile_query(query_string);
        for element in self.doc.root().iter() {
            let child = query.execute(element);
            if child.as_str().unwrap_or("") == value_string {
                self.auto_cache.insert(
                    (query_string.to_string(), value_string.to_string()),
                    element,
                );
                if self.auto_cache.len() == self.auto_cache.capacity() {
                    self.auto_cache.pop_front();
                }

                return Some(element);
            }
        }

        None
    }

    pub fn len(&self) -> usize {
        self.doc.root().len()
    }

    pub fn indices(&self) -> Vec<IndexInfo> {
        self.indices
            .iter()
            .map(|(name, index)| IndexInfo {
                name: name.clone(),
                num_entries: index.index.len(),
                num_queries: index.num_queries,
                num_hits: index.num_hits,
                allocated_memory: index.allocated_memory,
            })
            .collect()
    }

    pub fn num_queries(&self) -> usize {
        self.num_queries
    }

    pub fn num_query_cache_hits(&self) -> usize {
        self.num_query_cache_hits
    }

    pub fn num_query_cache_misses(&self) -> usize {
        self.num_table_scans - self.num_query_cache_hits
    }

    pub fn query_cache_hit_ratio(&self) -> f32 {
        if self.num_table_scans == 0 {
            0.
        } else {
            100. * self.num_query_cache_hits as f32 / self.num_table_scans as f32
        }
    }

    pub fn num_auto_cache_hits(&self) -> usize {
        self.num_auto_cache_hits
    }

    pub fn num_auto_cache_misses(&self) -> usize {
        self.num_queries - self.num_index_hits - self.num_auto_cache_hits
    }

    pub fn auto_cache_hit_ratio(&self) -> f32 {
        let queries = self.num_queries - self.num_index_hits;
        if queries == 0 {
            0.
        } else {
            100. * self.num_query_cache_hits as f32 / queries as f32
        }
    }

    pub fn num_index_hits(&self) -> usize {
        self.num_index_hits
    }

    pub fn num_index_misses(&self) -> usize {
        self.num_queries - self.num_index_hits
    }

    pub fn index_hit_ratio(&self) -> f32 {
        if self.num_queries == 0 {
            0.
        } else {
            100. * self.num_query_cache_hits as f32 / self.num_queries as f32
        }
    }

    pub fn allocated_memory(&self) -> usize {
        let allocated_index_memory: usize = self
            .indices
            .values()
            .map(|index| index.allocated_memory)
            .sum();
        let allocated_auto_cache_content: usize = self
            .auto_cache
            .keys()
            .map(|(path, key)| key.len() + path.len())
            .sum();
        let allocated_auto_cache_table: usize = self.auto_cache.capacity() * 11 / 10
            * (std::mem::size_of::<(String, String)>() + std::mem::size_of::<&Element>());

        self.doc.allocated_size()
            + allocated_index_memory
            + allocated_auto_cache_content
            + allocated_auto_cache_table
    }
}