interrupt-ref-cell 0.1.1

A `RefCell` for sharing data with interrupt handlers or signal handlers on the same thread.
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
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
//! A [`RefCell`] for sharing data with interrupt handlers or signal handlers on the same thread.
//!
//! [`InterruptRefCell`] is just like [`RefCell`], but disables interrupts during borrows.
//!
//! See [`std::cell`] for a module-level description of cells.
//!
//! # Synchronization
//!
//! This cell synchronizes the current thread _with itself_ via a [`compiler_fence`].
//!
//! A compiler fence is sufficient for sharing a `!Sync` type, such as [`RefCell`], with an interrupt handler on the same thread.
//!
//! [`compiler_fence`]: std::sync::atomic::compiler_fence
//!
//! # Caveats
//!
//! <div class="warning">Interrupts are disabled on a best-effort basis.</div>
//!
//! Holding a reference does not guarantee that interrupts are disabled.
//! Dropping shared references in the wrong order might enable interrupts prematurely.
//! Similarly, you can just enable interrupts manually while holding a reference.
//!
//! # Examples
//!
//! ```
//! use interrupt_ref_cell::{InterruptRefCell, LocalKeyExt};
//!
//! thread_local! {
//!     static X: InterruptRefCell<Vec<i32>> = InterruptRefCell::new(Vec::new());
//! }
//!
//! fn interrupt_handler() {
//!     X.with_borrow_mut(|v| v.push(1));
//! }
//! #
//! # // Setup signal handling for demo
//! #
//! # use nix::libc;
//! # use nix::sys::signal::{self, SigHandler, Signal};
//! #
//! # extern "C" fn handle_sigint(_signal: libc::c_int) {
//! #     interrupt_handler();
//! # }
//! #
//! # let handler = SigHandler::Handler(handle_sigint);
//! # unsafe { signal::signal(Signal::SIGINT, handler) }.unwrap();
//! #
//! # fn raise_interrupt() {
//! #     signal::raise(Signal::SIGINT);
//! # }
//!
//! X.with_borrow(|v| {
//!     // Raise an interrupt
//!     raise_interrupt();
//!     assert_eq!(*v, vec![]);
//! });
//!
//! // The interrupt handler runs
//!
//! X.with_borrow(|v| assert_eq!(*v, vec![1]));
//! ```

#![cfg_attr(target_os = "none", no_std)]

mod interrupt_dropper;
#[cfg(not(target_os = "none"))]
mod local_key;

use core::cell::{BorrowError, BorrowMutError, Ref, RefCell, RefMut};
use core::cmp::Ordering;
use core::ops::{Deref, DerefMut};
use core::{fmt, mem};

use self::interrupt_dropper::InterruptDropper;
#[cfg(not(target_os = "none"))]
pub use self::local_key::LocalKeyExt;

/// A mutable memory location with dynamically checked borrow rules
///
/// See the [module-level documentation](self) for more.
pub struct InterruptRefCell<T: ?Sized> {
    inner: RefCell<T>,
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for InterruptRefCell<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("InterruptRefCell");
        match self.try_borrow() {
            Ok(borrow) => d.field("value", &borrow),
            Err(_) => d.field("value", &format_args!("<borrowed>")),
        };
        d.finish()
    }
}

impl<T> InterruptRefCell<T> {
    /// Creates a new `InterruptRefCell` containing `value`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    /// ```
    #[inline]
    pub const fn new(value: T) -> Self {
        Self {
            inner: RefCell::new(value),
        }
    }

    /// Consumes the `InterruptRefCell`, returning the wrapped value.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// let five = c.into_inner();
    /// ```
    #[inline]
    pub fn into_inner(self) -> T {
        self.inner.into_inner()
    }

    /// Replaces the wrapped value with a new one, returning the old value,
    /// without deinitializing either one.
    ///
    /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html).
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    /// let cell = InterruptRefCell::new(5);
    /// let old_value = cell.replace(6);
    /// assert_eq!(old_value, 5);
    /// assert_eq!(cell, InterruptRefCell::new(6));
    /// ```
    #[inline]
    #[track_caller]
    pub fn replace(&self, t: T) -> T {
        mem::replace(&mut *self.borrow_mut(), t)
    }

    /// Replaces the wrapped value with a new one computed from `f`, returning
    /// the old value, without deinitializing either one.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    /// let cell = InterruptRefCell::new(5);
    /// let old_value = cell.replace_with(|&mut old| old + 1);
    /// assert_eq!(old_value, 5);
    /// assert_eq!(cell, InterruptRefCell::new(6));
    /// ```
    #[inline]
    #[track_caller]
    pub fn replace_with<F: FnOnce(&mut T) -> T>(&self, f: F) -> T {
        let mut_borrow = &mut *self.borrow_mut();
        let replacement = f(mut_borrow);
        mem::replace(mut_borrow, replacement)
    }

    /// Swaps the wrapped value of `self` with the wrapped value of `other`,
    /// without deinitializing either one.
    ///
    /// This function corresponds to [`std::mem::swap`](../mem/fn.swap.html).
    ///
    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently borrowed, or
    /// if `self` and `other` point to the same `InterruptRefCell`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    /// let c = InterruptRefCell::new(5);
    /// let d = InterruptRefCell::new(6);
    /// c.swap(&d);
    /// assert_eq!(c, InterruptRefCell::new(6));
    /// assert_eq!(d, InterruptRefCell::new(5));
    /// ```
    #[inline]
    pub fn swap(&self, other: &Self) {
        mem::swap(&mut *self.borrow_mut(), &mut *other.borrow_mut())
    }
}

impl<T: ?Sized> InterruptRefCell<T> {
    /// Immutably borrows the wrapped value.
    ///
    /// The borrow lasts until the returned `InterruptRef` exits scope. Multiple
    /// immutable borrows can be taken out at the same time.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently mutably borrowed. For a non-panicking variant, use
    /// [`try_borrow`](#method.try_borrow).
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// let borrowed_five = c.borrow();
    /// let borrowed_five2 = c.borrow();
    /// ```
    ///
    /// An example of panic:
    ///
    /// ```should_panic
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// let m = c.borrow_mut();
    /// let b = c.borrow(); // this causes a panic
    /// ```
    #[inline]
    #[track_caller]
    pub fn borrow(&self) -> InterruptRef<'_, T> {
        self.try_borrow().expect("already mutably borrowed")
    }

    /// Immutably borrows the wrapped value, returning an error if the value is currently mutably
    /// borrowed.
    ///
    /// The borrow lasts until the returned `InterruptRef` exits scope. Multiple immutable borrows can be
    /// taken out at the same time.
    ///
    /// This is the non-panicking variant of [`borrow`](#method.borrow).
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// {
    ///     let m = c.borrow_mut();
    ///     assert!(c.try_borrow().is_err());
    /// }
    ///
    /// {
    ///     let m = c.borrow();
    ///     assert!(c.try_borrow().is_ok());
    /// }
    /// ```
    #[inline]
    #[cfg_attr(feature = "debug_interruptrefcell", track_caller)]
    pub fn try_borrow(&self) -> Result<InterruptRef<'_, T>, BorrowError> {
        let guard = interrupts::disable();
        self.inner.try_borrow().map(|inner| {
            let inner = InterruptDropper::from(inner);
            InterruptRef { inner, guard }
        })
    }

    /// Mutably borrows the wrapped value.
    ///
    /// The borrow lasts until the returned `InterruptRefMut` or all `InterruptRefMut`s derived
    /// from it exit scope. The value cannot be borrowed while this borrow is
    /// active.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed. For a non-panicking variant, use
    /// [`try_borrow_mut`](#method.try_borrow_mut).
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new("hello".to_owned());
    ///
    /// *c.borrow_mut() = "bonjour".to_owned();
    ///
    /// assert_eq!(&*c.borrow(), "bonjour");
    /// ```
    ///
    /// An example of panic:
    ///
    /// ```should_panic
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    /// let m = c.borrow();
    ///
    /// let b = c.borrow_mut(); // this causes a panic
    /// ```
    #[inline]
    #[track_caller]
    pub fn borrow_mut(&self) -> InterruptRefMut<'_, T> {
        self.try_borrow_mut().expect("already borrowed")
    }

    /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed.
    ///
    /// The borrow lasts until the returned `InterruptRefMut` or all `InterruptRefMut`s derived
    /// from it exit scope. The value cannot be borrowed while this borrow is
    /// active.
    ///
    /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut).
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// {
    ///     let m = c.borrow();
    ///     assert!(c.try_borrow_mut().is_err());
    /// }
    ///
    /// assert!(c.try_borrow_mut().is_ok());
    /// ```
    #[inline]
    #[cfg_attr(feature = "debug_interruptrefcell", track_caller)]
    pub fn try_borrow_mut(&self) -> Result<InterruptRefMut<'_, T>, BorrowMutError> {
        let guard = interrupts::disable();
        self.inner.try_borrow_mut().map(|inner| {
            let inner = InterruptDropper::from(inner);
            InterruptRefMut { inner, guard }
        })
    }

    /// Returns a raw pointer to the underlying data in this cell.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// let ptr = c.as_ptr();
    /// ```
    #[inline]
    pub fn as_ptr(&self) -> *mut T {
        self.inner.as_ptr()
    }

    /// Returns a mutable reference to the underlying data.
    ///
    /// Since this method borrows `InterruptRefCell` mutably, it is statically guaranteed
    /// that no borrows to the underlying data exist. The dynamic checks inherent
    /// in [`borrow_mut`] and most other methods of `InterruptRefCell` are therefore
    /// unnecessary.
    ///
    /// This method can only be called if `InterruptRefCell` can be mutably borrowed,
    /// which in general is only the case directly after the `InterruptRefCell` has
    /// been created. In these situations, skipping the aforementioned dynamic
    /// borrowing checks may yield better ergonomics and runtime-performance.
    ///
    /// In most situations where `InterruptRefCell` is used, it can't be borrowed mutably.
    /// Use [`borrow_mut`] to get mutable access to the underlying data then.
    ///
    /// [`borrow_mut`]: InterruptRefCell::borrow_mut()
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let mut c = InterruptRefCell::new(5);
    /// *c.get_mut() += 1;
    ///
    /// assert_eq!(c, InterruptRefCell::new(6));
    /// ```
    #[inline]
    pub fn get_mut(&mut self) -> &mut T {
        self.inner.get_mut()
    }

    /// Immutably borrows the wrapped value, returning an error if the value is
    /// currently mutably borrowed.
    ///
    /// # Safety
    ///
    /// Unlike `InterruptRefCell::borrow`, this method is unsafe because it does not
    /// return a `InterruptRef`, thus leaving the borrow flag untouched. Mutably
    /// borrowing the `InterruptRefCell` while the reference returned by this method
    /// is alive is undefined behaviour.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    ///
    /// {
    ///     let m = c.borrow_mut();
    ///     assert!(unsafe { c.try_borrow_unguarded() }.is_err());
    /// }
    ///
    /// {
    ///     let m = c.borrow();
    ///     assert!(unsafe { c.try_borrow_unguarded() }.is_ok());
    /// }
    /// ```
    #[inline]
    pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> {
        let guard = interrupts::disable();
        let ret = self.inner.try_borrow_unguarded();
        drop(guard);
        ret
    }
}

impl<T: Default> InterruptRefCell<T> {
    /// Takes the wrapped value, leaving `Default::default()` in its place.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::InterruptRefCell;
    ///
    /// let c = InterruptRefCell::new(5);
    /// let five = c.take();
    ///
    /// assert_eq!(five, 5);
    /// assert_eq!(c.into_inner(), 0);
    /// ```
    pub fn take(&self) -> T {
        self.replace(Default::default())
    }
}

impl<T: Clone> Clone for InterruptRefCell<T> {
    /// # Panics
    ///
    /// Panics if the value is currently mutably borrowed.
    #[inline]
    #[track_caller]
    fn clone(&self) -> InterruptRefCell<T> {
        InterruptRefCell::new(self.borrow().clone())
    }

    /// # Panics
    ///
    /// Panics if `other` is currently mutably borrowed.
    #[inline]
    #[track_caller]
    fn clone_from(&mut self, other: &Self) {
        self.get_mut().clone_from(&other.borrow())
    }
}

impl<T: Default> Default for InterruptRefCell<T> {
    /// Creates a `InterruptRefCell<T>`, with the `Default` value for T.
    #[inline]
    fn default() -> InterruptRefCell<T> {
        InterruptRefCell::new(Default::default())
    }
}

impl<T: ?Sized + PartialEq> PartialEq for InterruptRefCell<T> {
    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn eq(&self, other: &InterruptRefCell<T>) -> bool {
        *self.borrow() == *other.borrow()
    }
}

impl<T: ?Sized + Eq> Eq for InterruptRefCell<T> {}

impl<T: ?Sized + PartialOrd> PartialOrd for InterruptRefCell<T> {
    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn partial_cmp(&self, other: &InterruptRefCell<T>) -> Option<Ordering> {
        self.borrow().partial_cmp(&*other.borrow())
    }

    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn lt(&self, other: &InterruptRefCell<T>) -> bool {
        *self.borrow() < *other.borrow()
    }

    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn le(&self, other: &InterruptRefCell<T>) -> bool {
        *self.borrow() <= *other.borrow()
    }

    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn gt(&self, other: &InterruptRefCell<T>) -> bool {
        *self.borrow() > *other.borrow()
    }

    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn ge(&self, other: &InterruptRefCell<T>) -> bool {
        *self.borrow() >= *other.borrow()
    }
}

impl<T: ?Sized + Ord> Ord for InterruptRefCell<T> {
    /// # Panics
    ///
    /// Panics if the value in either `InterruptRefCell` is currently mutably borrowed.
    #[inline]
    fn cmp(&self, other: &InterruptRefCell<T>) -> Ordering {
        self.borrow().cmp(&*other.borrow())
    }
}

impl<T> From<T> for InterruptRefCell<T> {
    /// Creates a new `InterruptRefCell<T>` containing the given value.
    fn from(t: T) -> InterruptRefCell<T> {
        InterruptRefCell::new(t)
    }
}

/// Wraps a borrowed reference to a value in a `InterruptRefCell` box.
/// A wrapper type for an immutably borrowed value from a `InterruptRefCell<T>`.
///
/// See the [module-level documentation](self) for more.
pub struct InterruptRef<'b, T: ?Sized + 'b> {
    inner: InterruptDropper<Ref<'b, T>>,
    guard: interrupts::Guard,
}

impl<T: ?Sized> Deref for InterruptRef<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}

impl<'b, T: ?Sized> InterruptRef<'b, T> {
    /// Copies a `InterruptRef`.
    ///
    /// The `InterruptRefCell` is already immutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `InterruptRef::clone(...)`. A `Clone` implementation or a method would interfere
    /// with the widespread use of `r.borrow().clone()` to clone the contents of
    /// a `InterruptRefCell`.
    #[allow(clippy::should_implement_trait)]
    #[must_use]
    #[inline]
    pub fn clone(orig: &InterruptRef<'b, T>) -> InterruptRef<'b, T> {
        let guard = interrupts::disable();
        let inner = InterruptDropper::from(Ref::clone(&orig.inner));
        InterruptRef { inner, guard }
    }

    /// Makes a new `InterruptRef` for a component of the borrowed data.
    ///
    /// The `InterruptRefCell` is already immutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as `InterruptRef::map(...)`.
    /// A method would interfere with methods of the same name on the contents
    /// of a `InterruptRefCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::{InterruptRefCell, InterruptRef};
    ///
    /// let c = InterruptRefCell::new((5, 'b'));
    /// let b1: InterruptRef<'_, (u32, char)> = c.borrow();
    /// let b2: InterruptRef<'_, u32> = InterruptRef::map(b1, |t| &t.0);
    /// assert_eq!(*b2, 5)
    /// ```
    #[inline]
    pub fn map<U: ?Sized, F>(orig: InterruptRef<'b, T>, f: F) -> InterruptRef<'b, U>
    where
        F: FnOnce(&T) -> &U,
    {
        let InterruptRef { inner, guard } = orig;
        let inner = InterruptDropper::from(Ref::map(InterruptDropper::into_inner(inner), f));
        InterruptRef { inner, guard }
    }

    /// Makes a new `InterruptRef` for an optional component of the borrowed data. The
    /// original guard is returned as an `Err(..)` if the closure returns
    /// `None`.
    ///
    /// The `InterruptRefCell` is already immutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `InterruptRef::filter_map(...)`. A method would interfere with methods of the same
    /// name on the contents of a `InterruptRefCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::{InterruptRefCell, InterruptRef};
    ///
    /// let c = InterruptRefCell::new(vec![1, 2, 3]);
    /// let b1: InterruptRef<'_, Vec<u32>> = c.borrow();
    /// let b2: Result<InterruptRef<'_, u32>, _> = InterruptRef::filter_map(b1, |v| v.get(1));
    /// assert_eq!(*b2.unwrap(), 2);
    /// ```
    #[allow(clippy::result_large_err)]
    #[inline]
    pub fn filter_map<U: ?Sized, F>(
        orig: InterruptRef<'b, T>,
        f: F,
    ) -> Result<InterruptRef<'b, U>, Self>
    where
        F: FnOnce(&T) -> Option<&U>,
    {
        let guard = interrupts::disable();
        let filter_map = Ref::filter_map(InterruptDropper::into_inner(orig.inner), f);
        drop(guard);
        match filter_map {
            Ok(inner) => {
                let inner = InterruptDropper::from(inner);
                Ok(InterruptRef {
                    inner,
                    guard: orig.guard,
                })
            }
            Err(inner) => {
                let inner = InterruptDropper::from(inner);
                Err(InterruptRef {
                    inner,
                    guard: orig.guard,
                })
            }
        }
    }

    /// Splits a `InterruptRef` into multiple `InterruptRef`s for different components of the
    /// borrowed data.
    ///
    /// The `InterruptRefCell` is already immutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `InterruptRef::map_split(...)`. A method would interfere with methods of the same
    /// name on the contents of a `InterruptRefCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::{InterruptRefCell, InterruptRef};
    ///
    /// let cell = InterruptRefCell::new([1, 2, 3, 4]);
    /// let borrow = cell.borrow();
    /// let (begin, end) = InterruptRef::map_split(borrow, |slice| slice.split_at(2));
    /// assert_eq!(*begin, [1, 2]);
    /// assert_eq!(*end, [3, 4]);
    /// ```
    #[inline]
    pub fn map_split<U: ?Sized, V: ?Sized, F>(
        orig: InterruptRef<'b, T>,
        f: F,
    ) -> (InterruptRef<'b, U>, InterruptRef<'b, V>)
    where
        F: FnOnce(&T) -> (&U, &V),
    {
        let guard = interrupts::disable();
        let (a, b) = Ref::map_split(InterruptDropper::into_inner(orig.inner), f);
        (
            InterruptRef {
                inner: InterruptDropper::from(a),
                guard,
            },
            InterruptRef {
                inner: InterruptDropper::from(b),
                guard: orig.guard,
            },
        )
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for InterruptRef<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for InterruptRef<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl<'b, T: ?Sized> InterruptRefMut<'b, T> {
    /// Makes a new `InterruptRefMut` for a component of the borrowed data, e.g., an enum
    /// variant.
    ///
    /// The `InterruptRefCell` is already mutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `InterruptRefMut::map(...)`. A method would interfere with methods of the same
    /// name on the contents of a `InterruptRefCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::{InterruptRefCell, InterruptRefMut};
    ///
    /// let c = InterruptRefCell::new((5, 'b'));
    /// {
    ///     let b1: InterruptRefMut<'_, (u32, char)> = c.borrow_mut();
    ///     let mut b2: InterruptRefMut<'_, u32> = InterruptRefMut::map(b1, |t| &mut t.0);
    ///     assert_eq!(*b2, 5);
    ///     *b2 = 42;
    /// }
    /// assert_eq!(*c.borrow(), (42, 'b'));
    /// ```
    #[inline]
    pub fn map<U: ?Sized, F>(orig: InterruptRefMut<'b, T>, f: F) -> InterruptRefMut<'b, U>
    where
        F: FnOnce(&mut T) -> &mut U,
    {
        let InterruptRefMut { inner, guard } = orig;
        let inner = InterruptDropper::from(RefMut::map(InterruptDropper::into_inner(inner), f));
        InterruptRefMut { inner, guard }
    }

    /// Makes a new `InterruptRefMut` for an optional component of the borrowed data. The
    /// original guard is returned as an `Err(..)` if the closure returns
    /// `None`.
    ///
    /// The `InterruptRefCell` is already mutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `InterruptRefMut::filter_map(...)`. A method would interfere with methods of the
    /// same name on the contents of a `InterruptRefCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::{InterruptRefCell, InterruptRefMut};
    ///
    /// let c = InterruptRefCell::new(vec![1, 2, 3]);
    ///
    /// {
    ///     let b1: InterruptRefMut<'_, Vec<u32>> = c.borrow_mut();
    ///     let mut b2: Result<InterruptRefMut<'_, u32>, _> = InterruptRefMut::filter_map(b1, |v| v.get_mut(1));
    ///
    ///     if let Ok(mut b2) = b2 {
    ///         *b2 += 2;
    ///     }
    /// }
    ///
    /// assert_eq!(*c.borrow(), vec![1, 4, 3]);
    /// ```
    #[allow(clippy::result_large_err)]
    #[inline]
    pub fn filter_map<U: ?Sized, F>(
        orig: InterruptRefMut<'b, T>,
        f: F,
    ) -> Result<InterruptRefMut<'b, U>, Self>
    where
        F: FnOnce(&mut T) -> Option<&mut U>,
    {
        let guard = interrupts::disable();
        let filter_map = RefMut::filter_map(InterruptDropper::into_inner(orig.inner), f);
        drop(guard);
        match filter_map {
            Ok(inner) => {
                let inner = InterruptDropper::from(inner);
                Ok(InterruptRefMut {
                    inner,
                    guard: orig.guard,
                })
            }
            Err(inner) => {
                let inner = InterruptDropper::from(inner);
                Err(InterruptRefMut {
                    inner,
                    guard: orig.guard,
                })
            }
        }
    }

    /// Splits a `InterruptRefMut` into multiple `InterruptRefMut`s for different components of the
    /// borrowed data.
    ///
    /// The underlying `InterruptRefCell` will remain mutably borrowed until both
    /// returned `InterruptRefMut`s go out of scope.
    ///
    /// The `InterruptRefCell` is already mutably borrowed, so this cannot fail.
    ///
    /// This is an associated function that needs to be used as
    /// `InterruptRefMut::map_split(...)`. A method would interfere with methods of the
    /// same name on the contents of a `InterruptRefCell` used through `Deref`.
    ///
    /// # Examples
    ///
    /// ```
    /// use interrupt_ref_cell::{InterruptRefCell, InterruptRefMut};
    ///
    /// let cell = InterruptRefCell::new([1, 2, 3, 4]);
    /// let borrow = cell.borrow_mut();
    /// let (mut begin, mut end) = InterruptRefMut::map_split(borrow, |slice| slice.split_at_mut(2));
    /// assert_eq!(*begin, [1, 2]);
    /// assert_eq!(*end, [3, 4]);
    /// begin.copy_from_slice(&[4, 3]);
    /// end.copy_from_slice(&[2, 1]);
    /// ```
    #[inline]
    pub fn map_split<U: ?Sized, V: ?Sized, F>(
        orig: InterruptRefMut<'b, T>,
        f: F,
    ) -> (InterruptRefMut<'b, U>, InterruptRefMut<'b, V>)
    where
        F: FnOnce(&mut T) -> (&mut U, &mut V),
    {
        let guard = interrupts::disable();
        let (a, b) = RefMut::map_split(InterruptDropper::into_inner(orig.inner), f);
        (
            InterruptRefMut {
                inner: InterruptDropper::from(a),
                guard,
            },
            InterruptRefMut {
                inner: InterruptDropper::from(b),
                guard: orig.guard,
            },
        )
    }
}

/// A wrapper type for a mutably borrowed value from a `InterruptRefCell<T>`.
///
/// See the [module-level documentation](self) for more.
pub struct InterruptRefMut<'b, T: ?Sized + 'b> {
    inner: InterruptDropper<RefMut<'b, T>>,
    guard: interrupts::Guard,
}

impl<T: ?Sized> Deref for InterruptRefMut<'_, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.inner.deref()
    }
}

impl<T: ?Sized> DerefMut for InterruptRefMut<'_, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.deref_mut()
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for InterruptRefMut<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for InterruptRefMut<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.fmt(f)
    }
}