ferravex_play/
ability.rs

1//! Fixed-capacity ability charges, resource costs and cancellable reservations.
2//! Hosts own conditions and actual effects; no ability creates a hit or movement.
3//!
4//! [`AbilityBank::availability`] provides a read-only HUD/AI snapshot. Previewing
5//! never spends charges/resources, advances recharge, or creates a reservation.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum AbilityError {
8    Invalid,
9    Capacity,
10    Blocked,
11    Empty,
12    Resource,
13    Stale,
14}
15/// The first condition preventing a new reservation or immediate activation.
16///
17/// Conditions are checked in declaration order. A snapshot still exposes charges,
18/// costs and pending reservations when an earlier condition takes precedence.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum AbilityBlocker {
21    /// The host supplied `enabled = false`.
22    Disabled,
23    /// This slot already has an uncommitted, uncancelled reservation.
24    Busy,
25    /// No unreserved charges remain.
26    NoCharges,
27    /// The supplied resource pool cannot pay the cost.
28    InsufficientResource,
29    /// The bank has issued every possible reservation serial.
30    ReservationExhausted,
31}
32/// A value snapshot returned by [`AbilityBank::availability`].
33///
34/// This is advisory information, not a reservation: changing the bank, resource
35/// pool or host's enabled condition may change the next activation's result.
36/// See [`AbilityBank::availability`] for a compiling HUD/AI usage example.
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub struct AbilityAvailability {
39    /// Unreserved charges currently held by the slot.
40    pub charges: u8,
41    /// The slot's configured charge capacity.
42    pub max_charges: u8,
43    /// The same charge cooldown as [`AbilityBank::remaining`]: zero if any
44    /// charge remains. This is not a readiness guarantee; other blockers apply.
45    pub cooldown_remaining: f32,
46    /// Remaining simulation seconds on the next-charge timer, even if another
47    /// charge is available. Zero when full or when the first reservation has
48    /// not yet been committed. The timer is frozen while `reserved` is true.
49    pub recharge_remaining: f32,
50    /// Resource amount required for a new reservation.
51    pub resource_cost: f32,
52    /// Current value of the supplied pool, after any previous reservations.
53    pub resource_available: f32,
54    /// Whether this slot has a pending reservation, regardless of `blocker`.
55    pub reserved: bool,
56    /// First blocker, or `None` when a new reservation can succeed.
57    pub blocker: Option<AbilityBlocker>,
58}
59impl AbilityAvailability {
60    /// Convert this snapshot's blocker to the existing activation error.
61    ///
62    /// Both host-disabled and busy states map to [`AbilityError::Blocked`].
63    /// This only reads the snapshot; it never authorizes or performs an action.
64    ///
65    /// ```
66    /// use ferravex_play::ability::{AbilityBank, AbilityError, AbilitySpec, ResourcePool};
67    /// let bank = AbilityBank::<1>::new(1, &[AbilitySpec {
68    ///     charges: 1, recharge_seconds: 0.5, cost: 3.0,
69    /// }]).unwrap();
70    /// let pool = ResourcePool::new(2.0, 5.0, 0.0).unwrap();
71    /// let preview = bank.availability(0, &pool, true).unwrap();
72    /// assert_eq!(preview.check(), Err(AbilityError::Resource));
73    /// assert_eq!(pool.value(), 2.0);
74    /// ```
75    pub fn check(&self) -> Result<(), AbilityError> {
76        match self.blocker {
77            None => Ok(()),
78            Some(AbilityBlocker::Disabled | AbilityBlocker::Busy) => Err(AbilityError::Blocked),
79            Some(AbilityBlocker::NoCharges) => Err(AbilityError::Empty),
80            Some(AbilityBlocker::InsufficientResource) => Err(AbilityError::Resource),
81            Some(AbilityBlocker::ReservationExhausted) => Err(AbilityError::Capacity),
82        }
83    }
84}
85#[derive(Clone, Copy, Debug)]
86pub struct AbilitySpec {
87    pub charges: u8,
88    pub recharge_seconds: f32,
89    pub cost: f32,
90}
91#[derive(Clone, Copy, Debug)]
92pub struct ResourcePool {
93    value: f32,
94    maximum: f32,
95    regeneration: f32,
96}
97impl ResourcePool {
98    pub fn new(value: f32, maximum: f32, regeneration: f32) -> Result<Self, AbilityError> {
99        if ![value, maximum, regeneration]
100            .iter()
101            .all(|v| v.is_finite() && *v >= 0.)
102            || value > maximum
103            || maximum > 1e9
104            || regeneration > 1e9
105        {
106            return Err(AbilityError::Invalid);
107        }
108        Ok(Self {
109            value,
110            maximum,
111            regeneration,
112        })
113    }
114    pub fn value(&self) -> f32 {
115        self.value
116    }
117    pub fn advance(&mut self, dt: f32) -> Result<(), AbilityError> {
118        valid_dt(dt)?;
119        self.value = (self.value + self.regeneration * dt).min(self.maximum);
120        Ok(())
121    }
122    pub fn credit(&mut self, amount: f32) -> Result<(), AbilityError> {
123        if !amount.is_finite() || amount < 0. {
124            return Err(AbilityError::Invalid);
125        }
126        self.value = (self.value + amount).min(self.maximum);
127        Ok(())
128    }
129}
130#[derive(Clone, Copy, Debug)]
131struct Slot {
132    spec: AbilitySpec,
133    charges: u8,
134    remaining: f64,
135    reservation: Option<u64>,
136}
137/// Opaque, single-use token. Owners must be host-unique generational actor IDs.
138#[derive(Clone, Copy, Debug)]
139pub struct Reservation {
140    owner: u64,
141    slot: usize,
142    serial: u64,
143}
144pub struct AbilityBank<const N: usize> {
145    owner: u64,
146    slots: [Option<Slot>; N],
147    serial: u64,
148}
149impl<const N: usize> AbilityBank<N> {
150    pub fn new(owner: u64, specs: &[AbilitySpec]) -> Result<Self, AbilityError> {
151        if owner == 0 || N == 0 || N > 64 || specs.is_empty() || specs.len() > N {
152            return Err(AbilityError::Capacity);
153        }
154        let mut slots = [None; N];
155        for (out, spec) in slots.iter_mut().zip(specs) {
156            if spec.charges == 0
157                || !spec.recharge_seconds.is_finite()
158                || !(0.0001..=3600.).contains(&spec.recharge_seconds)
159                || !spec.cost.is_finite()
160                || !(0. ..=1e9).contains(&spec.cost)
161            {
162                return Err(AbilityError::Invalid);
163            }
164            *out = Some(Slot {
165                spec: *spec,
166                charges: spec.charges,
167                remaining: 0.,
168                reservation: None,
169            });
170        }
171        Ok(Self {
172            owner,
173            slots,
174            serial: 0,
175        })
176    }
177    pub fn advance(&mut self, dt: f32) -> Result<(), AbilityError> {
178        valid_dt(dt)?;
179        for slot in self.slots.iter_mut().flatten() {
180            if slot.reservation.is_some() || slot.charges == slot.spec.charges {
181                continue;
182            }
183            slot.remaining -= f64::from(dt);
184            if slot.remaining <= 1e-9 {
185                let period = f64::from(slot.spec.recharge_seconds);
186                let restored = (1. + (-slot.remaining).max(0.) / period)
187                    .floor()
188                    .min(f64::from(slot.spec.charges - slot.charges))
189                    as u8;
190                slot.charges += restored;
191                slot.remaining = if slot.charges == slot.spec.charges {
192                    0.
193                } else {
194                    slot.remaining + f64::from(restored) * period
195                };
196            }
197        }
198        Ok(())
199    }
200    pub fn charges(&self, id: usize) -> Option<u8> {
201        self.slots.get(id)?.map(|s| s.charges)
202    }
203    pub fn remaining(&self, id: usize) -> Option<f32> {
204        self.slots.get(id)?.map(|s| {
205            if s.charges > 0 {
206                0.
207            } else {
208                s.remaining as f32
209            }
210        })
211    }
212    /// Inspect whether a new reservation or immediate activation can succeed.
213    ///
214    /// Reads only immutable references and allocates no storage. Charges and pool
215    /// value already exclude anything spent by pending reservations. Recharge is
216    /// driven only by [`Self::advance`], not by previews or presentation time.
217    ///
218    /// A valid slot returns a snapshot even when blocked. An unknown slot returns
219    /// [`AbilityError::Invalid`] when enabled, or [`AbilityError::Blocked`] when
220    /// disabled, preserving [`Self::begin`]'s host-condition-first error order.
221    /// For unchanged inputs, `availability(...).and_then(|a| a.check())` matches
222    /// both `begin(...).map(|_| ())` and [`Self::activate`].
223    ///
224    /// ```
225    /// use ferravex_play::ability::{AbilityBank, AbilityBlocker, AbilitySpec, ResourcePool};
226    /// let mut bank = AbilityBank::<1>::new(1, &[AbilitySpec {
227    ///     charges: 2, recharge_seconds: 0.5, cost: 3.0,
228    /// }]).unwrap();
229    /// let mut pool = ResourcePool::new(6.0, 6.0, 0.0).unwrap();
230    /// let hud = bank.availability(0, &pool, true).unwrap();
231    /// assert_eq!((hud.charges, hud.max_charges), (2, 2));
232    /// assert_eq!((hud.resource_cost, hud.resource_available), (3.0, 6.0));
233    /// assert_eq!(hud.blocker, None);
234    /// assert!(!hud.reserved);
235    /// assert_eq!(pool.value(), 6.0);
236    ///
237    /// let token = bank.begin(0, &mut pool, true).unwrap();
238    /// let busy = bank.availability(0, &pool, true).unwrap();
239    /// assert_eq!(busy.blocker, Some(AbilityBlocker::Busy));
240    /// assert_eq!((busy.charges, busy.resource_available), (1, 3.0));
241    /// bank.cancel(token, &mut pool).unwrap();
242    /// assert_eq!(bank.availability(0, &pool, true).unwrap(), hud);
243    /// ```
244    pub fn availability(
245        &self,
246        id: usize,
247        pool: &ResourcePool,
248        enabled: bool,
249    ) -> Result<AbilityAvailability, AbilityError> {
250        let slot = self
251            .slots
252            .get(id)
253            .and_then(Option::as_ref)
254            .ok_or(if enabled {
255                AbilityError::Invalid
256            } else {
257                AbilityError::Blocked
258            })?;
259        let reserved = slot.reservation.is_some();
260        let blocker = if !enabled {
261            Some(AbilityBlocker::Disabled)
262        } else if reserved {
263            Some(AbilityBlocker::Busy)
264        } else if slot.charges == 0 {
265            Some(AbilityBlocker::NoCharges)
266        } else if pool.value < slot.spec.cost {
267            Some(AbilityBlocker::InsufficientResource)
268        } else if self.serial == u64::MAX {
269            Some(AbilityBlocker::ReservationExhausted)
270        } else {
271            None
272        };
273        Ok(AbilityAvailability {
274            charges: slot.charges,
275            max_charges: slot.spec.charges,
276            cooldown_remaining: if slot.charges > 0 {
277                0.
278            } else {
279                slot.remaining as f32
280            },
281            recharge_remaining: slot.remaining as f32,
282            resource_cost: slot.spec.cost,
283            resource_available: pool.value,
284            reserved,
285            blocker,
286        })
287    }
288    pub fn begin(
289        &mut self,
290        id: usize,
291        pool: &mut ResourcePool,
292        enabled: bool,
293    ) -> Result<Reservation, AbilityError> {
294        self.availability(id, pool, enabled)?.check()?;
295        let slot = self
296            .slots
297            .get_mut(id)
298            .and_then(Option::as_mut)
299            .ok_or(AbilityError::Invalid)?;
300        let serial = self.serial.checked_add(1).ok_or(AbilityError::Capacity)?;
301        self.serial = serial;
302        slot.charges -= 1;
303        pool.value -= slot.spec.cost;
304        slot.reservation = Some(serial);
305        Ok(Reservation {
306            owner: self.owner,
307            slot: id,
308            serial,
309        })
310    }
311    pub fn commit(&mut self, token: Reservation) -> Result<(), AbilityError> {
312        let slot = self.pending(token)?;
313        slot.reservation = None;
314        if slot.remaining == 0. {
315            slot.remaining = f64::from(slot.spec.recharge_seconds)
316        }
317        Ok(())
318    }
319    /// Refund only to the same resource pool used by begin. The host owns the pool;
320    /// do not move reservations across actors, lives, banks or resource accounts.
321    pub fn cancel(
322        &mut self,
323        token: Reservation,
324        pool: &mut ResourcePool,
325    ) -> Result<(), AbilityError> {
326        let slot = self.pending(token)?;
327        slot.reservation = None;
328        slot.charges += 1;
329        if slot.charges == slot.spec.charges {
330            slot.remaining = 0.
331        }
332        pool.credit(slot.spec.cost)?;
333        Ok(())
334    }
335    fn pending(&mut self, token: Reservation) -> Result<&mut Slot, AbilityError> {
336        if token.owner != self.owner {
337            return Err(AbilityError::Stale);
338        }
339        self.slots
340            .get_mut(token.slot)
341            .and_then(Option::as_mut)
342            .filter(|s| s.reservation == Some(token.serial))
343            .ok_or(AbilityError::Stale)
344    }
345    pub fn activate(
346        &mut self,
347        id: usize,
348        pool: &mut ResourcePool,
349        enabled: bool,
350    ) -> Result<(), AbilityError> {
351        let token = self.begin(id, pool, enabled)?;
352        self.commit(token)
353    }
354}
355fn valid_dt(dt: f32) -> Result<(), AbilityError> {
356    if dt.is_finite() && (0. ..=60.).contains(&dt) {
357        Ok(())
358    } else {
359        Err(AbilityError::Invalid)
360    }
361}
362#[cfg(test)]
363mod tests {
364    use super::*;
365    fn bank() -> AbilityBank<2> {
366        AbilityBank::new(
367            1,
368            &[AbilitySpec {
369                charges: 2,
370                recharge_seconds: 0.5,
371                cost: 3.,
372            }],
373        )
374        .unwrap()
375    }
376    #[test]
377    fn atomic_activation_recharge_and_failure_do_not_spend() {
378        let mut b = bank();
379        let mut p = ResourcePool::new(10., 10., 1.).unwrap();
380        assert_eq!(b.activate(0, &mut p, false), Err(AbilityError::Blocked));
381        assert_eq!(p.value(), 10.);
382        b.activate(0, &mut p, true).unwrap();
383        b.activate(0, &mut p, true).unwrap();
384        assert_eq!(p.value(), 4.);
385        assert_eq!(b.charges(0), Some(0));
386        assert_eq!(b.activate(0, &mut p, true), Err(AbilityError::Empty));
387        b.advance(0.75).unwrap();
388        assert_eq!(b.charges(0), Some(1));
389        b.advance(0.25).unwrap();
390        assert_eq!(b.charges(0), Some(2));
391        p.advance(1.).unwrap();
392        assert_eq!(p.value(), 5.);
393    }
394    #[test]
395    fn reservation_refunds_once_stale_and_foreign_tokens_fail() {
396        let mut b = bank();
397        let mut p = ResourcePool::new(5., 5., 0.).unwrap();
398        let t = b.begin(0, &mut p, true).unwrap();
399        assert_eq!(p.value(), 2.);
400        b.advance(2.).unwrap();
401        assert_eq!(b.charges(0), Some(1));
402        b.cancel(t, &mut p).unwrap();
403        assert_eq!(p.value(), 5.);
404        assert_eq!(b.cancel(t, &mut p), Err(AbilityError::Stale));
405        let mut foreign = AbilityBank::<2>::new(
406            2,
407            &[AbilitySpec {
408                charges: 2,
409                recharge_seconds: 0.5,
410                cost: 3.,
411            }],
412        )
413        .unwrap();
414        assert_eq!(foreign.commit(t), Err(AbilityError::Stale));
415        assert!(b.advance(f32::NAN).is_err());
416    }
417    #[test]
418    fn charge_clock_is_partition_independent() {
419        let mut a = bank();
420        let mut b = bank();
421        let mut p = ResourcePool::new(10., 10., 0.).unwrap();
422        let mut q = p;
423        a.activate(0, &mut p, true).unwrap();
424        b.activate(0, &mut q, true).unwrap();
425        a.advance(1.).unwrap();
426        for _ in 0..100 {
427            b.advance(0.01).unwrap();
428        }
429        assert_eq!(a.charges(0), b.charges(0));
430    }
431
432    fn assert_blocked(
433        bank: &mut AbilityBank<2>,
434        pool: &mut ResourcePool,
435        enabled: bool,
436        blocker: AbilityBlocker,
437        error: AbilityError,
438    ) {
439        let before = bank.availability(0, pool, enabled).unwrap();
440        let serial = bank.serial;
441        let reservation = bank.slots[0].unwrap().reservation;
442        assert_eq!(before.blocker, Some(blocker));
443        assert_eq!(before.check(), Err(error));
444        assert_eq!(bank.begin(0, pool, enabled).map(|_| ()), Err(error));
445        assert_eq!(bank.activate(0, pool, enabled), Err(error));
446        assert_eq!(bank.availability(0, pool, enabled).unwrap(), before);
447        assert_eq!(bank.serial, serial);
448        assert_eq!(bank.slots[0].unwrap().reservation, reservation);
449    }
450
451    #[test]
452    fn availability_is_read_only_and_reservations_remain_single_use() {
453        let mut b = bank();
454        let mut p = ResourcePool::new(6., 6., 0.).unwrap();
455        let ready = AbilityAvailability {
456            charges: 2,
457            max_charges: 2,
458            cooldown_remaining: 0.,
459            recharge_remaining: 0.,
460            resource_cost: 3.,
461            resource_available: 6.,
462            reserved: false,
463            blocker: None,
464        };
465        for _ in 0..100 {
466            assert_eq!(b.availability(0, &p, true), Ok(ready));
467        }
468        assert_eq!(ready.check(), Ok(()));
469        assert_eq!(b.serial, 0);
470        assert_eq!(p.value(), 6.);
471        let token = b.begin(0, &mut p, true).unwrap();
472        assert_eq!(token.serial, 1);
473        let busy = b.availability(0, &p, true).unwrap();
474        assert_eq!((busy.charges, busy.resource_available), (1, 3.));
475        assert!(busy.reserved);
476        assert_eq!(busy.recharge_remaining, 0.);
477        assert_blocked(
478            &mut b,
479            &mut p,
480            true,
481            AbilityBlocker::Busy,
482            AbilityError::Blocked,
483        );
484        b.advance(5.).unwrap();
485        assert_eq!(b.availability(0, &p, true), Ok(busy));
486        b.cancel(token, &mut p).unwrap();
487        assert_eq!(b.availability(0, &p, true), Ok(ready));
488        assert_eq!(b.commit(token), Err(AbilityError::Stale));
489        assert_eq!(b.cancel(token, &mut p), Err(AbilityError::Stale));
490        b.activate(0, &mut p, true).unwrap();
491        assert_eq!(b.charges(0), Some(1));
492        assert_eq!(p.value(), 3.);
493    }
494
495    #[test]
496    fn availability_explains_blocker_precedence_and_recovery() {
497        let mut b = bank();
498        let mut p = ResourcePool::new(6., 6., 0.).unwrap();
499        b.activate(0, &mut p, true).unwrap();
500        b.advance(0.125).unwrap();
501        let partial = b.availability(0, &p, true).unwrap();
502        assert_eq!(partial.check(), Ok(()));
503        assert_eq!(partial.cooldown_remaining, 0.);
504        assert_eq!(partial.recharge_remaining, 0.375);
505        assert_eq!(b.remaining(0), Some(partial.cooldown_remaining));
506
507        let token = b.begin(0, &mut p, true).unwrap();
508        assert_blocked(
509            &mut b,
510            &mut p,
511            false,
512            AbilityBlocker::Disabled,
513            AbilityError::Blocked,
514        );
515        let disabled = b.availability(0, &p, false).unwrap();
516        assert!(disabled.reserved);
517        assert_eq!(disabled.charges, 0);
518        assert_eq!(disabled.resource_available, 0.);
519        assert_eq!(disabled.cooldown_remaining, 0.375);
520        assert_blocked(
521            &mut b,
522            &mut p,
523            true,
524            AbilityBlocker::Busy,
525            AbilityError::Blocked,
526        );
527        b.advance(60.).unwrap();
528        assert_eq!(b.availability(0, &p, false), Ok(disabled));
529        b.commit(token).unwrap();
530        assert_blocked(
531            &mut b,
532            &mut p,
533            true,
534            AbilityBlocker::NoCharges,
535            AbilityError::Empty,
536        );
537        b.advance(0.25).unwrap();
538        let cooling = b.availability(0, &p, true).unwrap();
539        assert_eq!(cooling.cooldown_remaining, 0.125);
540        assert_eq!(b.remaining(0), Some(cooling.cooldown_remaining));
541        b.advance(0.125).unwrap();
542        assert_blocked(
543            &mut b,
544            &mut p,
545            true,
546            AbilityBlocker::InsufficientResource,
547            AbilityError::Resource,
548        );
549        p.credit(3.).unwrap();
550        let ready = b.availability(0, &p, true).unwrap();
551        assert_eq!(ready.check(), Ok(()));
552        assert_eq!(ready.charges, 1);
553        assert_eq!(ready.recharge_remaining, 0.5);
554        b.activate(0, &mut p, true).unwrap();
555        b.advance(1.).unwrap();
556        let full = b.availability(0, &p, true).unwrap();
557        assert_eq!(full.charges, full.max_charges);
558        assert_eq!(full.recharge_remaining, 0.);
559        assert_eq!(full.cooldown_remaining, 0.);
560    }
561
562    #[test]
563    fn availability_unknown_ids_preserve_disabled_first_errors() {
564        let mut b = bank();
565        let mut p = ResourcePool::new(6., 6., 0.).unwrap();
566        let before = b.availability(0, &p, true).unwrap();
567        for id in [1, 2, usize::MAX] {
568            for enabled in [false, true] {
569                let error = if enabled {
570                    AbilityError::Invalid
571                } else {
572                    AbilityError::Blocked
573                };
574                assert_eq!(b.availability(id, &p, enabled), Err(error));
575                assert_eq!(b.begin(id, &mut p, enabled).map(|_| ()), Err(error));
576                assert_eq!(b.activate(id, &mut p, enabled), Err(error));
577            }
578        }
579        assert_eq!(b.availability(0, &p, true), Ok(before));
580        assert_eq!(b.serial, 0);
581    }
582
583    #[test]
584    fn availability_checks_resource_boundaries_and_free_abilities() {
585        for cost in [0., 3., 1e9] {
586            let mut b = AbilityBank::<2>::new(
587                1,
588                &[AbilitySpec {
589                    charges: 1,
590                    recharge_seconds: 0.5,
591                    cost,
592                }],
593            )
594            .unwrap();
595            let mut p = ResourcePool::new(cost, cost, 0.).unwrap();
596            let ready = b.availability(0, &p, true).unwrap();
597            assert_eq!(ready.check(), Ok(()));
598            assert_eq!(
599                (ready.resource_available, ready.resource_cost),
600                (cost, cost)
601            );
602            let token = b.begin(0, &mut p, true).unwrap();
603            assert_eq!(p.value(), 0.);
604            assert_blocked(
605                &mut b,
606                &mut p,
607                true,
608                AbilityBlocker::Busy,
609                AbilityError::Blocked,
610            );
611            b.cancel(token, &mut p).unwrap();
612            assert_eq!(b.availability(0, &p, true), Ok(ready));
613            b.activate(0, &mut p, true).unwrap();
614            assert_eq!(p.value(), 0.);
615            let empty = b.availability(0, &p, true).unwrap();
616            assert_eq!(empty.blocker, Some(AbilityBlocker::NoCharges));
617            assert_eq!(empty.cooldown_remaining, 0.5);
618        }
619
620        let mut b = bank();
621        let mut p = ResourcePool::new(f32::from_bits(3.0_f32.to_bits() - 1), 3., 1.).unwrap();
622        assert_blocked(
623            &mut b,
624            &mut p,
625            true,
626            AbilityBlocker::InsufficientResource,
627            AbilityError::Resource,
628        );
629        p.advance(1.).unwrap();
630        assert_eq!(b.availability(0, &p, true).unwrap().check(), Ok(()));
631        b.activate(0, &mut p, true).unwrap();
632        assert_eq!(p.value(), 0.);
633    }
634
635    #[test]
636    fn availability_predicts_serial_exhaustion_without_issuing_tokens() {
637        let mut b = bank();
638        let mut p = ResourcePool::new(6., 6., 0.).unwrap();
639        b.serial = u64::MAX - 1;
640        for _ in 0..100 {
641            assert_eq!(b.availability(0, &p, true).unwrap().check(), Ok(()));
642        }
643        assert_eq!(b.serial, u64::MAX - 1);
644        let token = b.begin(0, &mut p, true).unwrap();
645        assert_eq!(token.serial, u64::MAX);
646        assert_blocked(
647            &mut b,
648            &mut p,
649            true,
650            AbilityBlocker::Busy,
651            AbilityError::Blocked,
652        );
653        b.cancel(token, &mut p).unwrap();
654        assert_blocked(
655            &mut b,
656            &mut p,
657            false,
658            AbilityBlocker::Disabled,
659            AbilityError::Blocked,
660        );
661        assert_blocked(
662            &mut b,
663            &mut p,
664            true,
665            AbilityBlocker::ReservationExhausted,
666            AbilityError::Capacity,
667        );
668        let mut empty_pool = ResourcePool::new(0., 0., 0.).unwrap();
669        assert_blocked(
670            &mut b,
671            &mut empty_pool,
672            true,
673            AbilityBlocker::InsufficientResource,
674            AbilityError::Resource,
675        );
676    }
677}