memscope_rs/mem_ctx.rs
1use std::ops::Deref;
2use std::sync::Arc;
3
4use crate::auto_export::MemScopeConfig;
5use crate::capture::backends::global_tracking::GlobalTracker;
6use crate::guard::MemScopeGuard;
7
8/// Convenience session handle — one-call init, `track!`-able, one-call export.
9///
10/// # Examples
11///
12/// ```ignore
13/// use memscope_rs::prelude::*;
14///
15/// let ctx = MemCtx::init()?;
16/// let data = vec![1u64; 100];
17/// track!(ctx, data); // macro auto-derefs to GlobalTracker
18/// ctx.export("./report")?; // delegate to GlobalTracker::export_html
19/// ```
20pub struct MemCtx {
21 tracker: Arc<GlobalTracker>,
22}
23
24impl MemCtx {
25 /// Initialise logging + global tracking in one call.
26 pub fn init() -> crate::MemScopeResult<Self> {
27 crate::init_logging()?;
28 crate::capture::backends::global_tracking::init_global_tracking()?;
29 let tracker = crate::global_tracker()?;
30 Ok(Self { tracker })
31 }
32
33 /// One-line start with the default configuration.
34 ///
35 /// Equivalent to [`MemCtx::start_with`]`(MemScopeConfig::default())`. The
36 /// returned [`MemScopeGuard`] triggers the exit-path export (HTML + JSON
37 /// to `./memscope-report`) on drop, covering normal return, panic, and —
38 /// when the `auto-signal` feature is enabled — Ctrl-C.
39 ///
40 /// This is the recommended entry point for new code. Existing code that
41 /// calls [`MemCtx::init`] + [`MemCtx::export`] continues to work unchanged.
42 ///
43 /// # Errors
44 ///
45 /// Returns [`MemScopeError`](crate::MemScopeError) if logging init, global
46 /// tracker init, or lifecycle hook installation fails.
47 pub fn start() -> crate::MemScopeResult<MemScopeGuard> {
48 crate::guard::start()
49 }
50
51 /// One-line start with a custom [`MemScopeConfig`].
52 ///
53 /// Like [`MemCtx::start`] but accepts a user-supplied configuration for
54 /// output path, formats, signal policy, and periodic flush interval.
55 /// The returned [`MemScopeGuard`] owns the optional background flusher
56 /// and triggers the exit-path export on drop.
57 ///
58 /// # Errors
59 ///
60 /// Returns [`MemScopeError`](crate::MemScopeError) if any of the setup
61 /// steps fails. A repeated call without `reset_global_tracking` fails at
62 /// the global-tracker init step.
63 pub fn start_with(config: MemScopeConfig) -> crate::MemScopeResult<MemScopeGuard> {
64 crate::guard::start_with(config)
65 }
66
67 /// Export complete dashboard (HTML + JSON) under `path`.
68 pub fn export(&self, path: impl AsRef<std::path::Path>) -> crate::MemScopeResult<()> {
69 self.tracker.export_html(path)
70 }
71}
72
73impl Deref for MemCtx {
74 type Target = GlobalTracker;
75 fn deref(&self) -> &Self::Target {
76 &self.tracker
77 }
78}