pipecircuit 0.0.11

Correct. Robust. Fast. Portable.
Documentation
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
use core::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    marker::PhantomData,
    num::NonZeroU64,
};

use crate::{StateMachine, StepInputOf};

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PositiveDuration(NonZeroU64);

impl PositiveDuration {
    pub const fn from_nanoseconds(nanoseconds: NonZeroU64) -> Self {
        Self(nanoseconds)
    }

    pub const fn nanoseconds(self) -> NonZeroU64 {
        self.0
    }
}

/// One correlation address in a machine-scoped continuation namespace.
pub struct ContinuationId<Machine> {
    value: NonZeroU64,
    machine: PhantomData<fn() -> Machine>,
}

impl<Machine> ContinuationId<Machine> {
    /// Reconstructs typed correlation data after a trusted decoder validates
    /// its wire representation. This does not reconstruct settlement authority.
    pub const fn from_nonzero(value: NonZeroU64) -> Self {
        Self {
            value,
            machine: PhantomData,
        }
    }

    pub const fn value(self) -> NonZeroU64 {
        self.value
    }
}

impl<Machine> Clone for ContinuationId<Machine> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Machine> Copy for ContinuationId<Machine> {}

impl<Machine> fmt::Debug for ContinuationId<Machine> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(formatter)
    }
}

impl<Machine> PartialEq for ContinuationId<Machine> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<Machine> Eq for ContinuationId<Machine> {}

impl<Machine> PartialOrd for ContinuationId<Machine> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<Machine> Ord for ContinuationId<Machine> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.value.cmp(&other.value)
    }
}

impl<Machine> Hash for ContinuationId<Machine> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.value.hash(state);
    }
}

enum NextContinuationId {
    Available(NonZeroU64),
    Exhausted,
}

/// Owns one deterministic, nonwrapping continuation-ID namespace.
pub struct ContinuationIds<Machine> {
    next: NextContinuationId,
    machine: PhantomData<fn() -> Machine>,
}

impl<Machine> ContinuationIds<Machine> {
    pub const fn new() -> Self {
        Self {
            next: NextContinuationId::Available(NonZeroU64::MIN),
            machine: PhantomData,
        }
    }

    pub fn try_issue(
        &mut self,
    ) -> Result<ContinuationId<Machine>, ContinuationIdentifiersExhausted> {
        let NextContinuationId::Available(current) = self.next else {
            return Err(ContinuationIdentifiersExhausted);
        };
        self.next = match current.get().checked_add(1).and_then(NonZeroU64::new) {
            Some(next) => NextContinuationId::Available(next),
            None => NextContinuationId::Exhausted,
        };
        Ok(ContinuationId::from_nonzero(current))
    }
}

impl<Machine> Default for ContinuationIds<Machine> {
    fn default() -> Self {
        Self::new()
    }
}

/// Owns the machine-wide identity namespace and coordinates continuation
/// admission and settlement around application-selected storage.
pub struct ContinuationCoordinator<Machine> {
    ids: ContinuationIds<Machine>,
}

impl<Machine> ContinuationCoordinator<Machine> {
    pub const fn new() -> Self {
        Self {
            ids: ContinuationIds::new(),
        }
    }
}

impl<Machine> Default for ContinuationCoordinator<Machine> {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ContinuationIdentifiersExhausted;

#[must_use = "continuation settlements must be stepped back into their owning machine"]
pub enum ContinuationSettlement<Completion, Expiry> {
    Completed(Completion),
    Expired(Expiry),
}

/// The protected input produced only by consuming a continuation authority.
#[must_use = "continuation inputs must be stepped back into their owning machine"]
pub struct ContinuationInput<Machine, Completion, Expiry> {
    id: ContinuationId<Machine>,
    settlement: ContinuationSettlement<Completion, Expiry>,
}

impl<Machine, Completion, Expiry> ContinuationInput<Machine, Completion, Expiry> {
    pub const fn id(&self) -> ContinuationId<Machine> {
        self.id
    }

    pub const fn settlement(&self) -> &ContinuationSettlement<Completion, Expiry> {
        &self.settlement
    }

    pub fn into_parts(
        self,
    ) -> (
        ContinuationId<Machine>,
        ContinuationSettlement<Completion, Expiry>,
    ) {
        (self.id, self.settlement)
    }
}

/// Move-only authority to resume one exact state machine input.
#[must_use = "dropping a continuation abandons owed work without settling its machine"]
pub struct Continuation<Machine, Completion, Expiry> {
    id: ContinuationId<Machine>,
    expiry: Expiry,
    completion: PhantomData<fn(Completion)>,
}

impl<Machine, Completion, Expiry> Continuation<Machine, Completion, Expiry> {
    pub const fn id(&self) -> ContinuationId<Machine> {
        self.id
    }

    pub fn complete(
        self,
        completion: Completion,
    ) -> CompletedContinuation<Machine, Completion, Expiry> {
        CompletedContinuation {
            input: ContinuationInput {
                id: self.id,
                settlement: ContinuationSettlement::Completed(completion),
            },
            cancel_deadline: CancelContinuationDeadline { id: self.id },
        }
    }

    pub fn expire(self) -> ContinuationInput<Machine, Completion, Expiry> {
        ContinuationInput {
            id: self.id,
            settlement: ContinuationSettlement::Expired(self.expiry),
        }
    }
}

/// The two routes made necessary by completing before the mandatory deadline.
#[must_use = "completion must route both the machine input and deadline cancellation"]
pub struct CompletedContinuation<Machine, Completion, Expiry> {
    input: ContinuationInput<Machine, Completion, Expiry>,
    cancel_deadline: CancelContinuationDeadline<Machine>,
}

impl<Machine, Completion, Expiry> CompletedContinuation<Machine, Completion, Expiry> {
    pub fn into_parts(
        self,
    ) -> (
        ContinuationInput<Machine, Completion, Expiry>,
        CancelContinuationDeadline<Machine>,
    ) {
        (self.input, self.cancel_deadline)
    }
}

/// A mandatory deadline to install before releasing its associated work.
#[must_use = "continuation deadlines must be routed before their work is released"]
pub struct ContinuationDeadline<Machine> {
    id: ContinuationId<Machine>,
    after: PositiveDuration,
}

impl<Machine> ContinuationDeadline<Machine> {
    pub const fn id(&self) -> ContinuationId<Machine> {
        self.id
    }

    pub const fn after(&self) -> PositiveDuration {
        self.after
    }

    pub fn into_parts(self) -> (ContinuationId<Machine>, PositiveDuration) {
        (self.id, self.after)
    }
}

/// A typed instruction to cancel the deadline of a completed continuation.
#[must_use = "completed continuation deadlines must be cancelled or explicitly discarded"]
pub struct CancelContinuationDeadline<Machine> {
    id: ContinuationId<Machine>,
}

impl<Machine> CancelContinuationDeadline<Machine> {
    pub const fn id(&self) -> ContinuationId<Machine> {
        self.id
    }

    pub fn into_id(self) -> ContinuationId<Machine> {
        self.id
    }
}

/// Work addressed with the continuation that its eventual result settles.
#[must_use = "owed work must be delivered or returned to its owner"]
pub struct ContinuationWork<Machine, Work> {
    id: ContinuationId<Machine>,
    work: Work,
}

impl<Machine, Work> ContinuationWork<Machine, Work> {
    /// Rebuilds addressed work at a delivery boundary from decoded correlation
    /// data and a decoded work value.
    pub const fn new(id: ContinuationId<Machine>, work: Work) -> Self {
        Self { id, work }
    }

    pub const fn id(&self) -> ContinuationId<Machine> {
        self.id
    }

    pub const fn work(&self) -> &Work {
        &self.work
    }

    pub fn into_parts(self) -> (ContinuationId<Machine>, Work) {
        (self.id, self.work)
    }

    pub fn map<Mapped>(
        self,
        map: impl FnOnce(Work) -> Mapped,
    ) -> ContinuationWork<Machine, Mapped> {
        ContinuationWork {
            id: self.id,
            work: map(self.work),
        }
    }
}

impl<Requester, Target, Work> StepInputOf<Target> for ContinuationWork<Requester, Work>
where
    Target: StateMachine,
    Work: StepInputOf<Target>,
{
    type Outcome = ContinuationCompletion<Requester, Work::Outcome>;

    #[inline]
    fn step(self, target: &mut Target) -> Self::Outcome {
        let (id, work) = self.into_parts();
        ContinuationCompletion::new(id, target.step(work))
    }
}

/// A completed outside-world result addressed back to its parked continuation.
#[must_use = "continuation completions must settle or be classified as stale"]
pub struct ContinuationCompletion<Machine, Completion> {
    id: ContinuationId<Machine>,
    completion: Completion,
}

impl<Machine, Completion> ContinuationCompletion<Machine, Completion> {
    pub const fn new(id: ContinuationId<Machine>, completion: Completion) -> Self {
        Self { id, completion }
    }

    pub const fn id(&self) -> ContinuationId<Machine> {
        self.id
    }

    pub const fn completion(&self) -> &Completion {
        &self.completion
    }

    pub fn into_parts(self) -> (ContinuationId<Machine>, Completion) {
        (self.id, self.completion)
    }

    pub fn map<Mapped>(
        self,
        map: impl FnOnce(Completion) -> Mapped,
    ) -> ContinuationCompletion<Machine, Mapped> {
        ContinuationCompletion {
            id: self.id,
            completion: map(self.completion),
        }
    }
}

/// One state-machine-authorized operation that must either complete or expire.
///
/// `Owed` is created by the machine that will consume the future settlement.
/// Its default admission path parks the move-only authority before releasing
/// either the deadline or the work to the circuit:
///
/// ```
/// use core::num::NonZeroU64;
/// use pipecircuit::{
///     ContinuationCompletion, ContinuationCoordinator, ContinuationInput,
///     ContinuationSettlement, ContinuationSlot, Owed, PositiveDuration, StateMachine,
///     StepInputOf,
/// };
///
/// struct Downloader {
///     received: Option<u8>,
/// }
///
/// struct Download;
/// struct Downloaded(u8);
/// struct DownloadExpired;
///
/// impl StateMachine for Downloader {}
///
/// impl StepInputOf<Downloader>
///     for ContinuationInput<Downloader, Downloaded, DownloadExpired>
/// {
///     type Outcome = ();
///
///     fn step(self, downloader: &mut Downloader) -> Self::Outcome {
///         match self.into_parts().1 {
///             ContinuationSettlement::Completed(Downloaded(byte)) => {
///                 downloader.received = Some(byte);
///             }
///             ContinuationSettlement::Expired(DownloadExpired) => {
///                 downloader.received = None;
///             }
///         }
///     }
/// }
///
/// # fn main() -> Result<(), ()> {
/// let mut continuations = ContinuationCoordinator::new();
/// let mut pending = ContinuationSlot::new();
/// let owed = Owed::<Downloader, Downloaded, DownloadExpired, Download>::new(
///     Download,
///     DownloadExpired,
///     PositiveDuration::from_nanoseconds(NonZeroU64::MIN),
/// );
///
/// let admitted = continuations.try_admit(owed, &mut pending).map_err(|_| ())?;
/// let (deadline, work) = admitted.into_parts();
/// // The switchboard routes `deadline` to a timer and `work` to its participant.
/// let completion = ContinuationCompletion::new(work.id(), Downloaded(7));
/// let completed = continuations
///     .try_complete(&mut pending, completion)
///     .map_err(|_| ())?;
/// let (input, cancel_deadline) = completed.into_parts();
/// // The switchboard routes `cancel_deadline` to the timer and `input` home.
/// let mut downloader = Downloader { received: None };
/// downloader.step(input);
/// assert_eq!(downloader.received, Some(7));
/// assert_eq!(cancel_deadline.id(), deadline.id());
/// # Ok(())
/// # }
/// ```
#[must_use = "owed work must be parked, scheduled, and delivered"]
pub struct Owed<Machine, Completion, Expiry, Work = ()> {
    work: Work,
    expiry: Expiry,
    timeout_after: PositiveDuration,
    machine: PhantomData<fn() -> Machine>,
    completion: PhantomData<fn(Completion)>,
}

impl<Machine, Completion, Expiry, Work> Owed<Machine, Completion, Expiry, Work>
where
    Machine: StateMachine,
    ContinuationInput<Machine, Completion, Expiry>: StepInputOf<Machine>,
{
    pub const fn new(work: Work, expiry: Expiry, timeout_after: PositiveDuration) -> Self {
        Self {
            work,
            expiry,
            timeout_after,
            machine: PhantomData,
            completion: PhantomData,
        }
    }
}

impl<Machine, Completion, Expiry, Work> Owed<Machine, Completion, Expiry, Work> {
    pub const fn work(&self) -> &Work {
        &self.work
    }

    pub const fn timeout_after(&self) -> PositiveDuration {
        self.timeout_after
    }

    pub fn into_parts(self) -> (Work, Expiry, PositiveDuration) {
        (self.work, self.expiry, self.timeout_after)
    }
}

impl<Machine, Completion, Expiry> Owed<Machine, Completion, Expiry>
where
    Machine: StateMachine,
    ContinuationInput<Machine, Completion, Expiry>: StepInputOf<Machine>,
{
    pub const fn wait(expiry: Expiry, timeout_after: PositiveDuration) -> Self {
        Self::new((), expiry, timeout_after)
    }
}

pub type OwedAdmissionOutcome<Machine, Completion, Expiry, Work> =
    Result<ParkedOwed<Machine, Work>, OwedAdmissionFailure<Machine, Completion, Expiry, Work>>;

pub type OwedIssueOutcome<Machine, Completion, Expiry, Work> = Result<
    UnparkedOwedParts<Machine, Completion, Expiry, Work>,
    OwedIssueFailure<Machine, Completion, Expiry, Work>,
>;

impl<Machine> ContinuationCoordinator<Machine> {
    /// Issues and parks one semantic debt before exposing its deadline or work.
    pub fn try_admit<Completion, Expiry, Work>(
        &mut self,
        owed: Owed<Machine, Completion, Expiry, Work>,
        slot: &mut ContinuationSlot<Machine, Completion, Expiry>,
    ) -> OwedAdmissionOutcome<Machine, Completion, Expiry, Work> {
        if let Some(pending_id) = slot.pending_id() {
            return Err(OwedAdmissionFailure::Pending { pending_id, owed });
        }
        let id = match self.ids.try_issue() {
            Ok(id) => id,
            Err(ContinuationIdentifiersExhausted) => {
                return Err(OwedAdmissionFailure::IdentifiersExhausted(owed));
            }
        };
        let (work, expiry, timeout_after) = owed.into_parts();
        slot.state = ContinuationSlotState::Pending(Continuation {
            id,
            expiry,
            completion: PhantomData,
        });
        Ok(ParkedOwed {
            deadline: ContinuationDeadline {
                id,
                after: timeout_after,
            },
            work: ContinuationWork { id, work },
        })
    }

    /// Issues the typed parts needed by an application-selected continuation
    /// store. The authority must be parked before deadline or work delivery.
    pub fn try_issue<Completion, Expiry, Work>(
        &mut self,
        owed: Owed<Machine, Completion, Expiry, Work>,
    ) -> OwedIssueOutcome<Machine, Completion, Expiry, Work> {
        let id = match self.ids.try_issue() {
            Ok(id) => id,
            Err(ContinuationIdentifiersExhausted) => return Err(OwedIssueFailure { owed }),
        };
        let (work, expiry, timeout_after) = owed.into_parts();
        Ok(UnparkedOwedParts {
            work: ContinuationWork { id, work },
            deadline: ContinuationDeadline {
                id,
                after: timeout_after,
            },
            continuation: Continuation {
                id,
                expiry,
                completion: PhantomData,
            },
        })
    }

    pub fn try_complete<Completion, Expiry>(
        &self,
        slot: &mut ContinuationSlot<Machine, Completion, Expiry>,
        completion: ContinuationCompletion<Machine, Completion>,
    ) -> Result<
        CompletedContinuation<Machine, Completion, Expiry>,
        CompleteContinuationFailure<Machine, Completion>,
    > {
        slot.try_complete(completion)
    }

    pub fn try_expire<Completion, Expiry>(
        &self,
        slot: &mut ContinuationSlot<Machine, Completion, Expiry>,
        id: ContinuationId<Machine>,
    ) -> Result<ContinuationInput<Machine, Completion, Expiry>, ContinuationNotPending<Machine>>
    {
        slot.try_expire(id)
    }
}

/// The lower-level admission surface for a custom continuation store.
#[must_use = "the continuation must be parked before its deadline or work is routed"]
pub struct UnparkedOwedParts<Machine, Completion, Expiry, Work> {
    work: ContinuationWork<Machine, Work>,
    deadline: ContinuationDeadline<Machine>,
    continuation: Continuation<Machine, Completion, Expiry>,
}

impl<Machine, Completion, Expiry, Work> UnparkedOwedParts<Machine, Completion, Expiry, Work> {
    pub fn into_parts(
        self,
    ) -> (
        ContinuationWork<Machine, Work>,
        ContinuationDeadline<Machine>,
        Continuation<Machine, Completion, Expiry>,
    ) {
        (self.work, self.deadline, self.continuation)
    }
}

/// Deadline and work released only after their continuation authority is parked.
#[must_use = "the deadline must be routed before the associated work is released"]
pub struct ParkedOwed<Machine, Work> {
    deadline: ContinuationDeadline<Machine>,
    work: ContinuationWork<Machine, Work>,
}

impl<Machine, Work> ParkedOwed<Machine, Work> {
    pub fn into_parts(
        self,
    ) -> (
        ContinuationDeadline<Machine>,
        ContinuationWork<Machine, Work>,
    ) {
        (self.deadline, self.work)
    }
}

/// A failed default admission preserves the complete semantic debt.
#[must_use = "failed admission still owns the rejected owed operation"]
pub enum OwedAdmissionFailure<Machine, Completion, Expiry, Work> {
    Pending {
        pending_id: ContinuationId<Machine>,
        owed: Owed<Machine, Completion, Expiry, Work>,
    },
    IdentifiersExhausted(Owed<Machine, Completion, Expiry, Work>),
}

impl<Machine, Completion, Expiry, Work> OwedAdmissionFailure<Machine, Completion, Expiry, Work> {
    pub const fn pending_id(&self) -> Option<ContinuationId<Machine>> {
        match self {
            Self::Pending { pending_id, .. } => Some(*pending_id),
            Self::IdentifiersExhausted(_) => None,
        }
    }

    pub fn into_owed(self) -> Owed<Machine, Completion, Expiry, Work> {
        match self {
            Self::Pending { owed, .. } | Self::IdentifiersExhausted(owed) => owed,
        }
    }
}

/// Identifier exhaustion during custom-store admission preserves the debt.
#[must_use = "failed issuance still owns the rejected owed operation"]
pub struct OwedIssueFailure<Machine, Completion, Expiry, Work> {
    owed: Owed<Machine, Completion, Expiry, Work>,
}

impl<Machine, Completion, Expiry, Work> OwedIssueFailure<Machine, Completion, Expiry, Work> {
    pub fn into_owed(self) -> Owed<Machine, Completion, Expiry, Work> {
        self.owed
    }
}

enum ContinuationSlotState<Machine, Completion, Expiry> {
    Vacant,
    Pending(Continuation<Machine, Completion, Expiry>),
}

/// One allocation-free owner for a single pending continuation authority.
pub struct ContinuationSlot<Machine, Completion, Expiry> {
    state: ContinuationSlotState<Machine, Completion, Expiry>,
}

impl<Machine, Completion, Expiry> ContinuationSlot<Machine, Completion, Expiry> {
    pub const fn new() -> Self {
        Self {
            state: ContinuationSlotState::Vacant,
        }
    }

    pub const fn pending_id(&self) -> Option<ContinuationId<Machine>> {
        match &self.state {
            ContinuationSlotState::Vacant => None,
            ContinuationSlotState::Pending(continuation) => Some(continuation.id()),
        }
    }

    pub fn try_park(
        &mut self,
        continuation: Continuation<Machine, Completion, Expiry>,
    ) -> Result<(), ContinuationSlotOccupied<Machine, Completion, Expiry>> {
        match &self.state {
            ContinuationSlotState::Vacant => {
                self.state = ContinuationSlotState::Pending(continuation);
                Ok(())
            }
            ContinuationSlotState::Pending(pending) => Err(ContinuationSlotOccupied {
                pending_id: pending.id(),
                rejected: continuation,
            }),
        }
    }

    pub fn try_take(
        &mut self,
        id: ContinuationId<Machine>,
    ) -> Result<Continuation<Machine, Completion, Expiry>, ContinuationNotPending<Machine>> {
        let state = core::mem::replace(&mut self.state, ContinuationSlotState::Vacant);
        match state {
            ContinuationSlotState::Vacant => Err(ContinuationNotPending::Vacant { requested: id }),
            ContinuationSlotState::Pending(pending) if pending.id() != id => {
                let pending_id = pending.id();
                self.state = ContinuationSlotState::Pending(pending);
                Err(ContinuationNotPending::Different {
                    requested: id,
                    pending: pending_id,
                })
            }
            ContinuationSlotState::Pending(pending) => Ok(pending),
        }
    }

    pub fn try_complete(
        &mut self,
        completion: ContinuationCompletion<Machine, Completion>,
    ) -> Result<
        CompletedContinuation<Machine, Completion, Expiry>,
        CompleteContinuationFailure<Machine, Completion>,
    > {
        let id = completion.id();
        let continuation = match self.try_take(id) {
            Ok(continuation) => continuation,
            Err(cause) => return Err(CompleteContinuationFailure { completion, cause }),
        };
        let (_, completion) = completion.into_parts();
        Ok(continuation.complete(completion))
    }

    pub fn try_expire(
        &mut self,
        id: ContinuationId<Machine>,
    ) -> Result<ContinuationInput<Machine, Completion, Expiry>, ContinuationNotPending<Machine>>
    {
        self.try_take(id).map(Continuation::expire)
    }
}

impl<Machine, Completion, Expiry> Default for ContinuationSlot<Machine, Completion, Expiry> {
    fn default() -> Self {
        Self::new()
    }
}

#[must_use = "a rejected continuation still owns its resumption authority"]
pub struct ContinuationSlotOccupied<Machine, Completion, Expiry> {
    pending_id: ContinuationId<Machine>,
    rejected: Continuation<Machine, Completion, Expiry>,
}

impl<Machine, Completion, Expiry> ContinuationSlotOccupied<Machine, Completion, Expiry> {
    pub const fn pending_id(&self) -> ContinuationId<Machine> {
        self.pending_id
    }

    pub fn into_rejected(self) -> Continuation<Machine, Completion, Expiry> {
        self.rejected
    }
}

#[must_use = "unknown continuation IDs must be classified as stale or invalid"]
pub enum ContinuationNotPending<Machine> {
    Vacant {
        requested: ContinuationId<Machine>,
    },
    Different {
        requested: ContinuationId<Machine>,
        pending: ContinuationId<Machine>,
    },
}

impl<Machine> Clone for ContinuationNotPending<Machine> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Machine> Copy for ContinuationNotPending<Machine> {}

impl<Machine> fmt::Debug for ContinuationNotPending<Machine> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Vacant { requested } => formatter
                .debug_struct("Vacant")
                .field("requested", requested)
                .finish(),
            Self::Different { requested, pending } => formatter
                .debug_struct("Different")
                .field("requested", requested)
                .field("pending", pending)
                .finish(),
        }
    }
}

impl<Machine> PartialEq for ContinuationNotPending<Machine> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Self::Vacant {
                    requested: left_requested,
                },
                Self::Vacant {
                    requested: right_requested,
                },
            ) => left_requested == right_requested,
            (
                Self::Different {
                    requested: left_requested,
                    pending: left_pending,
                },
                Self::Different {
                    requested: right_requested,
                    pending: right_pending,
                },
            ) => left_requested == right_requested && left_pending == right_pending,
            (Self::Vacant { .. }, Self::Different { .. })
            | (Self::Different { .. }, Self::Vacant { .. }) => false,
        }
    }
}

impl<Machine> Eq for ContinuationNotPending<Machine> {}

#[must_use = "failed completion retains the outside-world result"]
pub struct CompleteContinuationFailure<Machine, Completion> {
    completion: ContinuationCompletion<Machine, Completion>,
    cause: ContinuationNotPending<Machine>,
}

impl<Machine, Completion> CompleteContinuationFailure<Machine, Completion> {
    pub const fn cause(&self) -> &ContinuationNotPending<Machine> {
        &self.cause
    }

    pub fn into_completion(self) -> ContinuationCompletion<Machine, Completion> {
        self.completion
    }

    pub fn into_parts(
        self,
    ) -> (
        ContinuationCompletion<Machine, Completion>,
        ContinuationNotPending<Machine>,
    ) {
        (self.completion, self.cause)
    }
}

#[cfg(kani)]
mod proofs;

#[cfg(test)]
mod tests;