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
/*<LICENSE>
    This file is part of Memthol.

    Copyright (C) 2020 OCamlPro.

    Memthol is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Memthol is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Memthol.  If not, see <https://www.gnu.org/licenses/>.
*/

//! Common imports for this crate.

pub use regex::Regex;

pub use base::prelude::{serde::*, *};

/// Re-exports from the `alloc_data` crate.
pub mod alloc {
    pub use alloc_data::prelude::*;
}

/// Re-exports from `plotters`'s `coord` module.
pub mod coord {
    pub use plotters::coord::{
        cartesian::Cartesian2d,
        ranged1d::{AsRangedCoord, Ranged, ValueFormatter},
        types::{RangedCoordf32, RangedCoordu32, RangedCoordu64, RangedDuration},
    };
}

pub use alloc::Alloc;

/// A window of time, for a graph.
pub type TimeWindow = Range<time::SinceStart>;
/// A window of time, for a graph.
pub type TimeWindopt = Range<Option<time::SinceStart>>;

/// Imports this crate's prelude.
macro_rules! prelude {
    () => {
        use $crate::prelude::*;
    };
}

base::cfg_item! {
    cfg(server) {
        pub use crate::{data, ChartExt};
    }
}

pub use crate::{
    chart::{self, settings},
    color::Color,
    filter::{self, Filter, Filters},
    msg,
    point::{self, Point, PointVal, Points},
};

/// Number pretty formatting.
pub mod num_fmt {
    /// Applies an action to a pretty string representation of a number.
    ///
    /// ```rust
    /// # use charts::prelude::num_fmt::*;
    /// let mut s = String::new();
    /// str_do(16_504_670, |pretty| s = pretty);
    /// assert_eq!(&s, "16.50M");
    ///
    /// str_do(670, |pretty| s = pretty);
    /// assert_eq!(&s, "670");
    ///
    /// str_do(1_052_504_670u32, |pretty| s = pretty);
    /// assert_eq!(&s, "1.05G");
    /// ```
    pub fn str_do<Res>(
        stuff: impl std::convert::TryInto<f64> + std::fmt::Display + Clone,
        action: impl FnOnce(String) -> Res,
    ) -> Res {
        use number_prefix::NumberPrefix::{self, *};
        let s = match stuff.clone().try_into().map(NumberPrefix::decimal) {
            Ok(Prefixed(pref, val)) => format!("{:.2}{}", val, pref),
            Err(_) | Ok(Standalone(_)) => stuff.to_string(),
        };
        action(s)
    }

    /// Applies an action to a pretty string representation of a number.
    ///
    /// ```rust
    /// # use charts::prelude::num_fmt::*;
    /// let mut s = String::new();
    /// str_do(16_504_670, |pretty| s = pretty);
    /// assert_eq!(&s, "16.50M");
    ///
    /// str_do(670, |pretty| s = pretty);
    /// assert_eq!(&s, "670");
    ///
    /// str_do(1_052_504_670u32, |pretty| s = pretty);
    /// assert_eq!(&s, "1.05G");
    /// ```
    pub fn bin_str_do<Res>(
        stuff: impl std::convert::TryInto<f64> + std::fmt::Display + Clone,
        action: impl FnOnce(String) -> Res,
    ) -> Res {
        use number_prefix::NumberPrefix::{self, *};
        let s = match stuff.clone().try_into().map(NumberPrefix::binary) {
            Ok(Prefixed(pref, val)) => format!("{:.2}{}", val, pref),
            Err(_) | Ok(Standalone(_)) => stuff.to_string(),
        };
        action(s)
    }
}

/// A set of allocation UIDs.
pub type AllocUidSet = BTSet<uid::Alloc>;

/// Dump-loading information.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoadInfo {
    /// Number of dumps loaded so far.
    pub loaded: usize,
    /// Total number of dumps.
    ///
    /// Can be `0`, in which case the progress is considered to be `0` as well.
    pub total: usize,
}
impl LoadInfo {
    /// Unknown info, `loaded` and `total` are set to `0`.
    pub fn unknown() -> Self {
        Self {
            loaded: 0,
            total: 0,
        }
    }
    /// Percent version of the progress.
    pub fn percent(&self) -> f64 {
        if self.total == 0 {
            0.
        } else {
            (self.loaded as f64) * 100. / (self.total as f64)
        }
    }
}

/// Allocation statistics.
///
/// Sent to the client so that it can display basic informations (run date, allocation count...).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AllocStats {
    /// Dump directory.
    pub dump_dir: std::path::PathBuf,
    /// Total number of allocations.
    pub alloc_count: usize,
    /// Total size of the allocations.
    pub total_size: u64,
    /// Date at which the run started.
    pub start_date: time::Date,
    /// Duration of the run.
    pub duration: time::SinceStart,
}
#[cfg(any(test, feature = "server"))]
impl AllocStats {
    /// Constructor.
    pub fn new(dump_dir: impl Into<std::path::PathBuf>, start_date: time::Date) -> Self {
        let dump_dir = dump_dir.into();
        // let dump_dir = dump_dir.canonicalize().unwrap_or(dump_dir);
        Self {
            dump_dir,
            alloc_count: 0,
            total_size: 0,
            start_date,
            duration: time::SinceStart::zero(),
        }
    }

    /// Allocation statistics accessor for the global data server-side.
    pub fn get() -> Res<Option<AllocStats>> {
        data::Data::get_stats()
    }
}