Skip to main content

micromegas_analytics/
scope.rs

1use datafusion::parquet::data_type::AsBytes;
2use std::sync::Arc;
3use xxhash_rust::xxh32::xxh32;
4
5/// A description of a scope, including its name, location, and hash.
6#[derive(Debug)]
7pub struct ScopeDesc {
8    pub name: Arc<String>,
9    pub filename: Arc<String>,
10    pub target: Arc<String>,
11    pub line: u32,
12    pub hash: u32,
13}
14
15/// A hash map of scope descriptions, keyed by their hash.
16pub type ScopeHashMap = std::collections::HashMap<u32, ScopeDesc>;
17
18impl ScopeDesc {
19    pub fn new(name: Arc<String>, filename: Arc<String>, target: Arc<String>, line: u32) -> Self {
20        let hash = compute_scope_hash(&name, &filename, &target, line);
21        Self {
22            name,
23            filename,
24            target,
25            line,
26            hash,
27        }
28    }
29}
30
31/// A borrowed scope description handed to block processors per event.
32///
33/// Borrows the parse arena, so it costs no allocation to construct; the owning
34/// [`ScopeDesc`] is materialized only when a scope is first inserted into a
35/// long-lived [`ScopeHashMap`] (once per distinct scope, not per event).
36#[derive(Debug, Clone, Copy)]
37pub struct BorrowedScopeDesc<'a> {
38    pub name: &'a str,
39    pub filename: &'a str,
40    pub target: &'a str,
41    pub line: u32,
42    pub hash: u32,
43}
44
45impl<'a> BorrowedScopeDesc<'a> {
46    pub fn new(name: &'a str, filename: &'a str, target: &'a str, line: u32) -> Self {
47        let hash = compute_scope_hash(name, filename, target, line);
48        Self {
49            name,
50            filename,
51            target,
52            line,
53            hash,
54        }
55    }
56
57    /// Materializes an owned `ScopeDesc` (allocates the strings).
58    pub fn to_owned(self) -> ScopeDesc {
59        ScopeDesc {
60            name: Arc::new(self.name.to_owned()),
61            filename: Arc::new(self.filename.to_owned()),
62            target: Arc::new(self.target.to_owned()),
63            line: self.line,
64            hash: self.hash,
65        }
66    }
67}
68
69/// Computes the hash of a scope.
70pub fn compute_scope_hash(name: &str, filename: &str, target: &str, line: u32) -> u32 {
71    let hash_name = xxh32(name.as_bytes(), 0);
72    let hash_with_filename = xxh32(filename.as_bytes(), hash_name);
73    let hash_with_target = xxh32(target.as_bytes(), hash_with_filename);
74    xxh32(line.as_bytes(), hash_with_target)
75}