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
//! Pure admission state for one task's scheduler-visible perf counters.
/// Why a task perf context rejected a new counter.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PerfAttachError {
/// Task exit already tombstoned the context.
Closed,
/// The fixed scheduler-visible storage is full.
Full,
}
/// Lock-protected state shared by the task exit and event-open transactions.
pub(crate) struct PerfTaskContextState<T, const CAPACITY: usize> {
accepting: bool,
counters: heapless::Vec<T, CAPACITY>,
}
impl<T, const CAPACITY: usize> PerfTaskContextState<T, CAPACITY> {
/// Creates one live, empty task context.
pub(crate) const fn new() -> Self {
Self {
accepting: true,
counters: heapless::Vec::new(),
}
}
/// Publishes one counter while admission remains open.
pub(crate) fn attach(&mut self, counter: T) -> Result<(), PerfAttachError> {
if !self.accepting {
return Err(PerfAttachError::Closed);
}
self.counters
.push(counter)
.map_err(|_| PerfAttachError::Full)
}
/// Tombstones admission and returns every counter visible at that point.
pub(crate) fn close_snapshot(&mut self) -> heapless::Vec<T, CAPACITY>
where
T: Clone,
{
self.accepting = false;
self.counters.clone()
}
/// Returns a bounded snapshot without changing admission state.
pub(crate) fn snapshot(&self) -> heapless::Vec<T, CAPACITY>
where
T: Clone,
{
self.counters.clone()
}
/// Returns a bounded snapshot only while child inheritance is admissible.
pub(crate) fn snapshot_if_accepting(&self) -> Option<heapless::Vec<T, CAPACITY>>
where
T: Clone,
{
self.accepting.then(|| self.counters.clone())
}
/// Removes entries that no longer belong in the scheduler-visible set.
pub(crate) fn retain(&mut self, keep: impl FnMut(&T) -> bool) {
self.counters.retain(keep);
}
/// Removes one entry selected by an identity predicate.
pub(crate) fn remove(&mut self, matches: impl FnMut(&T) -> bool) -> bool {
let Some(index) = self.counters.iter().position(matches) else {
return false;
};
self.counters.swap_remove(index);
true
}
/// Borrows the fixed counter slice while its external lock is held.
pub(crate) fn counters(&self) -> &[T] {
self.counters.as_slice()
}
}