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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
#![cfg_attr(not(test), no_std)]
//! Implement a somewhat convenient and somewhat efficient way to perform RPC
//! in an embedded context.
//!
//! The approach is inspired by Go's channels, with the restriction that
//! there is a clear separation into a requester and a responder.
//!
//! Requests may be canceled, which the responder should honour on a
//! best-effort basis.
//!
//! ### Example use cases
//! - USB device interrupt handler performs low-level protocol details, hands off
//!   commands from the host to higher-level logic running in the idle thread.
//!   This higher-level logic need only understand clearly typed commands, as
//!   moduled by variants of a given `Request` enum.
//! - `trussed` crypto service, responding to crypto request from apps across
//!   TrustZone for Cortex-M secure/non-secure boundaries.
//! - Request to blink a few lights and reply on button press
//!
//!
//! ### Approach
//! It is assumed that all requests fit in a single `Request` enum, and that
//! all responses fit in single `Response` enum. The [`Channel`](Channel) and [`Interchange`](Interchange) structs allocate a single buffer in which either Request or Response fit and handle synchronization
//! Both structures have `const` constructors, allowing them to be statically allocated.
//!
//! An alternative approach would be to use two heapless Queues of length one
//! each for response and requests. The advantage of our construction is to
//! have only one static memory region in use.
//!
//! ```
//! # #![cfg(not(loom))]
//! # use interchange::{State, Interchange};
//! #[derive(Clone, Debug, PartialEq)]
//! pub enum Request {
//!     This(u8, u32),
//!     That(i64),
//! }
//!
//! #[derive(Clone, Debug, PartialEq)]
//! pub enum Response {
//!     Here(u8, u8, u8),
//!     There(i16),
//! }
//!
//! static INTERCHANGE: Interchange<Request, Response, 1> = Interchange::new();
//!
//! let (mut rq, mut rp) = INTERCHANGE.claim().unwrap();
//!
//! assert!(rq.state() == State::Idle);
//!
//! // happy path: no cancelation
//! let request = Request::This(1, 2);
//! assert!(rq.request(request).is_ok());
//!
//! let request = rp.take_request().unwrap();
//! println!("rp got request: {:?}", request);
//!
//! let response = Response::There(-1);
//! assert!(!rp.is_canceled());
//! assert!(rp.respond(response).is_ok());
//!
//! let response = rq.take_response().unwrap();
//! println!("rq got response: {:?}", response);
//!
//! // early cancelation path
//! assert!(rq.request(request).is_ok());
//!
//! let request =  rq.cancel().unwrap().unwrap();
//! println!("responder could cancel: {:?}", request);
//!
//! assert!(rp.take_request().is_none());
//! assert!(State::Idle == rq.state());
//!
//! // late cancelation
//! assert!(rq.request(request).is_ok());
//! let request = rp.take_request().unwrap();
//!
//! println!("responder could cancel: {:?}", &rq.cancel().unwrap().is_none());
//! assert!(rp.is_canceled());
//! assert!(rp.respond(response).is_err());
//! assert!(rp.acknowledge_cancel().is_ok());
//! assert!(State::Idle == rq.state());
//!
//! // building into request buffer
//! impl Default for Request {
//!   fn default() -> Self {
//!     Request::That(0)
//!   }
//! }
//!
//! rq.with_request_mut(|r| *r = Request::This(1,2)).unwrap() ;
//! assert!(rq.send_request().is_ok());
//! let request = rp.take_request().unwrap();
//! assert_eq!(request, Request::This(1, 2));
//! println!("rp got request: {:?}", request);
//!
//! // building into response buffer
//! impl Default for Response {
//!   fn default() -> Self {
//!     Response::There(1)
//!   }
//! }
//!
//! rp.with_response_mut(|r| *r = Response::Here(3,2,1)).unwrap();
//! assert!(rp.send_response().is_ok());
//! let response = rq.take_response().unwrap();
//! assert_eq!(response, Response::Here(3,2,1));
//!
//! ```

use core::fmt::{self, Debug};
use core::sync::atomic::Ordering;

#[cfg(loom)]
use loom::{
    cell::UnsafeCell,
    sync::atomic::{AtomicBool, AtomicU8, AtomicUsize},
};

#[cfg(not(loom))]
use core::{
    cell::UnsafeCell,
    sync::atomic::{AtomicBool, AtomicU8, AtomicUsize},
};

#[derive(Clone, Copy)]
pub struct Error;

impl Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("The interchange is busy, this operation could not be performed")
    }
}

#[repr(u8)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
/// State of the RPC interchange
pub enum State {
    /// The requester may send a new request.
    Idle = 0,
    /// The requester is building a request, using the pre-allocated static data as &mut Request
    BuildingRequest = 1,
    /// The request is pending either processing by responder or cancelation by requester.
    Requested = 2,
    /// The responder is building a response, using the pre-allocated static data as &mut Response
    /// It may opportunitstically be canceled by requester.
    BuildingResponse = 3,
    /// The responder sent a response.
    Responded = 4,

    #[doc(hidden)]
    CancelingRequested = 10,
    #[doc(hidden)]
    CancelingBuildingResponse = 11,
    /// The requester canceled the request. Responder needs to acknowledge to return to `Idle`
    /// state.
    Canceled = 12,
}

impl PartialEq<u8> for State {
    #[inline]
    fn eq(&self, other: &u8) -> bool {
        *self as u8 == *other
    }
}

impl From<u8> for State {
    fn from(byte: u8) -> Self {
        match byte {
            1 => State::BuildingRequest,
            2 => State::Requested,
            3 => State::BuildingResponse,
            4 => State::Responded,

            10 => State::CancelingRequested,
            11 => State::CancelingBuildingResponse,
            12 => State::Canceled,

            _ => State::Idle,
        }
    }
}

// the repr(u8) is necessary so MaybeUninit::zeroized.assume_init() is valid and corresponds to
// None
#[repr(u8)]
enum Message<Rq, Rp> {
    None,
    Request(Rq),
    Response(Rp),
}

impl<Rq, Rp> Message<Rq, Rp> {
    fn is_request_state(&self) -> bool {
        matches!(self, Self::Request(_))
    }

    fn is_response_state(&self) -> bool {
        matches!(self, Self::Response(_))
    }

    fn take_rq(&mut self) -> Rq {
        let this = core::mem::replace(self, Message::None);
        match this {
            Message::Request(r) => r,
            _ => unreachable!(),
        }
    }

    fn rq_ref(&self) -> &Rq {
        match *self {
            Self::Request(ref request) => request,
            _ => unreachable!(),
        }
    }

    fn rq_mut(&mut self) -> &mut Rq {
        match *self {
            Self::Request(ref mut request) => request,
            _ => unreachable!(),
        }
    }

    fn take_rp(&mut self) -> Rp {
        let this = core::mem::replace(self, Message::None);
        match this {
            Message::Response(r) => r,
            _ => unreachable!(),
        }
    }

    fn rp_ref(&self) -> &Rp {
        match *self {
            Self::Response(ref response) => response,
            _ => unreachable!(),
        }
    }

    fn rp_mut(&mut self) -> &mut Rp {
        match *self {
            Self::Response(ref mut response) => response,
            _ => unreachable!(),
        }
    }

    fn from_rq(rq: Rq) -> Self {
        Self::Request(rq)
    }

    fn from_rp(rp: Rp) -> Self {
        Self::Response(rp)
    }
}

/// Channel used for Request/Response mechanism.
///
/// The Channel doesn't implement any mechanism to prevent it from beind [`split()`](Channel::split) twice.
/// It is generally recommended to use [`Interchange`](Interchange) instead, which includes a
/// safe API to "Claim" many channels
///
/// ```
/// # #![cfg(not(loom))]
/// # use interchange::{State, Channel};
/// #[derive(Clone, Debug, PartialEq)]
/// pub enum Request {
///     This(u8, u32),
///     That(i64),
/// }
///
/// #[derive(Clone, Debug, PartialEq)]
/// pub enum Response {
///     Here(u8, u8, u8),
///     There(i16),
/// }
///
/// static CHANNEL: Channel<Request,Response> = Channel::new();
///
/// let (mut rq, mut rp) = CHANNEL.split().unwrap();
///
/// assert!(rq.state() == State::Idle);
///
/// // happy path: no cancelation
/// let request = Request::This(1, 2);
/// assert!(rq.request(request).is_ok());
///
/// let request = rp.take_request().unwrap();
/// println!("rp got request: {:?}", request);
///
/// let response = Response::There(-1);
/// assert!(!rp.is_canceled());
/// assert!(rp.respond(response).is_ok());
///
/// let response = rq.take_response().unwrap();
/// println!("rq got response: {:?}", response);
///
/// // early cancelation path
/// assert!(rq.request(request).is_ok());
///
/// let request =  rq.cancel().unwrap().unwrap();
/// println!("responder could cancel: {:?}", request);
///
/// assert!(rp.take_request().is_none());
/// assert!(State::Idle == rq.state());
///
/// // late cancelation
/// assert!(rq.request(request).is_ok());
/// let request = rp.take_request().unwrap();
///
/// println!("responder could cancel: {:?}", &rq.cancel().unwrap().is_none());
/// assert!(rp.is_canceled());
/// assert!(rp.respond(response).is_err());
/// assert!(rp.acknowledge_cancel().is_ok());
/// assert!(State::Idle == rq.state());
///
/// // building into request buffer
/// impl Default for Request {
///   fn default() -> Self {
///     Request::That(0)
///   }
/// }
///
/// rq.with_request_mut(|r| *r = Request::This(1,2)).unwrap() ;
/// assert!(rq.send_request().is_ok());
/// let request = rp.take_request().unwrap();
/// assert_eq!(request, Request::This(1, 2));
/// println!("rp got request: {:?}", request);
///
/// // building into response buffer
/// impl Default for Response {
///   fn default() -> Self {
///     Response::There(1)
///   }
/// }
///
/// rp.with_response_mut(|r| *r = Response::Here(3,2,1)).unwrap();
/// assert!(rp.send_response().is_ok());
/// let response = rq.take_response().unwrap();
/// assert_eq!(response, Response::Here(3,2,1));
///
/// ```
pub struct Channel<Rq, Rp> {
    data: UnsafeCell<Message<Rq, Rp>>,
    state: AtomicU8,
    requester_claimed: AtomicBool,
    responder_claimed: AtomicBool,
}

impl<Rq, Rp> Channel<Rq, Rp> {
    #[cfg(not(loom))]
    const CHANNEL_INIT: Channel<Rq, Rp> = Self::new();

    // Loom's atomics are not const :/
    #[cfg(not(loom))]
    pub const fn new() -> Self {
        Self {
            data: UnsafeCell::new(Message::None),
            state: AtomicU8::new(0),
            requester_claimed: AtomicBool::new(false),
            responder_claimed: AtomicBool::new(false),
        }
    }

    #[cfg(loom)]
    pub fn new() -> Self {
        Self {
            data: UnsafeCell::new(Message::None),
            state: AtomicU8::new(0),
            requester_claimed: AtomicBool::new(false),
            responder_claimed: AtomicBool::new(false),
        }
    }

    /// Obtain the requester end of the channel if it hasn't been taken yet.
    ///
    /// Can be called again if the previously obtained [`Requester`](Requester) has been dropped
    pub fn requester(&self) -> Option<Requester<'_, Rq, Rp>> {
        if self
            .requester_claimed
            .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            Some(Requester { channel: self })
        } else {
            None
        }
    }

    /// Obtain the responder end of the channel if it hasn't been taken yet.
    ///
    /// Can be called again if the previously obtained [`Responder`](Responder) has been dropped
    pub fn responder(&self) -> Option<Responder<'_, Rq, Rp>> {
        if self
            .responder_claimed
            .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            Some(Responder { channel: self })
        } else {
            None
        }
    }

    /// Obtain both the requester and responder ends of the channel.
    ///
    /// Can be called again if the previously obtained [`Responder`](Responder) and [`Requester`](Requester) have been dropped
    pub fn split(&self) -> Option<(Requester<'_, Rq, Rp>, Responder<'_, Rq, Rp>)> {
        Some((self.requester()?, self.responder()?))
    }
}

impl<Rq, Rp> Default for Channel<Rq, Rp> {
    fn default() -> Self {
        Self::new()
    }
}

/// Requester end of a channel
///
/// For a `static` [`Channel`](Channel) or [`Interchange`](Interchange),
/// the requester uses a `'static` lifetime parameter
pub struct Requester<'i, Rq, Rp> {
    channel: &'i Channel<Rq, Rp>,
}

impl<'i, Rq, Rp> Drop for Requester<'i, Rq, Rp> {
    fn drop(&mut self) {
        self.channel
            .requester_claimed
            .store(false, Ordering::Release);
    }
}

impl<'i, Rq, Rp> Requester<'i, Rq, Rp> {
    #[inline]
    fn transition(&self, from: State, to: State) -> bool {
        self.channel
            .state
            .compare_exchange(from as u8, to as u8, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
    }

    #[cfg(not(loom))]
    unsafe fn data(&self) -> &Message<Rq, Rp> {
        &mut *self.channel.data.get()
    }

    #[cfg(not(loom))]
    unsafe fn data_mut(&mut self) -> &mut Message<Rq, Rp> {
        &mut *self.channel.data.get()
    }

    #[cfg(not(loom))]
    unsafe fn with_data<R>(&self, f: impl FnOnce(&Message<Rq, Rp>) -> R) -> R {
        f(&*self.channel.data.get())
    }

    #[cfg(not(loom))]
    unsafe fn with_data_mut<R>(&mut self, f: impl FnOnce(&mut Message<Rq, Rp>) -> R) -> R {
        f(&mut *self.channel.data.get())
    }

    #[cfg(loom)]
    unsafe fn with_data<R>(&self, f: impl FnOnce(&Message<Rq, Rp>) -> R) -> R {
        self.channel.data.with(|i| f(&*i))
    }

    #[cfg(loom)]
    unsafe fn with_data_mut<R>(&mut self, f: impl FnOnce(&mut Message<Rq, Rp>) -> R) -> R {
        self.channel.data.with_mut(|i| f(&mut *i))
    }

    #[inline]
    /// Current state of the channel.
    ///
    /// Informational only!
    ///
    /// The responder may change this state between calls,
    /// internally atomics ensure correctness.
    pub fn state(&self) -> State {
        State::from(self.channel.state.load(Ordering::Acquire))
    }

    /// Send a request to the responder.
    ///
    /// If efficiency is a concern, or requests need multiple steps to
    /// construct, use `request_mut` and `send_request.
    ///
    /// If the RPC state is `Idle`, this always succeeds, else calling
    /// is a logic error and the request is returned.
    pub fn request(&mut self, request: Rq) -> Result<(), Error> {
        if State::Idle == self.channel.state.load(Ordering::Acquire) {
            unsafe {
                self.with_data_mut(|i| *i = Message::from_rq(request));
            }
            self.channel
                .state
                .store(State::Requested as u8, Ordering::Release);
            Ok(())
        } else {
            Err(Error)
        }
    }

    /// Attempt to cancel a request.
    ///
    /// If the responder has not taken the request yet, this succeeds and returns
    /// the request.
    ///
    /// If the responder has taken the request (is processing), we succeed and return None.
    ///
    /// In other cases (`Idle` or `Reponsed`) there is nothing to cancel and we fail.
    pub fn cancel(&mut self) -> Result<Option<Rq>, Error> {
        // we canceled before the responder was even aware of the request.
        if self.transition(State::Requested, State::CancelingRequested) {
            self.channel
                .state
                .store(State::Idle as u8, Ordering::Release);
            return Ok(Some(unsafe { self.with_data_mut(|i| i.take_rq()) }));
        }

        // we canceled after the responder took the request, but before they answered.
        if self.transition(State::BuildingResponse, State::CancelingRequested) {
            // this may not yet be None in case the responder switched state to
            // BuildingResponse but did not take out the request yet.
            // assert!(self.data.is_none());
            self.channel
                .state
                .store(State::Canceled as u8, Ordering::Release);
            return Ok(None);
        }

        Err(Error)
    }

    /// If there is a response waiting, obtain a reference to it
    ///
    /// This may be called multiple times.
    // Safety: We cannot test this with loom efficiently, but given that `with_response` is tested,
    // this is likely correct
    #[cfg(not(loom))]
    pub fn response(&self) -> Result<&Rp, Error> {
        if self.transition(State::Responded, State::Responded) {
            Ok(unsafe { self.data().rp_ref() })
        } else {
            Err(Error)
        }
    }

    /// If there is a request waiting, perform an operation with a reference to it
    ///
    /// This may be called multiple times.
    pub fn with_response<R>(&self, f: impl FnOnce(&Rp) -> R) -> Result<R, Error> {
        if self.transition(State::Responded, State::Responded) {
            Ok(unsafe { self.with_data(|i| f(i.rp_ref())) })
        } else {
            Err(Error)
        }
    }

    /// Look for a response.
    /// If the responder has sent a response, we return it.
    ///
    /// This may be called only once as it move the state to Idle.
    /// If you need copies, clone the request.
    // It is a logic error to call this method if we're Idle or Canceled, but
    // it seems unnecessary to model this.
    pub fn take_response(&mut self) -> Option<Rp> {
        if self.transition(State::Responded, State::Idle) {
            Some(unsafe { self.with_data_mut(|i| i.take_rp()) })
        } else {
            None
        }
    }
}

impl<'i, Rq, Rp> Requester<'i, Rq, Rp>
where
    Rq: Default,
{
    /// Initialize a request with its default values and mutates it with `f`
    ///
    /// This is usefull to build large structures in-place
    pub fn with_request_mut<R>(&mut self, f: impl FnOnce(&mut Rq) -> R) -> Result<R, Error> {
        if self.transition(State::Idle, State::BuildingRequest)
            || self.transition(State::BuildingRequest, State::BuildingRequest)
        {
            let res = unsafe {
                self.with_data_mut(|i| {
                    if !i.is_request_state() {
                        *i = Message::from_rq(Rq::default());
                    }
                    f(i.rq_mut())
                })
            };
            Ok(res)
        } else {
            Err(Error)
        }
    }

    /// Initialize a request with its default values and and return a mutable reference to it
    ///
    /// This is usefull to build large structures in-place
    // Safety: We cannot test this with loom efficiently, but given that `with_request_mut` is tested,
    // this is likely correct
    #[cfg(not(loom))]
    pub fn request_mut(&mut self) -> Result<&mut Rq, Error> {
        if self.transition(State::Idle, State::BuildingRequest)
            || self.transition(State::BuildingRequest, State::BuildingRequest)
        {
            unsafe {
                self.with_data_mut(|i| {
                    if !i.is_request_state() {
                        *i = Message::from_rq(Rq::default());
                    }
                })
            }
            Ok(unsafe { self.data_mut().rq_mut() })
        } else {
            Err(Error)
        }
    }

    /// Send a request that was already placed in the channel using `request_mut` or
    /// `with_request_mut`.
    pub fn send_request(&mut self) -> Result<(), Error> {
        if State::BuildingRequest == self.channel.state.load(Ordering::Acquire)
            && self.transition(State::BuildingRequest, State::Requested)
        {
            Ok(())
        } else {
            // logic error
            Err(Error)
        }
    }
}

/// Responder end of a channel
///
/// For a `static` [`Channel`](Channel) or [`Interchange`](Interchange),
/// the responder uses a `'static` lifetime parameter
pub struct Responder<'i, Rq, Rp> {
    channel: &'i Channel<Rq, Rp>,
}

impl<'i, Rq, Rp> Drop for Responder<'i, Rq, Rp> {
    fn drop(&mut self) {
        self.channel
            .responder_claimed
            .store(false, Ordering::Release);
    }
}

impl<'i, Rq, Rp> Responder<'i, Rq, Rp> {
    #[inline]
    fn transition(&self, from: State, to: State) -> bool {
        self.channel
            .state
            .compare_exchange(from as u8, to as u8, Ordering::SeqCst, Ordering::SeqCst)
            .is_ok()
    }

    #[cfg(not(loom))]
    unsafe fn data(&self) -> &Message<Rq, Rp> {
        &mut *self.channel.data.get()
    }

    #[cfg(not(loom))]
    unsafe fn data_mut(&mut self) -> &mut Message<Rq, Rp> {
        &mut *self.channel.data.get()
    }

    #[cfg(not(loom))]
    unsafe fn with_data<R>(&self, f: impl FnOnce(&Message<Rq, Rp>) -> R) -> R {
        f(&*self.channel.data.get())
    }

    #[cfg(not(loom))]
    unsafe fn with_data_mut<R>(&mut self, f: impl FnOnce(&mut Message<Rq, Rp>) -> R) -> R {
        f(&mut *self.channel.data.get())
    }

    #[cfg(loom)]
    unsafe fn with_data<R>(&self, f: impl FnOnce(&Message<Rq, Rp>) -> R) -> R {
        self.channel.data.with(|i| f(&*i))
    }

    #[cfg(loom)]
    unsafe fn with_data_mut<R>(&mut self, f: impl FnOnce(&mut Message<Rq, Rp>) -> R) -> R {
        self.channel.data.with_mut(|i| f(&mut *i))
    }

    #[inline]
    /// Current state of the channel.
    ///
    /// Informational only!
    ///
    /// The responder may change this state between calls,
    /// internally atomics ensure correctness.
    pub fn state(&self) -> State {
        State::from(self.channel.state.load(Ordering::Acquire))
    }

    /// If there is a request waiting, perform an operation with a reference to it
    ///
    /// This may be called only once as it move the state to BuildingResponse.
    /// If you need copies, use `take_request`
    pub fn with_request<R>(&self, f: impl FnOnce(&Rq) -> R) -> Result<R, Error> {
        if self.transition(State::Requested, State::BuildingResponse) {
            Ok(unsafe { self.with_data(|i| f(i.rq_ref())) })
        } else {
            Err(Error)
        }
    }

    /// If there is a request waiting, obtain a reference to it
    ///
    /// This may be called multiple times.
    // Safety: We cannot test this with loom efficiently, but given that `with_request` is tested,
    // this is likely correct
    #[cfg(not(loom))]
    pub fn request(&self) -> Result<&Rq, Error> {
        if self.transition(State::Requested, State::BuildingResponse) {
            Ok(unsafe { self.data().rq_ref() })
        } else {
            Err(Error)
        }
    }

    /// If there is a request waiting, take a reference to it out
    ///
    /// This may be called only once as it move the state to BuildingResponse.
    /// If you need copies, clone the request.
    pub fn take_request(&mut self) -> Option<Rq> {
        if self.transition(State::Requested, State::BuildingResponse) {
            Some(unsafe { self.with_data_mut(|i| i.take_rq()) })
        } else {
            None
        }
    }

    // Check if requester attempted to cancel
    pub fn is_canceled(&self) -> bool {
        self.channel.state.load(Ordering::SeqCst) == State::Canceled as u8
    }

    // Acknowledge a cancel, thereby setting Channel to Idle state again.
    //
    // It is a logic error to call this method if there is no pending cancellation.
    pub fn acknowledge_cancel(&self) -> Result<(), Error> {
        if self
            .channel
            .state
            .compare_exchange(
                State::Canceled as u8,
                State::Idle as u8,
                Ordering::SeqCst,
                Ordering::SeqCst,
            )
            .is_ok()
        {
            Ok(())
        } else {
            Err(Error)
        }
    }

    /// Respond to a request.
    ///
    /// If efficiency is a concern, or responses need multiple steps to
    /// construct, use `with_response_mut` or `response_mut` and `send_response`.
    ///
    pub fn respond(&mut self, response: Rp) -> Result<(), Error> {
        if State::BuildingResponse == self.channel.state.load(Ordering::Acquire) {
            unsafe {
                self.with_data_mut(|i| *i = Message::from_rp(response));
            }
            self.channel
                .state
                .store(State::Responded as u8, Ordering::Release);
            Ok(())
        } else {
            Err(Error)
        }
    }
}

impl<'i, Rq, Rp> Responder<'i, Rq, Rp>
where
    Rp: Default,
{
    /// Initialize a response with its default values and mutates it with `f`
    ///
    /// This is usefull to build large structures in-place
    pub fn with_response_mut<R>(&mut self, f: impl FnOnce(&mut Rp) -> R) -> Result<R, Error> {
        if self.transition(State::Requested, State::BuildingResponse)
            || self.transition(State::BuildingResponse, State::BuildingResponse)
        {
            let res = unsafe {
                self.with_data_mut(|i| {
                    if !i.is_response_state() {
                        *i = Message::from_rp(Rp::default());
                    }
                    f(i.rp_mut())
                })
            };
            Ok(res)
        } else {
            Err(Error)
        }
    }

    /// Initialize a response with its default values and and return a mutable reference to it
    ///
    /// This is usefull to build large structures in-place
    // Safety: We cannot test this with loom efficiently, but given that `with_response_mut` is tested,
    // this is likely correct
    #[cfg(not(loom))]
    pub fn response_mut(&mut self) -> Result<&mut Rp, Error> {
        if self.transition(State::Requested, State::BuildingResponse)
            || self.transition(State::BuildingResponse, State::BuildingResponse)
        {
            unsafe {
                self.with_data_mut(|i| {
                    if !i.is_response_state() {
                        *i = Message::from_rp(Rp::default());
                    }
                })
            }
            Ok(unsafe { self.data_mut().rp_mut() })
        } else {
            Err(Error)
        }
    }

    /// Send a response that was already placed in the channel using `response_mut` or
    /// `with_response_mut`.
    pub fn send_response(&mut self) -> Result<(), Error> {
        if State::BuildingResponse == self.channel.state.load(Ordering::Acquire)
            && self.transition(State::BuildingResponse, State::Responded)
        {
            Ok(())
        } else {
            // logic error
            Err(Error)
        }
    }
}

unsafe impl<'i, Rq, Rp> Send for Responder<'i, Rq, Rp> {}
unsafe impl<'i, Rq, Rp> Send for Requester<'i, Rq, Rp> {}
unsafe impl<Rq, Rp> Send for Channel<Rq, Rp> {}
unsafe impl<Rq, Rp> Sync for Channel<Rq, Rp> {}

/// Set of `N` channels
///
/// Channels can be claimed with [`claim()`](Self::claim)
///
/// ```
/// # #![cfg(not(loom))]
/// # use interchange::*;
/// # #[derive(Clone, Debug, PartialEq)]
/// # pub enum Request {
/// #     This(u8, u32),
/// #     That(i64),
/// # }
/// #
/// # #[derive(Clone, Debug, PartialEq)]
/// # pub enum Response {
/// #     Here(u8, u8, u8),
/// #     There(i16),
/// # }
/// #
/// static interchange: Interchange<Request, Response,10> = Interchange::new();
///
/// for i in 0..10 {
///     let rq: Requester<'_, Request, Response>;
///     let rp: Responder<'_, Request, Response>;
///     (rq, rp) = interchange.claim().unwrap() ;
/// }
/// ```
pub struct Interchange<Rq, Rp, const N: usize> {
    channels: [Channel<Rq, Rp>; N],
    last_claimed: AtomicUsize,
}

impl<Rq, Rp, const N: usize> Interchange<Rq, Rp, N> {
    /// Create a new Interchange
    #[cfg(not(loom))]
    pub const fn new() -> Self {
        Self {
            channels: [Channel::<Rq, Rp>::CHANNEL_INIT; N],
            last_claimed: AtomicUsize::new(0),
        }
    }

    /// Claim one of the channels of the interchange. Returns None if called more than `N` times.
    pub fn claim(&self) -> Option<(Requester<Rq, Rp>, Responder<Rq, Rp>)> {
        self.as_interchange_ref().claim()
    }

    /// Returns a reference to the interchange with the `N` const-generic removed.
    /// This can avoid the requirement to have `const N: usize` everywhere
    /// ```
    /// # #![cfg(not(loom))]
    /// # use interchange::{State, Interchange, InterchangeRef};
    /// # #[derive(Clone, Debug, PartialEq)]
    /// # pub enum Request {
    /// #     This(u8, u32),
    /// #     That(i64),
    /// # }
    /// # #[derive(Clone, Debug, PartialEq)]
    /// # pub enum Response {
    /// #     Here(u8, u8, u8),
    /// #     There(i16),
    /// # }
    /// static INTERCHANGE_INNER: Interchange<Request, Response, 1> = Interchange::new();
    ///
    /// // The size of the interchange is absent from the type
    /// static INTERCHANGE: InterchangeRef<'static, Request, Response> = INTERCHANGE_INNER.as_interchange_ref();
    ///
    /// let (mut rq, mut rp) = INTERCHANGE.claim().unwrap();
    /// ```
    pub const fn as_interchange_ref(&self) -> InterchangeRef<'_, Rq, Rp> {
        InterchangeRef {
            channels: &self.channels,
            last_claimed: &self.last_claimed,
        }
    }
}

/// Interchange witout the `const N: usize` generic parameter
/// Obtained using [`Interchange::as_interchange_ref`](Interchange::as_interchange_ref)
pub struct InterchangeRef<'alloc, Rq, Rp> {
    channels: &'alloc [Channel<Rq, Rp>],
    last_claimed: &'alloc AtomicUsize,
}
impl<'alloc, Rq, Rp> InterchangeRef<'alloc, Rq, Rp> {
    /// Claim one of the channels of the interchange. Returns None if called more than `N` times.
    pub fn claim(&self) -> Option<(Requester<'alloc, Rq, Rp>, Responder<'alloc, Rq, Rp>)> {
        let index = self.last_claimed.fetch_add(1, Ordering::Relaxed);
        let n = self.channels.len();

        for i in (index % n)..n {
            let tmp = self.channels[i].split();
            if tmp.is_some() {
                return tmp;
            }
        }

        for i in 0..(index % n) {
            let tmp = self.channels[i].split();
            if tmp.is_some() {
                return tmp;
            }
        }
        None
    }
}

#[cfg(not(loom))]
impl<Rq, Rp, const N: usize> Default for Interchange<Rq, Rp, N> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(all(not(loom), test))]
mod tests {
    use super::*;
    #[derive(Clone, Debug, PartialEq)]
    pub enum Request {
        This(u8, u32),
    }
    #[derive(Clone, Debug, PartialEq)]
    pub enum Response {
        Here(u8, u8, u8),
        There(i16),
    }
    impl Default for Response {
        fn default() -> Self {
            Response::There(1)
        }
    }
    impl Default for Request {
        fn default() -> Self {
            Request::This(0, 0)
        }
    }

    #[test]
    fn interchange() {
        static INTERCHANGE: Interchange<Request, Response, 1> = Interchange::new();
        let (mut rq, mut rp) = INTERCHANGE.claim().unwrap();
        assert_eq!(rq.state(), State::Idle);
        // happy path: no cancelation
        let request = Request::This(1, 2);
        assert!(rq.request(request).is_ok());
        let request = rp.take_request().unwrap();
        println!("rp got request: {:?}", request);
        let response = Response::There(-1);
        assert!(!rp.is_canceled());
        assert!(rp.respond(response).is_ok());
        let response = rq.take_response().unwrap();
        println!("rq got response: {:?}", response);
        // early cancelation path
        assert!(rq.request(request).is_ok());
        let request = rq.cancel().unwrap().unwrap();
        println!("responder could cancel: {:?}", request);
        assert!(rp.take_request().is_none());
        assert_eq!(State::Idle, rq.state());
        // late cancelation
        assert!(rq.request(request).is_ok());
        let request = rp.take_request().unwrap();
        println!(
            "responder could cancel: {:?}",
            &rq.cancel().unwrap().is_none()
        );
        assert_eq!(request, Request::This(1, 2));
        assert!(rp.is_canceled());
        assert!(rp.respond(response).is_err());
        assert!(rp.acknowledge_cancel().is_ok());
        assert_eq!(State::Idle, rq.state());
        // building into request buffer
        rq.with_request_mut(|r| *r = Request::This(1, 2)).unwrap();
        assert!(rq.send_request().is_ok());
        let request = rp.take_request().unwrap();
        assert_eq!(request, Request::This(1, 2));
        println!("rp got request: {:?}", request);
        // building into response buffer
        rp.with_response_mut(|r| *r = Response::Here(3, 2, 1))
            .unwrap();
        assert!(rp.send_response().is_ok());
        let response = rq.take_response().unwrap();
        assert_eq!(response, Response::Here(3, 2, 1));
    }

    #[test]
    fn interchange_ref() {
        static INTERCHANGE_INNER: Interchange<Request, Response, 1> = Interchange::new();
        static INTERCHANGE: InterchangeRef<'static, Request, Response> =
            INTERCHANGE_INNER.as_interchange_ref();
        let (mut rq, mut rp) = INTERCHANGE.claim().unwrap();
        assert_eq!(rq.state(), State::Idle);
        // happy path: no cancelation
        let request = Request::This(1, 2);
        assert!(rq.request(request).is_ok());
        let request = rp.take_request().unwrap();
        println!("rp got request: {:?}", request);
        let response = Response::There(-1);
        assert!(!rp.is_canceled());
        assert!(rp.respond(response).is_ok());
        let response = rq.take_response().unwrap();
        println!("rq got response: {:?}", response);
        // early cancelation path
        assert!(rq.request(request).is_ok());
        let request = rq.cancel().unwrap().unwrap();
        println!("responder could cancel: {:?}", request);
        assert!(rp.take_request().is_none());
        assert_eq!(State::Idle, rq.state());
        // late cancelation
        assert!(rq.request(request).is_ok());
        let request = rp.take_request().unwrap();
        println!(
            "responder could cancel: {:?}",
            &rq.cancel().unwrap().is_none()
        );
        assert_eq!(request, Request::This(1, 2));
        assert!(rp.is_canceled());
        assert!(rp.respond(response).is_err());
        assert!(rp.acknowledge_cancel().is_ok());
        assert_eq!(State::Idle, rq.state());
        // building into request buffer
        rq.with_request_mut(|r| *r = Request::This(1, 2)).unwrap();
        assert!(rq.send_request().is_ok());
        let request = rp.take_request().unwrap();
        assert_eq!(request, Request::This(1, 2));
        println!("rp got request: {:?}", request);
        // building into response buffer
        rp.with_response_mut(|r| *r = Response::Here(3, 2, 1))
            .unwrap();
        assert!(rp.send_response().is_ok());
        let response = rq.take_response().unwrap();
        assert_eq!(response, Response::Here(3, 2, 1));
    }
}