pool_machines 0.1.3 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.1](https://github.com/seuros/pool_machines/compare/pool-machines-v0.5.0...pool-machines-v0.5.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * drop slot indexing and name the real class in handle TypeErrors ([f17e7bb](https://github.com/seuros/pool_machines/commit/f17e7bbb58f6f5f4cb3047895cb554b7f2cbb0ca))
9
+
10
+ ## [0.5.0](https://github.com/seuros/pool_machines/compare/pool-machines-v0.4.0...pool-machines-v0.5.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * adopt matryona-machines 0.2 (Class::pin, exact_typed, symbols!)
16
+
17
+ ### Features
18
+
19
+ * adopt matryona-machines 0.2 (Class::pin, exact_typed, symbols!) ([46a30f5](https://github.com/seuros/pool_machines/commit/46a30f5f8e7e2ed55852af8a510e036bf2b0904f))
20
+
21
+ ## [0.4.0](https://github.com/seuros/pool_machines/compare/pool-machines-v0.3.0...pool-machines-v0.4.0) (2026-11-14)
22
+
23
+
24
+ ### ⚠ BREAKING CHANGES
25
+
26
+ * drop flow-machines, record no clock on a retiring checkin, Handle sealed, resolved at load and checked by exact class
27
+
28
+ ### Features
29
+
30
+ * drop flow-machines, record no clock on a retiring checkin, Handle sealed, resolved at load and checked by exact class ([0af2455](https://github.com/seuros/pool_machines/commit/0af2455e73f0279d0c5bdcd8473f489633ae0ae3))
31
+
32
+ ## [0.3.0](https://github.com/seuros/pool_machines/compare/pool-machines-v0.2.2...pool-machines-v0.3.0) (2026-11-13)
33
+
34
+
35
+ ### ⚠ BREAKING CHANGES
36
+
37
+ * converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. Requires flow-machines >= 0.3. Handles are issued through periscope-machines; Ruby answers symbols and no longer raises on a stale handle.
38
+
39
+ ### Features
40
+
41
+ * one Refusal, scoped handles, and refusals that leave the clock alone ([f9e176a](https://github.com/seuros/pool_machines/commit/f9e176ae029835068e43bf4af75c3967fea56545))
42
+
3
43
  ## [0.2.2](https://github.com/seuros/pool_machines/compare/pool-machines-v0.2.1...pool-machines-v0.2.2) (2026-11-06)
4
44
 
5
45
 
@@ -1,15 +1,17 @@
1
1
  [package]
2
2
  name = "pool-machines"
3
- version = "0.2.2"
3
+ version = "0.5.1"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
7
7
  description = "Bounded resource-slot checkout, recycling, and draining"
8
8
  readme = "README.md"
9
- exclude = ["src/**/tests.rs", "tests/"]
9
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
10
10
  keywords = ["pool", "resource-pool", "draining", "no-std"]
11
11
  categories = ["no-std", "algorithms", "concurrency"]
12
12
  [dependencies]
13
- flow-machines.workspace = true
13
+ periscope-machines.workspace = true
14
+ [dev-dependencies]
15
+ matryona-machines = { workspace = true, features = ["testing"] }
14
16
  [lints]
15
17
  workspace = true
@@ -5,14 +5,106 @@
5
5
  Engine-room flight manual: track resource checkouts, returns, and retirement.
6
6
 
7
7
  Allocation-free `no_std` lifecycle decisions for fixed resource slots.
8
- Register externally created resources, check out the oldest idle slot, and return
9
- it with a generation-checked handle. Duplicate/stale returns are rejected.
8
+ Register externally created resources, check out the slot that has been idle
9
+ longest, and return it with the `Handle` the checkout issued. A handle is good
10
+ for one `checkin`; a spent, foreign or forged one is refused as `Stale`.
10
11
  Begin draining to refuse new checkouts; returned resources then retire rather
11
12
  than becoming idle. Idle retirement frees a slot for external destruction.
12
13
 
13
- Clock observations must not regress. Generations fail closed at exhaustion.
14
- Handles are scoped to one pool instance/lifetime; do not exchange handles between
15
- pools. The adapter must serialize these decisions with resource storage and
16
- actually destroy retired resources. There is no automatic construction, health
17
- check, async waiting, timeout driver, forced reclamation of busy resources,
18
- or runtime ownership guarantee.
14
+ The adapter must serialize these decisions with resource storage and actually
15
+ destroy retired resources. There is no automatic construction, health check,
16
+ async waiting, timeout driver, forced reclamation of busy resources, or
17
+ runtime ownership guarantee.
18
+
19
+ ```rust
20
+ use core::time::Duration;
21
+ use pool_machines::{DrainBegin, Pool, Refusal, Registration, Returned};
22
+
23
+ let at = Duration::from_secs;
24
+ let mut pool = Pool::<2>::with_scope(7).expect("two slots");
25
+ assert_eq!(pool.register(0, at(1)), Ok(Registration::Registered));
26
+ assert_eq!(pool.register(0, at(1)), Ok(Registration::AlreadyIdle));
27
+ assert_eq!(pool.register(2, at(1)), Err(Refusal::UnknownSlot));
28
+
29
+ let handle = pool.checkout(at(2)).expect("honoured").expect("slot 0 is idle");
30
+ assert_eq!((handle.slot(), handle.scope()), (0, 7));
31
+ assert_eq!(pool.checkout(at(2)), Ok(None));
32
+ assert_eq!(pool.checkin(handle, at(1)), Err(Refusal::TimeRegression));
33
+ assert_eq!(pool.checkin(handle, at(3)), Ok(Returned::Idle));
34
+ assert_eq!(pool.checkin(handle, at(3)), Err(Refusal::Stale));
35
+
36
+ assert_eq!(pool.retire_idle(at(4), at(60)), Ok(None));
37
+ assert_eq!(pool.begin_drain(), DrainBegin::Begun);
38
+ assert_eq!(pool.checkout(at(4)), Err(Refusal::Draining));
39
+ assert_eq!(pool.retire_idle(at(4), at(60)), Ok(Some(0)));
40
+
41
+ // Another pool, another scope: it refuses a handle it did not issue.
42
+ let mut other = Pool::<2>::with_scope(8).expect("two slots");
43
+ assert_eq!(other.checkin(handle, at(0)), Err(Refusal::Stale));
44
+ ```
45
+
46
+ ## Contract
47
+
48
+ - **Capacity.** `Pool<N>` holds `N` slots, `1..=u32::MAX`; the constructors
49
+ answer `None` otherwise. Each slot is vacant, idle since an instant, or busy
50
+ under one handle. `capacity()` is `N`; `checked_out()` counts busy slots.
51
+ - **Refusals.** `Refusal` is the crate's one refusal type and a refused call
52
+ changes nothing: not a slot, not an issued id, not
53
+ the observed clock. `register` answers `Draining`, `TimeRegression`,
54
+ `UnknownSlot` or `Busy`, checked in that order; `checkout` answers
55
+ `Draining`, `TimeRegression` or `Exhausted`; `checkin` answers `Stale` or
56
+ `TimeRegression`; `retire_idle` answers `TimeRegression`. `begin_drain`
57
+ never refuses.
58
+ - **Drains.** `checkout` and `retire_idle` return `Result<Option<_>, Refusal>`.
59
+ `Ok(None)` is an honoured answer, "nothing is idle at `now`" and "nothing is
60
+ old enough at `now`", not a refusal.
61
+ - **Time.** Instants and spans are `core::time::Duration` since an epoch the
62
+ caller picks. The pool keeps the latest instant an honoured call showed it
63
+ and refuses an earlier one as `TimeRegression`. Time is checked without
64
+ being recorded: only an honoured call moves the clock, and only one whose
65
+ answer depends on `now` (table below). The two drain
66
+ answers are honoured calls about `now`, so they record it, `Ok(None)`
67
+ included; a refusal never does.
68
+ - **Repeats.** `register` on a slot that already holds an idle resource
69
+ answers `Registration::AlreadyIdle`, and `begin_drain` on a draining pool
70
+ answers `DrainBegin::AlreadyDraining`: the effect asked for holds, the pool
71
+ can see it, and nothing changes (not the instant the slot went idle, not
72
+ the clock). A repeated `checkin` is **not** honoured: the pool keeps nothing
73
+ about a checkout once it is returned, so the repeat is `Stale` like any
74
+ other handle that names no live checkout.
75
+ - **Ids.** A `Handle` carries its slot and an id from one
76
+ `periscope_machines::Issuer`: the pool's scope in the top 16 bits, a
77
+ sequence counted from one below. An id is never reissued, so a spent handle
78
+ stays `Stale` after its slot is checked out again. A checkout refused for
79
+ any reason consumes no id. After `periscope_machines::SEQUENCE_MAX`
80
+ (2^48 - 1) checkouts `checkout` answers `Exhausted`.
81
+ - **Scopes.** A handle is only meaningful to the pool that issued it.
82
+ `Pool::with_scope(scope)` chooses the scope; `new()` is scope zero.
83
+ `Pool::scope` and `Handle::scope` read it. A handle of another scope, or one
84
+ the pool never issued, is `Stale` before any slot is read. Give each pool
85
+ its own scope: the core reads no clock and no random source, so it cannot
86
+ pick one, and two pools left in the same scope issue the same handles.
87
+ - **Restarts.** A fresh pool counts from one again, so a handle that outlived
88
+ a restart could name a new checkout. Save `Pool::issued` and rebuild with
89
+ `Pool::resumed(scope, issued)`, or give each incarnation a new scope.
90
+ `resumed` takes the scope explicitly and restores only the handle sequence:
91
+ every slot is vacant, the clock starts over, every earlier handle is
92
+ `Stale`, and registering the resources again is the caller's job. It is
93
+ `None` when `issued` is beyond `SEQUENCE_MAX`.
94
+ - **Checkout accounting.** The slots are the only record: `checked_out()`
95
+ counts the busy ones, so there is no second count to drift from them and
96
+ no invariant arm. The core has no dependency besides `periscope-machines`,
97
+ and it never panics.
98
+ - **Which answers record the clock.** An honoured answer records `now`
99
+ exactly when it depends on `now`:
100
+
101
+ | Call | Records `now` |
102
+ | --- | --- |
103
+ | `register` | `Registered` does (the slot is idle since `now`); `AlreadyIdle` does not, it holds whatever the time |
104
+ | `checkout` | always when honoured: `Some(handle)` picks the slot idle longest at `now`, `None` says nothing is idle at `now` |
105
+ | `checkin` | `Idle` does (the slot is idle since `now`); `Retire` does not, retiring holds whatever the time |
106
+ | `retire_idle` | always when honoured: `Some(slot)` and `None` are both about what is old enough at `now` |
107
+ | `begin_drain` | takes no time and records none |
108
+
109
+ The Ruby gem mirrors `Handle` and `Pool` under the same names; unit variants
110
+ are symbols and times are Integer nanoseconds.
@@ -1,172 +1,332 @@
1
1
  #![no_std]
2
2
  #![doc = include_str!("../README.md")]
3
- use core::{num::NonZeroU32, time::Duration};
4
- use flow_machines::CreditWindow;
3
+ #![cfg_attr(not(test), deny(clippy::indexing_slicing))]
4
+
5
+ #[cfg(test)]
6
+ extern crate std;
7
+
8
+ mod refusal;
9
+
10
+ use core::time::Duration;
11
+
12
+ use periscope_machines::{Issuer, scope_of};
13
+
14
+ pub use refusal::Refusal;
5
15
 
6
16
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
7
17
  enum Slot {
8
18
  Vacant,
19
+ /// Idle since the instant it was registered or checked in.
9
20
  Idle(Duration),
21
+ /// Checked out under the handle id it carries.
10
22
  Busy(u64),
11
23
  }
12
24
 
13
- /// Generation-checked handle within one pool lifetime.
25
+ /// One checkout: the slot it borrowed and the scoped id it was issued under.
26
+ ///
27
+ /// Only the pool that issued it honours it, and only once: an id is never
28
+ /// reissued, so a handle that was checked in is [`Refusal::Stale`] forever,
29
+ /// also after its slot is checked out again.
14
30
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
31
  pub struct Handle {
16
32
  slot: usize,
17
- generation: u64,
33
+ /// Scoped id from the pool's issuer.
34
+ key: u64,
18
35
  }
36
+
19
37
  impl Handle {
20
38
  /// Resource slot to retrieve from caller-owned storage.
21
39
  #[must_use]
22
40
  pub const fn slot(self) -> usize {
23
41
  self.slot
24
42
  }
43
+
44
+ /// The scope of the pool that issued this handle, see [`Pool::with_scope`].
45
+ #[must_use]
46
+ pub const fn scope(self) -> u16 {
47
+ scope_of(self.key)
48
+ }
25
49
  }
26
50
 
27
- /// Check-in disposition for the resource adapter.
51
+ /// Honoured outcome of [`Pool::register`].
52
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
53
+ pub enum Registration {
54
+ /// The vacant slot now holds an idle resource.
55
+ Registered,
56
+ /// An idempotent repeat: the slot already holds an idle resource. Nothing
57
+ /// changed, not the instant it went idle and not the observed clock.
58
+ AlreadyIdle,
59
+ }
60
+
61
+ /// Honoured outcome of [`Pool::checkin`]: what the adapter does with the resource.
28
62
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29
- #[non_exhaustive]
30
63
  pub enum Returned {
31
64
  /// Retain the resource for another checkout.
32
65
  Idle,
33
- /// Destroy the resource; the pool is draining.
66
+ /// Destroy the resource; the pool is draining and the slot is vacant.
34
67
  Retire,
35
- /// Invalid handle or clock; state was not changed.
36
- Rejected,
37
68
  }
38
69
 
39
- /// Slot lifecycle plus bounded checkout accounting.
40
- #[derive(Debug)]
70
+ /// Honoured outcome of [`Pool::begin_drain`].
71
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
72
+ pub enum DrainBegin {
73
+ /// The pool is now draining.
74
+ Begun,
75
+ /// An idempotent repeat: the pool was already draining. Nothing changed.
76
+ AlreadyDraining,
77
+ }
78
+
79
+ /// Slot lifecycle: each slot is vacant, idle, or checked out.
80
+ #[derive(Debug, Clone, PartialEq, Eq)]
41
81
  pub struct Pool<const N: usize> {
42
82
  slots: [Slot; N],
43
- credits: CreditWindow,
44
- generation: u64,
83
+ issuer: Issuer,
45
84
  observed: Duration,
46
85
  draining: bool,
47
86
  }
87
+
48
88
  impl<const N: usize> Pool<N> {
49
- /// Construct a pool with `1..=u32::MAX` initially vacant slots.
89
+ /// A pool of `N` vacant slots in scope zero, with no handle issued.
90
+ ///
91
+ /// `None` unless `N` is in `1..=u32::MAX`.
50
92
  #[must_use]
51
93
  pub fn new() -> Option<Self> {
52
- let Ok(count) = u32::try_from(N) else {
94
+ Self::with_scope(0)
95
+ }
96
+
97
+ /// A pool of `N` vacant slots whose handles carry `scope`.
98
+ ///
99
+ /// Handles are only meaningful to the pool that issued them. Two pools in
100
+ /// the same scope issue the same handle ids, so give every pool whose
101
+ /// handles could meet its own scope. `None` unless `N` is in `1..=u32::MAX`.
102
+ #[must_use]
103
+ pub fn with_scope(scope: u16) -> Option<Self> {
104
+ Self::build(Issuer::new(scope))
105
+ }
106
+
107
+ /// A pool that continues `scope` after a restart: `issued` is what
108
+ /// [`Pool::issued`] answered when the caller saved it.
109
+ ///
110
+ /// Only the handle sequence is restored. Every slot is vacant, the clock
111
+ /// starts over, and every handle issued before the restart is
112
+ /// [`Refusal::Stale`]; registering the resources again is the caller's
113
+ /// job. The next handle carries sequence `issued + 1`, so none is reissued
114
+ /// as long as the saved count is not lower than what was really issued:
115
+ /// save it before handing a handle out.
116
+ ///
117
+ /// `None` unless `N` is in `1..=u32::MAX`, and when `issued` is beyond
118
+ /// `periscope_machines::SEQUENCE_MAX`, which no pool reaches.
119
+ #[must_use]
120
+ pub fn resumed(scope: u16, issued: u64) -> Option<Self> {
121
+ Self::build(Issuer::resumed(scope, issued)?)
122
+ }
123
+
124
+ /// `N` is in `1..=u32::MAX`, so [`Pool::checked_out`] always fits a `u32`.
125
+ fn build(issuer: Issuer) -> Option<Self> {
126
+ if !u32::try_from(N).is_ok_and(|count| count > 0) {
53
127
  return None;
54
- };
128
+ }
55
129
  Some(Self {
56
130
  slots: [Slot::Vacant; N],
57
- credits: CreditWindow::new(NonZeroU32::new(count)?),
58
- generation: 0,
131
+ issuer,
59
132
  observed: Duration::ZERO,
60
133
  draining: false,
61
134
  })
62
135
  }
63
136
 
64
- /// Register an externally created resource into a vacant slot.
137
+ /// The scope carried by every handle this pool issues.
138
+ #[must_use]
139
+ pub const fn scope(&self) -> u16 {
140
+ self.issuer.scope()
141
+ }
142
+
143
+ /// Handles issued in this scope so far, live or not: the count to save
144
+ /// for [`Pool::resumed`].
145
+ #[must_use]
146
+ pub const fn issued(&self) -> u64 {
147
+ self.issuer.issued()
148
+ }
149
+
150
+ /// Compiled slot count `N`.
151
+ #[must_use]
152
+ pub const fn capacity(&self) -> usize {
153
+ N
154
+ }
155
+
156
+ /// Number of outstanding checkouts: the busy slots. O(N).
157
+ #[must_use]
158
+ pub fn checked_out(&self) -> u32 {
159
+ let busy = self
160
+ .slots
161
+ .iter()
162
+ .filter(|state| matches!(state, Slot::Busy(_)))
163
+ .count();
164
+ // Every constructor holds N to `1..=u32::MAX`, so the count fits.
165
+ u32::try_from(busy).unwrap_or(u32::MAX)
166
+ }
167
+
168
+ /// Whether [`Pool::begin_drain`] was called.
65
169
  #[must_use]
66
- pub fn register(&mut self, slot: usize, now: Duration) -> bool {
67
- if self.draining || now < self.observed {
68
- return false;
170
+ pub const fn is_draining(&self) -> bool {
171
+ self.draining
172
+ }
173
+
174
+ /// Register an externally created resource into a vacant slot, idle since `now`.
175
+ ///
176
+ /// Answers [`Registration::AlreadyIdle`] when the slot already holds an
177
+ /// idle resource: the effect asked for holds and the slot proves it, so
178
+ /// the repeat is honoured and changes nothing.
179
+ ///
180
+ /// # Errors
181
+ ///
182
+ /// Checked in this order: [`Refusal::Draining`], [`Refusal::TimeRegression`],
183
+ /// [`Refusal::UnknownSlot`] for an index of `N` or more, and
184
+ /// [`Refusal::Busy`] when the slot's resource is checked out.
185
+ pub fn register(&mut self, slot: usize, now: Duration) -> Result<Registration, Refusal> {
186
+ if self.draining {
187
+ return Err(Refusal::Draining);
69
188
  }
70
- let Some(state) = self.slots.get_mut(slot) else {
71
- return false;
72
- };
73
- if *state != Slot::Vacant {
74
- return false;
189
+ self.check_time(now)?;
190
+ match self.slots.get_mut(slot) {
191
+ None => Err(Refusal::UnknownSlot),
192
+ Some(Slot::Busy(_)) => Err(Refusal::Busy),
193
+ Some(Slot::Idle(_)) => Ok(Registration::AlreadyIdle),
194
+ Some(state @ Slot::Vacant) => {
195
+ *state = Slot::Idle(now);
196
+ self.observed = now;
197
+ Ok(Registration::Registered)
198
+ }
75
199
  }
76
- self.observed = now;
77
- *state = Slot::Idle(now);
78
- true
79
200
  }
80
201
 
81
- /// Check out the oldest idle resource.
82
- pub fn checkout(&mut self, now: Duration) -> Option<Handle> {
83
- if self.draining || !self.observe(now) {
84
- return None;
202
+ /// Check out the resource that has been idle longest, lowest slot first
203
+ /// among equals.
204
+ ///
205
+ /// A drain over the idle slots: `None` is the honoured answer "nothing is
206
+ /// idle at `now`". Honoured either way, so `now` is recorded as observed
207
+ /// either way and an earlier instant is refused afterwards.
208
+ ///
209
+ /// # Errors
210
+ ///
211
+ /// [`Refusal::Draining`], [`Refusal::TimeRegression`], or
212
+ /// [`Refusal::Exhausted`] when a resource is idle but all
213
+ /// `periscope_machines::SEQUENCE_MAX` (2^48 - 1) handle ids of the pool's
214
+ /// scope have been issued. A refusal records nothing, `now` included.
215
+ pub fn checkout(&mut self, now: Duration) -> Result<Option<Handle>, Refusal> {
216
+ if self.draining {
217
+ return Err(Refusal::Draining);
85
218
  }
86
- let slot = self
219
+ self.check_time(now)?;
220
+ let oldest = self
87
221
  .slots
88
- .iter()
222
+ .iter_mut()
89
223
  .enumerate()
90
- .filter_map(|(slot, state)| {
91
- if let Slot::Idle(since) = state {
92
- Some((slot, *since))
93
- } else {
94
- None
95
- }
224
+ .filter_map(|(slot, state)| match state {
225
+ Slot::Idle(since) => Some((*since, slot, state)),
226
+ Slot::Vacant | Slot::Busy(_) => None,
96
227
  })
97
- .min_by_key(|&(slot, since)| (since, slot))
98
- .map(|(slot, _)| slot)?;
99
- let generation = self.generation.checked_add(1)?;
100
- if !self.credits.try_acquire(NonZeroU32::MIN) {
101
- return None;
102
- }
103
- self.generation = generation;
104
- self.slots[slot] = Slot::Busy(generation);
105
- Some(Handle { slot, generation })
228
+ .min_by_key(|&(since, slot, _)| (since, slot));
229
+ let Some((_, slot, state)) = oldest else {
230
+ self.observed = now;
231
+ return Ok(None);
232
+ };
233
+ // Last check: an id is only spent on a checkout that is honoured.
234
+ let key = match self.issuer.issue() {
235
+ Ok(key) => key,
236
+ Err(periscope_machines::Refusal::Exhausted) => return Err(Refusal::Exhausted),
237
+ };
238
+ self.observed = now;
239
+ *state = Slot::Busy(key);
240
+ Ok(Some(Handle { slot, key }))
106
241
  }
107
242
 
108
243
  /// Return a live checkout, deciding whether to recycle or retire it.
109
244
  ///
110
- /// # Panics
111
- /// Panics if internal checkout accounting is inconsistent.
112
- #[must_use]
113
- pub fn checkin(&mut self, handle: Handle, now: Duration) -> Returned {
114
- if now < self.observed {
115
- return Returned::Rejected;
116
- }
117
- let Some(state) = self.slots.get_mut(handle.slot) else {
118
- return Returned::Rejected;
119
- };
120
- if *state != Slot::Busy(handle.generation) {
121
- return Returned::Rejected;
245
+ /// # Errors
246
+ ///
247
+ /// [`Refusal::Stale`] for a handle that names no live checkout here: one
248
+ /// already checked in, one of another scope, or one never issued (the
249
+ /// last two before any slot is read). A repeated `checkin` is never
250
+ /// honoured: the pool keeps nothing about a checkout once it is returned.
251
+ /// [`Refusal::TimeRegression`] for a live handle and an earlier `now`.
252
+ ///
253
+ /// [`Returned::Idle`] records `now`: the slot is idle since `now`.
254
+ /// [`Returned::Retire`] does not: retiring answers the same whatever the
255
+ /// time, so a later call may still show an instant before this one.
256
+ pub fn checkin(&mut self, handle: Handle, now: Duration) -> Result<Returned, Refusal> {
257
+ if !self.issuer.owns(handle.key) {
258
+ return Err(Refusal::Stale);
122
259
  }
123
- self.observed = now;
124
- assert!(self.credits.release(NonZeroU32::MIN));
125
- *state = if self.draining {
126
- Slot::Vacant
127
- } else {
128
- Slot::Idle(now)
260
+ // Judged before the slot is borrowed, answered after the stale check.
261
+ let time = self.check_time(now);
262
+ let state = match self.slots.get_mut(handle.slot) {
263
+ Some(state) if *state == Slot::Busy(handle.key) => state,
264
+ _ => return Err(Refusal::Stale),
129
265
  };
266
+ time?;
130
267
  if self.draining {
131
- Returned::Retire
268
+ // Retiring holds whatever the time: the clock is not recorded.
269
+ *state = Slot::Vacant;
270
+ Ok(Returned::Retire)
132
271
  } else {
133
- Returned::Idle
272
+ self.observed = now;
273
+ *state = Slot::Idle(now);
274
+ Ok(Returned::Idle)
134
275
  }
135
276
  }
136
277
 
137
- /// Stop future checkout/registration. Existing busy resources are not revoked.
138
- pub const fn begin_drain(&mut self) {
139
- self.draining = true;
140
- }
141
-
142
- /// Retire one idle resource old enough, or any idle resource when draining.
143
- pub fn retire_idle(&mut self, now: Duration, idle_for: Duration) -> Option<usize> {
144
- if !self.observe(now) {
145
- return None;
278
+ /// Stop future checkout and registration. Busy resources are not revoked.
279
+ ///
280
+ /// Never refuses. Repeating it answers [`DrainBegin::AlreadyDraining`].
281
+ pub const fn begin_drain(&mut self) -> DrainBegin {
282
+ if self.draining {
283
+ return DrainBegin::AlreadyDraining;
146
284
  }
147
- let slot = self.slots.iter().position(|state| match state {
148
- Slot::Idle(since) => {
149
- self.draining || now.checked_sub(*since).is_some_and(|age| age >= idle_for)
150
- }
151
- _ => false,
152
- })?;
153
- self.slots[slot] = Slot::Vacant;
154
- Some(slot)
285
+ self.draining = true;
286
+ DrainBegin::Begun
155
287
  }
156
288
 
157
- /// Number of outstanding checkouts.
158
- #[must_use]
159
- pub const fn checked_out(&self) -> u32 {
160
- self.credits.in_flight()
289
+ /// Retire one resource idle for at least `idle_for`, or any idle resource
290
+ /// when draining; lowest slot first. The slot is vacant afterwards.
291
+ ///
292
+ /// A drain: `None` is the honoured answer "nothing is old enough at
293
+ /// `now`". Honoured either way, so `now` is recorded as observed either
294
+ /// way and an earlier instant is refused afterwards.
295
+ ///
296
+ /// # Errors
297
+ ///
298
+ /// [`Refusal::TimeRegression`]; nothing is recorded.
299
+ pub fn retire_idle(
300
+ &mut self,
301
+ now: Duration,
302
+ idle_for: Duration,
303
+ ) -> Result<Option<usize>, Refusal> {
304
+ self.check_time(now)?;
305
+ self.observed = now;
306
+ let draining = self.draining;
307
+ let found = self
308
+ .slots
309
+ .iter_mut()
310
+ .enumerate()
311
+ .find(|(_, state)| match state {
312
+ Slot::Idle(since) => draining || now.saturating_sub(*since) >= idle_for,
313
+ Slot::Vacant | Slot::Busy(_) => false,
314
+ });
315
+ Ok(found.map(|(slot, state)| {
316
+ *state = Slot::Vacant;
317
+ slot
318
+ }))
161
319
  }
162
320
 
163
- fn observe(&mut self, now: Duration) -> bool {
164
- if now < self.observed {
165
- return false;
321
+ /// Time regression is checked without recording: `observed` moves only
322
+ /// when the call is honoured.
323
+ const fn check_time(&self, now: Duration) -> Result<(), Refusal> {
324
+ if now.as_nanos() < self.observed.as_nanos() {
325
+ return Err(Refusal::TimeRegression);
166
326
  }
167
- self.observed = now;
168
- true
327
+ Ok(())
169
328
  }
170
329
  }
330
+
171
331
  #[cfg(test)]
172
332
  mod tests;
@@ -0,0 +1,46 @@
1
+ use core::fmt;
2
+
3
+ /// Why a call was not honoured. A refused call changes nothing: not a slot,
4
+ /// not an issued handle id, not the observed clock.
5
+ ///
6
+ /// This is the crate's one refusal type. [`Pool::register`](crate::Pool::register)
7
+ /// answers [`Draining`](Self::Draining), [`TimeRegression`](Self::TimeRegression),
8
+ /// [`UnknownSlot`](Self::UnknownSlot) or [`Busy`](Self::Busy);
9
+ /// [`Pool::checkout`](crate::Pool::checkout) answers [`Draining`](Self::Draining),
10
+ /// [`TimeRegression`](Self::TimeRegression) or [`Exhausted`](Self::Exhausted);
11
+ /// [`Pool::checkin`](crate::Pool::checkin) answers [`Stale`](Self::Stale) or
12
+ /// [`TimeRegression`](Self::TimeRegression);
13
+ /// [`Pool::retire_idle`](crate::Pool::retire_idle) answers
14
+ /// [`TimeRegression`](Self::TimeRegression).
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
+ pub enum Refusal {
17
+ /// The pool is draining: it registers nothing and checks nothing out.
18
+ Draining,
19
+ /// `now` is earlier than the latest instant the pool observed.
20
+ TimeRegression,
21
+ /// The slot index is not one of the pool's `N` slots.
22
+ UnknownSlot,
23
+ /// The slot's resource is checked out, so nothing can be registered there.
24
+ Busy,
25
+ /// Every handle id of the pool's scope has been issued; none is reissued.
26
+ Exhausted,
27
+ /// The handle names no live checkout of this pool: already checked in,
28
+ /// issued by a pool of another scope, or never issued. The last two are
29
+ /// answered before any slot is looked at.
30
+ Stale,
31
+ }
32
+
33
+ impl fmt::Display for Refusal {
34
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35
+ f.write_str(match self {
36
+ Self::Draining => "the pool is draining",
37
+ Self::TimeRegression => "now is earlier than the observed clock",
38
+ Self::UnknownSlot => "slot index is not one of the pool's slots",
39
+ Self::Busy => "the slot's resource is checked out",
40
+ Self::Exhausted => "every handle id of this scope has been issued",
41
+ Self::Stale => "the handle names no live checkout of this pool",
42
+ })
43
+ }
44
+ }
45
+
46
+ impl core::error::Error for Refusal {}