Use this guide to collect usage statistics when your tool builds many source
file maps. Everything on this page requires the default rt-feedback
feature. The context is lock-free: finalizing a map updates the counters
with atomic operations, so multiple maps and threads can report into the same
context without blocking.
Create a shared feedback context
Section titled “Create a shared feedback context”Create one RuntimeFeedback, wrap it in an Arc and hand it to the map:
use std::sync::Arc;
let feedback = Arc::new(RuntimeFeedback::new());
let mut files = SourceFilesMap::<u8>::with_feedback(Arc::clone(&feedback));files.add_file("a.rs", b"fn a() {}").expect("capacity available");files.finalize().expect("no capacity issue");Builders accept the same context through
SourceFilesBuilder::with_feedback.
Read a snapshot
Section titled “Read a snapshot”snapshot returns an immutable, Copy snapshot of the counters:
let snapshot = feedback.snapshot();
assert_eq!(snapshot.total_files, 1);assert_eq!(snapshot.total_bytes, 9);assert_eq!(snapshot.max_file_size, 9);assert_eq!(snapshot.usage_count, 1);The snapshot fields:
| Field | Meaning |
|---|---|
total_files |
Number of files registered by the last finalized map |
total_bytes |
Total content bytes registered by the last finalized map |
max_file_size |
Size in bytes of the largest file of the last finalized map |
usage_count |
Number of finalizations that reported into this context |
Report from multiple threads
Section titled “Report from multiple threads”The reporting path takes no locks, so threads only contend on atomic
instructions. Share the Arc across workers and read the counters whenever
you need them:
use std::sync::Arc;
let feedback = Arc::new(RuntimeFeedback::new());
let handles: Vec<_> = (0..4) .map(|i| { let feedback = Arc::clone(&feedback); std::thread::spawn(move || { let mut files = SourceFilesBuilder::<u8>::with_feedback(feedback); files .add_file(format!("{i}.rs"), b"fn x() {}") .expect("capacity available"); files.finalize().expect("no capacity issue"); }) }) .collect();
for handle in handles { handle.join().expect("worker finished");}
assert_eq!(feedback.snapshot().usage_count, 4);With the default serde feature, FeedbackSnapshot also implements
Serialize and Deserialize, so you can log or persist snapshots directly.
Next steps
Section titled “Next steps”- Follow for the registration API the counters observe.
- Check for the full
RuntimeFeedbackandFeedbackSnapshotsignatures.
