[go: up one dir, main page]

logdriller 0.3.0

tool to visualize application log output in the terminal
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
use crate::{MatchSequence, Restore};
use memchr::memchr_iter;
use savefile::prelude::Savefile;
use std::fmt::{Debug, Formatter};
use std::sync::atomic::{AtomicU64, Ordering};

/// This is a little trie-based search structure.
///
/// Really, we should probably just use the machinery from the regex-crate.
/// It's battle tested and very fast. This may be buggy.
///
/// But it was really fun to write!
#[derive(Clone)]
enum TinyMap<K, V> {
    Inline(u8, [K; 8], [Option<V>; 8]),
    Heap(Vec<K>, Vec<V>),
}

impl<K: Debug, V: Debug> Debug for TinyMap<K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            TinyMap::Inline(count, keys, values) => f
                .debug_map()
                .entries(
                    keys[..*count as usize]
                        .iter()
                        .zip(values[..*count as usize].iter()),
                )
                .finish(),
            TinyMap::Heap(keys, values) => f
                .debug_map()
                .entries(keys.iter().zip(values.iter()))
                .finish(),
        }
    }
}

impl<K: Debug + Default + Copy + PartialEq, V> TinyMap<K, V> {
    fn new() -> TinyMap<K, V> {
        Self::Inline(0, Default::default(), Default::default())
    }
    #[allow(unused)]
    fn is_empty(&self) -> bool {
        match self {
            TinyMap::Inline(count, _, _) => *count == 0,
            TinyMap::Heap(keys, _) => keys.is_empty(),
        }
    }
    #[inline]
    fn visit(&mut self, mut visitor: impl FnMut(K, &mut V) -> bool) -> bool {
        match self {
            TinyMap::Inline(count, keys, values) => {
                for i in 0..*count {
                    if !visitor(keys[i as usize], values[i as usize].as_mut().unwrap()) {
                        return false;
                    }
                }
                true
            }
            TinyMap::Heap(keys, values) => {
                for (key, val) in keys.iter().zip(values.iter_mut()) {
                    if !visitor(*key, val) {
                        return false;
                    }
                }
                true
            }
        }
    }
    #[allow(unused)]
    fn remove(&mut self, key: K) {
        match self {
            TinyMap::Inline(count, keys, vals) => {
                if let Some(i) = keys[..*count as usize].iter().position(|x| *x == key) {
                    *count -= 1;
                    if *count as usize != i {
                        keys[i] = keys[*count as usize];
                        keys[*count as usize] = K::default();
                        vals[i] = vals[*count as usize].take();
                    }
                }
            }
            TinyMap::Heap(keys, vals) => {
                if let Some(i) = keys.iter().position(|x| *x == key) {
                    keys.swap_remove(i);
                    vals.swap_remove(i);
                }
            }
        }
    }
    #[inline]
    fn insert(&mut self, key: K, value: V) -> bool {
        match self {
            TinyMap::Inline(count, keys, values) => {
                if *count == 8 {
                    let keys = keys[..*count as usize].to_vec();
                    let values: Vec<V> = values[..*count as usize]
                        .iter_mut()
                        .map(|x| x.take().unwrap())
                        .collect();
                    *self = Self::Heap(keys, values);
                    return self.insert(key, value);
                }
                if keys[..*count as usize].contains(&key) {
                    return false;
                }
                keys[*count as usize] = key;
                values[*count as usize] = Some(value);
                *count += 1;
                true
            }
            TinyMap::Heap(keys, values) => {
                if keys.contains(&key) {
                    return false;
                }
                keys.push(key);
                values.push(value);
                true
            }
        }
    }
    #[inline]
    fn get(&self, key: K) -> Option<&V> {
        match self {
            TinyMap::Inline(count, keys, values) => {
                if let Some(index) = keys[..*count as usize].iter().position(|x| *x == key) {
                    values[index].as_ref()
                } else {
                    None
                }
            }
            TinyMap::Heap(keys, values) => {
                if let Some(index) = keys.iter().position(|x| *x == key) {
                    Some(&values[index])
                } else {
                    None
                }
            }
        }
    }
    #[inline]
    fn get_mut(&mut self, key: K) -> Option<&mut V> {
        match self {
            TinyMap::Inline(count, keys, values) => {
                if let Some(index) = keys[0..*count as usize].iter().position(|x| *x == key) {
                    values[index].as_mut()
                } else {
                    None
                }
            }
            TinyMap::Heap(keys, values) => {
                if let Some(index) = keys.iter().position(|x| *x == key) {
                    Some(&mut values[index])
                } else {
                    None
                }
            }
        }
    }
}


#[derive(Debug, PartialEq, Clone, Copy, Default, Savefile)]
pub enum TrieKey {
    #[default]
    Eof,
    Exact(u8),
    WildcardThen(u8),
    Any,
}

impl TrieKey {
    #[allow(unused)]
    fn exact(s: &str) -> Vec<TrieKey> {
        let mut ret = Vec::with_capacity(s.len());
        for (idx, c) in s.bytes().enumerate() {
            ret.push(if idx == 0 {
                TrieKey::WildcardThen(c)
            } else {
                TrieKey::Exact(c)
            });
        }
        ret
    }
    pub(crate) fn match_index(&self, key: &[u8], mut cb: impl FnMut(usize) -> bool) -> bool {
        match *self {
            TrieKey::Eof => {
                if key.is_empty() {
                    cb(0)
                } else {
                    true
                }
            }
            TrieKey::Exact(needle) => {
                if let Some(first) = key.first() {
                    if *first == needle {
                        cb(0)
                    } else {
                        true
                    }
                } else {
                    true
                }
            }
            TrieKey::WildcardThen(haystack_key) => {
                for index in memchr_iter(haystack_key, key) {
                    if !cb(index) {
                        return false;
                    }
                }
                true
            }
            TrieKey::Any => cb(0),
        }
    }
}

#[derive(Debug)]
enum TrieNode<V> {
    Empty,
    Head {
        map: Box<TinyMap<TrieKey, TrieNode<V>>>,
        value: Option<V>,
        generation: u64,
    },
    Tail {
        // Must not be empty
        tail: Vec<TrieKey>,
        value: Option<V>,
        generation: u64,
    },
}
impl<V:Clone> Clone for TrieNode<V> {
    fn clone(&self) -> Self {
        match self {
            TrieNode::Empty => {TrieNode::Empty}
            TrieNode::Head { map, value, generation } => {
                TrieNode::Head {
                    map: map.clone(),
                    value: value.clone(),
                    generation: *generation
                }
            }
            TrieNode::Tail { tail, value, generation } => {
                TrieNode::Tail {
                    tail: tail.clone(),
                    value: value.clone(),
                    generation: *generation
                }
            }
        }
    }
}

#[derive(Debug)]
pub struct Trie<V> {
    top: TrieNode<V>,
    generation: AtomicU64,
    match_sequence: MatchSequence,
}
impl<V> Trie<V> {
    pub fn empty_trie(&self) -> bool {
        match &self.top {
            TrieNode::Empty => {true}
            _ => false,
        }
    }

}
impl<V> Clone for Trie<V> where V: Clone{
    fn clone(&self) -> Self {
        Self {
            top: self.top.clone(),
            generation: AtomicU64::new(self.generation.load(Ordering::Relaxed)),
            match_sequence: self.match_sequence.clone(),
        }
    }
}
impl<V> Default for Trie<V> {
    fn default() -> Self {
        Self::new()
    }
}

trait MatchSequenceCollector {
    type Restore;
    fn save(&mut self) -> Self::Restore;
    fn restore(&mut self, restore: Self::Restore);
    fn add(&mut self, i: u32);
}
struct DummyMatchSequenceCollector;
impl MatchSequenceCollector for DummyMatchSequenceCollector {
    type Restore = ();
    #[inline]
    fn save(&mut self) -> Self::Restore {
    }

    #[inline]
    fn restore(&mut self, _restore: Self::Restore) {
    }

    #[inline]
    fn add(&mut self, _i: u32) {
    }
}
impl MatchSequenceCollector for MatchSequence {
    type Restore = Restore;
    fn save(&mut self) -> Restore {
        self.save()
    }
    fn restore(&mut self, restore: Restore) {
        self.restore(restore)
    }

    fn add(&mut self, i: u32) {
        self.add(i)
    }
}


impl<V> TrieNode<V> {
    // return false to stop traversal
    #[inline]
    pub fn search<'a, M: MatchSequenceCollector>(
        &mut self,
        needle_key: &[u8],
        match_sequence: &mut M,
        hit: &mut impl FnMut(&V, &M) -> bool,
        cur_generation: u64,
    ) -> bool {
        match self {
            TrieNode::Head {
                map,
                value,
                generation,
            } => {
                if let Some(v) = value.as_ref()
                    && *generation != cur_generation {
                        *generation = cur_generation;
                        if !hit(v, match_sequence) {
                            return false;
                        }
                    }
                if needle_key.is_empty() {
                    return true;
                }

                map.visit(|haystack_key, haystack_value| {
                    haystack_key.match_index(&needle_key[0..], |index| {
                        let restore = match_sequence.save();
                        match_sequence.add(index as u32);
                        if !haystack_value.search(
                            &needle_key[index + 1..],
                            match_sequence,
                            hit,
                            cur_generation,
                        ) {
                            return false;
                        }
                        match_sequence.restore(restore);
                        true
                    })
                })
            }
            //compile_error!("Support wildcards");
            TrieNode::Tail {
                tail,
                value: Some(value),
                generation,
            } => {
                if *generation == cur_generation {
                    return true;
                }

                #[inline]
                fn search_tail<'a, V, M: MatchSequenceCollector>(
                    key: &[u8],
                    tail: &[TrieKey],
                    match_sequence: &mut M,
                    hit: &'_ mut impl FnMut(&'a V, &'_ M) -> bool,
                    value: &'a V,
                    generation: &mut u64,
                    cur_generation: u64,
                ) -> bool {
                    if *generation == cur_generation {
                        return true;
                    }
                    if tail.is_empty() {
                        *generation = cur_generation;
                        hit(value, match_sequence);
                    } else if let Some(needle) = tail.first().cloned()
                        && !needle.match_index(key, |index| -> bool {
                            if *generation == cur_generation {
                                return true;
                            }
                            let saved = match_sequence.save();
                            match_sequence.add(index as u32);
                            let tail = &tail[1..];
                            if tail.is_empty() {
                                *generation = cur_generation;
                                if !hit(value, match_sequence) {
                                    return false;
                                }
                            } else {
                                let key = &key[index + 1..];
                                search_tail(
                                    key,
                                    tail,
                                    match_sequence,
                                    hit,
                                    value,
                                    generation,
                                    cur_generation,
                                );
                            }
                            match_sequence.restore(saved);
                            true
                        }) {
                            return false;
                        }
                    true
                }
                search_tail(
                    needle_key,
                    tail,
                    match_sequence,
                    &mut *hit,
                    value,
                    generation,
                    cur_generation,
                )
            }
            _ => {true}
        }
    }

    #[allow(unused)]
    pub fn get(&self, key: &[TrieKey]) -> Option<&V> {
        if key.is_empty() {
            return if let TrieNode::Head { value, .. } = self {
                value.as_ref()
            } else if let TrieNode::Tail {
                tail,
                value: Some(value),
                ..
            } = self
            {
                tail.is_empty().then_some(value)
            } else {
                None
            };
        }
        match self {
            TrieNode::Empty => None,
            TrieNode::Head { map, .. } => {
                if let Some(val) = map.get(key[0]) {
                    val.get(&key[1..])
                } else {
                    None
                }
            }
            TrieNode::Tail {
                tail,
                value: Some(value),
                ..
            } => (key == tail).then_some(value),
            TrieNode::Tail { value: None, .. } => None,
        }
    }

    pub fn push(&mut self, key: &[TrieKey], new_value: V) -> bool {
        if let TrieNode::Tail {
            tail,
            value,
            ..
        } = self
        {
            if tail == key {
                return false;
            }
            let old_tail = std::mem::take(tail);
            let old_value = value.take().unwrap();
            *self = TrieNode::Head {
                map: Box::new(TinyMap::new()),
                value: None,
                generation: 0
            };
            _ = self.push(&old_tail, old_value);
        }
        if let TrieNode::Empty = self {
            *self = TrieNode::Tail {
                tail: key.to_vec(),
                value: Some(new_value),
                generation: 0
            };
            return true;
        }
        if let TrieNode::Head {
            map,
            value,
            ..
        } = self
        {
            if key.is_empty() {
                if value.is_some() {
                    false
                } else {
                    *value = Some(new_value);
                    true
                }
            } else {
                let next = key[0];
                if let Some(child) = map.get_mut(next) {
                    child.push(&key[1..], new_value)
                } else {
                    map.insert(
                        next,
                        TrieNode::Tail {
                            tail: key[1..].to_vec(),
                            value: Some(new_value),
                            generation: 0
                        },
                    );
                    true
                }
            }
        } else {
            unreachable!();
        }
    }
}
impl<V> Trie<V> {
    pub fn new() -> Trie<V> {
        Self {
            top: TrieNode::Empty,
            generation: AtomicU64::new(1),
            match_sequence: Default::default(),
        }
    }
    #[allow(unused)]
    pub fn get(&self, key: &str) -> Option<&V> {
        let key = TrieKey::exact(key);
        self.top.get(&key)
    }

    pub fn search_fn(&mut self, key: &str, mut hit: impl FnMut(&V, &MatchSequence) -> bool) {
        let generation = self.generation.fetch_add(1, Ordering::Relaxed)+1;
        self.match_sequence.clear();
        self.top.search(
            key.as_bytes(),
            &mut self.match_sequence,
            &mut hit,
            generation,
        );
    }
    pub fn search_fn_fast(&mut self, key: &str, mut hit: impl FnMut(&V), max_hits: usize) {
        let generation = self.generation.fetch_add(1, Ordering::Relaxed)+1;
        let mut hit_count = 0;
        self.top.search(
            key.as_bytes(),
            &mut DummyMatchSequenceCollector,
            &mut |v,_|{
                hit(v);
                hit_count += 1;
                hit_count < max_hits
            },
            generation,
        );
    }
    pub fn push(&mut self, key: &[TrieKey], value: V) {
        self.top.push(key, value);
    }
    #[allow(unused)]
    pub fn push_exact(&mut self, key: &str, value: V) {
        let key = TrieKey::exact(key);
        self.top.push(&key, value);
    }
}

#[cfg(test)]
mod tests {
    use super::{TinyMap, Trie};
    use crate::Fingerprint;

    fn verify_matches(needles: &[&str], haystack: &str) {
        let mut trie = Trie::new();
        for needle in needles {
            let fp = Fingerprint::parse(&needle);
            trie.push(&fp.0, true);
        }
        println!("Trie:\n{:#?}", trie);
        let mut hit = false;
        trie.search_fn(haystack, |v, _ms| {
            if *v {
                hit = true;
            }
            true
        });
        assert!(hit);
    }

    #[test]
    fn trie_test1() {
        verify_matches(&["a", "b"], "abcd");
    }
    #[test]
    fn trie_test2() {
        verify_matches(&["0", "1"], "0");
    }

    #[test]
    fn tiny_map_test() {
        let mut t = TinyMap::new();
        t.insert(1, 2);
        t.insert(1, 3);
        assert_eq!(t.get(1), Some(&2));
        t.insert(2, 22);
        t.remove(1);
        assert_eq!(t.get(1), None);
        assert_eq!(t.get(2), Some(&22));
    }
    #[test]
    fn tiny_map_test2() {
        let mut t = TinyMap::new();
        for i in 0..20 {
            t.insert(i, i);
        }
        for i in 0..20 {
            assert_eq!(t.get(i), Some(&i));
        }
    }

    #[test]
    fn simple_trie_test() {
        let mut trie = Trie::new();

        trie.push_exact("hej", 42);
        trie.push_exact("hejsansvejsan", 42);
        trie.push_exact("hes", 43);
        assert_eq!(trie.get("hej"), Some(&42));
        assert_eq!(trie.get("hes"), Some(&43));
        assert_eq!(trie.get("hejsansvejsan"), Some(&42));
    }

    #[test]
    fn simple_trie_test2() {
        let mut trie = Trie::new();

        trie.push_exact("hj", 1);
        trie.push_exact("hs", 2);
        trie.push_exact("ht", 3);
        trie.push_exact("åäö", 3);
        trie.push_exact("hlgnstd", 4);
    }
}