flexcell 0.1.0-alpha.1

A flexible cell that allows safe circumvention of double borrow issues.
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
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
//! [FlexCell](crate::FlexCell) is a data structure designed to replace Rust's [RefCell](::core::cell::RefCell), allowing safe circumvention of double borrow issues.
//! By using FlexCell, you can temporarily relinquish an already borrowed reference, enabling it to be safely reborrowed without causing a double borrow error.
//!
//!
//! # Problem to Solve
//!
//! [RefCell](::core::cell::RefCell) is a powerful tool that provides interior mutability, but it can be inconvenient in certain situations.
//! For example, within a function that takes a mutable reference from a [`RefMut`](::core::cell::RefMut), you cannot borrow the same RefCell again.
//!
//! In most cases, this restriction is not an issue because you have already mutably borrowed the RefCell and passed it as an argument, so there is no need to reborrow it.
//! However, if a modification requiring the value of the RefCell occurs at the end of a long chain of nested function calls, you would need to add `Option<&mut T>` type arguments to the signatures of all functions in the call chain to eventually pass it to the function that requires the RefCell.
//! This interface modification can be quite cumbersome and may require changes to the entire project's code.
//!
//! [FlexCell](crate::FlexCell) is designed to solve this problem. With FlexCell, you can temporarily relinquish a borrowed reference and safely reborrow it in a lower call chain.
//! This allows you to flexibly manipulate internal values even in complex cyclic dependency patterns or recursive calls.
//!
//!
//! # Key Features
//!
//! - **Lending Mechanism**: FlexCell provides a mechanism to temporarily relinquish (or lend) an already borrowed value (or an entirely new external value).
//! - **Closure-Based Interface**: Unlike RefCell's guard-based interface, FlexCell uses closures to borrow internal values.
//! - **Safe Memory Management**: FlexCell adheres to Rust's memory safety model, managing the provenance and permissions of pointers internally.
//!
//!
//! # Examples
//!
//! ## Borrowing Internal Values ([`with`](crate::FlexCell::with), [`with_mut`](crate::FlexCell::with_mut))
//!
//! Here is an example of putting a simple `Vec` into a `FlexCell` and performing read/write operations.
//! Each time the given closure ends, the internal borrow is released, allowing subsequent calls to [`with`](crate::FlexCell::with) or [`with_mut`](crate::FlexCell::with_mut).
//!
//! ```rust
//! use flexcell::FlexCell;
//!
//! // Create a FlexCell containing a vector
//! let cell = FlexCell::new(vec![1, 2, 3]);
//!
//! // Borrow read-only
//! cell.with(|value| {
//!     assert_eq!(*value, vec![1, 2, 3]); // Check initial value
//! });
//!
//! // Borrow mutably
//! cell.with_mut(|value| {
//!     value.push(4);
//! });
//!
//! // Borrow read-only again to check the value
//! cell.with(|value| {
//!     assert_eq!(*value, vec![1, 2, 3, 4]); // Check modified value
//! });
//! ```
//!
//!
//! ## Lending External Values ([`lend_ref`](crate::FlexCell::lend_ref), [`lend`](crate::FlexCell::lend))
//!
//! You can also temporarily lend an external variable to a `FlexCell` instead of using the value already inside it.
//! In this case, `FlexCell` temporarily replaces its own value with a pointer to the external variable.
//!
//! ```rust
//! use flexcell::FlexCell;
//!
//! let cell = FlexCell::new(String::from("original"));
//! let mut external = String::from("external");
//!
//! cell.lend(&mut external, || {
//!     cell.with_mut(|s| {
//!         s.push_str(" modified");
//!     });
//! });
//!
//! // After the lend closure ends, the external value is modified
//! assert_eq!(external, "external modified");
//!
//! // Meanwhile, the original value is restored
//! cell.with(|val| {
//!     assert_eq!(*val, "original");
//! });
//! ```
//!
//! In the code above, the [`lend`](crate::FlexCell::lend) operation allows `FlexCell` to temporarily point to the external variable (`external`), enabling read/write operations within the closure.
//! After the closure ends, the original value of `FlexCell` is restored.
//!
//!
//! ## Replacing, Taking, and Setting Values ([`replace`](crate::FlexCell::replace), [`take`](crate::FlexCell::take), [`set`](crate::FlexCell::set))
//!
//! When `FlexCell` has full ownership of the internal value (e.g., created with [`new`](crate::FlexCell::new) or set with [`set`](crate::FlexCell::set)), you can take the value out or replace it.
//!
//! ```rust
//! use flexcell::FlexCell;
//!
//! let cell = FlexCell::new(vec![10, 20, 30]);
//!
//! // Take the value out
//! let fully_owned = cell.take();
//! assert_eq!(fully_owned, vec![10, 20, 30]); // Check the taken value
//!
//! // Set a new value
//! cell.set(vec![99, 100]);
//! cell.with(|value| {
//!     assert_eq!(*value, vec![99, 100]); // Check the new value
//! });
//!
//! // Replace the value
//! let old = cell.replace(vec![0]);
//! assert_eq!(old, vec![99, 100]); // Check the replaced old value
//! cell.with(|value| {
//!     assert_eq!(*value, vec![0]); // Check the new value after replacement
//! });
//! ```
//!
//! However, you cannot regain full ownership of the internal value if it is already borrowed with [`with`](crate::FlexCell::with) or [`with_mut`](crate::FlexCell::with_mut).
//! In such cases, you should use [`try_take`](crate::FlexCell::try_take) or [`try_replace`](crate::FlexCell::try_replace) methods to handle errors.
//!
//!
//! # Limitations and Precautions
//!
//! ## Lending Does Not Always Increase Permissions
//! Calling [`lend`](crate::FlexCell::lend) or [`lend_ref`](crate::FlexCell::lend_ref) on FlexCell temporarily replaces the internal reference state, allowing reborrowing with different values (or the same value with different permissions).
//! However, this does not always increase permissions.
//! Requests requiring higher permission levels than the lent reference will be impossible until the closure ends and the state is restored, or until another appropriate [`lend`](crate::FlexCell::lend) or [`set`](crate::FlexCell::set) is performed.
//!
//! For example:
//! - While [`lend`](crate::FlexCell::lend) is active, you cannot call [`take`](crate::FlexCell::take) or [`replace`](crate::FlexCell::replace) which require full ownership of the internal value.
//! - While [`lend_ref`](crate::FlexCell::lend_ref) is active, you cannot call [`with_mut`](crate::FlexCell::with_mut).
//!
//!
//! ## [`take`](crate::FlexCell::take) and [`replace`](crate::FlexCell::replace) Can Fail
//! FlexCell must fully own the internal value to perform [`take`](crate::FlexCell::take) or [`replace`](crate::FlexCell::replace).
//! If the value is already borrowed (read-only or mutable), attempting [`take`](crate::FlexCell::take) and [`replace`](crate::FlexCell::replace) will result in a [`ConsumeError`](crate::errors::ConsumeError).
//! You can handle errors using [`try_take`](crate::FlexCell::try_take) and [`try_replace`](crate::FlexCell::try_replace) methods.
//!
//!
//! ## Values [`set`](crate::FlexCell::set) Within Borrowing/Lending Contexts Are Temporary
//! Values [`set`](crate::FlexCell::set) within closures passed to [`with`](crate::FlexCell::with), [`with_mut`](crate::FlexCell::with_mut), [`lend_ref`](crate::FlexCell::lend_ref), or [`lend`](crate::FlexCell::lend) are only valid during the execution of the closure.
//! Once the closure ends, the internal state is restored, and the set value is dropped.
//!
//! Simply put:
//! - Values [`set`](crate::FlexCell::set) within a closure are temporarily valid only during the closure's execution.
//! - Values [`set`](crate::FlexCell::set) within a closure are dropped and disappear when the closure ends.
//!
//!
//! ## Single-Threaded Use
//! Currently, FlexCell is based on [`core::cell::Cell`](::core::cell::Cell), so it does not support [`Sync`](::core::marker::Sync) across multiple threads.
//!
//!
//! # Design Decisions
//!
//! ## Closure-Based Interface
//!
//! While RefCell provides a _guard-based_ interface, FlexCell offers a _closure-based_ interface.
//! Using guards allows delegating lock release to other procedures, providing more flexibility.
//! However, FlexCell adopts the closure approach to enforce the order of lock and unlock, preventing issues in nested borrow/lend patterns and ensuring a safe API.
//!
//!
//! ## Conceptually an `Option<Box<T>>` with Interior Mutability
//!
//! The internal value of FlexCell is allocated on the heap using `Box<T>`, and only the pointer is extracted and used through [`Box::leak`](::alloc::boxed::Box::leak).
//! Considering the potential use cases and the convenience and stability of the design, handling the value as a heap-allocated pointer is deemed more appropriate despite some overhead.
//!
//! Additionally, the value inside FlexCell can be taken, set, or replaced, similar to `Option<T>`.
//! This approach aims to provide an API that treats the internal unborrowed `Box<T>` of FlexCell as a pointer, similar to `&T` or `&mut T`.
//!
//!
//! ## Lending Instead of Unborrowing
//!
//! FlexCell does not _unborrow_ values. Instead, it safely _lends_ a new pointer that can be borrowed over the already borrowed reference, which cannot be reborrowed.
//! Therefore, whether the reference provided to the [`lend_ref`](crate::FlexCell::lend_ref) or [`lend`](crate::FlexCell::lend) method points to the same value originally inside FlexCell or not, it will not cause a runtime error.
//! The value will simply be used in subsequent borrows.
//!
//! In Rust's memory safety model, the provenance and permissions of pointers must be clearly defined.
//! To prevent undefined behavior, each lend must replace the internal reference with a new pointer with appropriate provenance.
//! This means treating the two pointers as entirely different even if they point to the same memory address.
//!
//! In most use cases I envision, the pointer lent to FlexCell will point to the same value originally inside it.
//! However, due to the reasons mentioned above, FlexCell does not directly restrict the address of the provided reference: there cannot be any optimization benefit from this information in the design, and comparing the two references would only incur runtime costs.

#![cfg_attr(not(test), no_std)]
#![allow(rustdoc::redundant_explicit_links)]

extern crate alloc;

use alloc::boxed::Box;
use core::cell::Cell;
use core::mem::ManuallyDrop;
use core::ptr::NonNull;

pub(crate) mod pointer;
use pointer::Pointer;

/// Contains all error types used by the crate.
pub mod errors;
use errors::{BorrowError, BorrowMutError, ConsumeError};

/// A flexible cell that allows safe circumvention of double borrow issues.
///
/// It provides a mechanism to temporarily relinquish an already borrowed reference or lend an entirely new external value, enabling it to be safely reborrowed without causing a double borrow error.
///
/// # Examples
///
/// ## Creating a new `FlexCell`
///
/// ```rust
/// use flexcell::FlexCell;
///
/// let cell = FlexCell::new(5);
/// ```
///
/// ## Borrowing the value immutably
///
/// ```rust
/// use flexcell::FlexCell;
///
/// let cell = FlexCell::new(5);
/// cell.with(|value| {
///     assert_eq!(*value, 5);
/// });
/// ```
///
/// ## Borrowing the value mutably
///
/// ```rust
/// use flexcell::FlexCell;
///
/// let cell = FlexCell::new(5);
/// cell.with_mut(|value| {
///     *value = 10;
/// });
/// cell.with(|value| {
///     assert_eq!(*value, 10);
/// });
/// ```
///
/// ## Temporarily lending an external value
///
/// ```rust
/// use flexcell::FlexCell;
///
/// let cell = FlexCell::new(String::from("original"));
/// let mut external = String::from("external");
///
/// cell.lend(&mut external, || {
///     cell.with_mut(|s| {
///         s.push_str(" modified");
///     });
/// });
///
/// assert_eq!(external, "external modified");
/// cell.with(|val| {
///     assert_eq!(*val, "original");
/// });
/// ```
#[derive(Debug)]
pub struct FlexCell<T: ?Sized>(Cell<Pointer<T>>);

impl<T: ?Sized> Drop for FlexCell<T> {
    #[inline]
    fn drop(&mut self) {
        drop(self.0.get().into_guard());
    }
}

struct Guard<'a, T: ?Sized>(&'a Cell<Pointer<T>>, Pointer<T>);

impl<'a, T: ?Sized> Guard<'a, T> {
    fn create<R>(cell: &'a Cell<Pointer<T>>, pointer: Pointer<T>, f: impl FnOnce() -> R) -> R {
        let guard = Self(cell, cell.replace(pointer));
        let result = f();
        drop(guard);
        result
    }
}

impl<T: ?Sized> Drop for Guard<'_, T> {
    #[inline]
    fn drop(&mut self) {
        drop(self.0.replace(self.1).into_guard());
    }
}

impl<T> FlexCell<T> {
    /// Creates a new `FlexCell` containing the given value.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// ```
    #[inline]
    pub fn new(value: T) -> Self {
        Self::from_boxed(Box::new(value))
    }

    /// Consumes the `FlexCell`, returning the wrapped value.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let value = cell.into_inner();
    /// assert_eq!(value, 5);
    /// ```
    #[inline]
    #[track_caller]
    pub fn into_inner(self) -> T {
        self.try_into_inner().unwrap()
    }

    /// Sets the value inside the `FlexCell`, replacing the current value.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// cell.set(10);
    /// cell.with(|value| assert_eq!(*value, 10));
    /// ```
    #[inline]
    pub fn set(&self, value: T) {
        self.set_boxed(Box::new(value));
    }

    /// Takes the value out of the `FlexCell`, leaving it empty.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let value = cell.take();
    /// assert_eq!(value, 5);
    /// ```
    #[inline]
    #[track_caller]
    pub fn take(&self) -> T {
        self.try_take().unwrap()
    }

    /// Replaces the value inside the `FlexCell`, returning the old value.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let old_value = cell.replace(10);
    /// assert_eq!(old_value, 5);
    /// cell.with(|value| assert_eq!(*value, 10));
    /// ```
    #[inline]
    #[track_caller]
    #[must_use = "If you don't need the old value, consider using `set` instead."]
    pub fn replace(&self, value: T) -> T {
        self.try_replace(value).unwrap()
    }

    /// Attempts to consume the `FlexCell`, returning the wrapped value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let value = cell.try_into_inner().unwrap();
    /// assert_eq!(value, 5);
    /// ```
    #[inline]
    pub fn try_into_inner(self) -> Result<T, ConsumeError> {
        self.try_into_boxed().map(|value| *value)
    }

    /// Attempts to take the value out of the `FlexCell`, leaving it empty.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let value = cell.try_take().unwrap();
    /// assert_eq!(value, 5);
    /// ```
    #[inline]
    pub fn try_take(&self) -> Result<T, ConsumeError> {
        self.try_take_boxed().map(|value| *value)
    }

    /// Attempts to replace the value inside the `FlexCell`, returning the old value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let old_value = cell.try_replace(10).unwrap();
    /// assert_eq!(old_value, 5);
    /// cell.with(|value| assert_eq!(*value, 10));
    /// ```
    #[inline]
    #[must_use = "If you don't need the old value, consider using `set` instead."]
    pub fn try_replace(&self, value: T) -> Result<T, ConsumeError> {
        self.try_replace_boxed(Box::new(value)).map(|value| *value)
    }
}

impl<T: ?Sized> FlexCell<T> {
    /// Returns a raw pointer to the value inside the `FlexCell`, or `None` if the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let ptr = cell.as_ptr().unwrap();
    /// ```
    pub fn as_ptr(&self) -> Option<NonNull<T>> {
        match self.0.get() {
            Pointer::Ref(ptr) | Pointer::Mut(ptr) | Pointer::Boxed(ptr) => Some(ptr),
            Pointer::Null => None,
        }
    }

    /// Creates an empty `FlexCell`.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell: FlexCell<i32> = FlexCell::empty();
    /// assert!(cell.as_ptr().is_none());
    /// ```
    pub const fn empty() -> Self {
        Self(Cell::new(Pointer::Null))
    }

    /// Creates a `FlexCell` from a boxed value.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::from_boxed(Box::new(5));
    /// ```
    pub fn from_boxed(value: Box<T>) -> Self {
        Self(Cell::new(Pointer::from_boxed(value)))
    }

    /// Consumes the `FlexCell`, returning the boxed value.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let boxed_value = cell.into_boxed();
    /// assert_eq!(*boxed_value, 5);
    /// ```
    #[inline]
    #[track_caller]
    pub fn into_boxed(self) -> Box<T> {
        self.try_into_boxed().unwrap()
    }

    /// Sets the boxed value inside the `FlexCell`, replacing the current value.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// cell.set_boxed(Box::new(10));
    /// cell.with(|value| assert_eq!(*value, 10));
    /// ```
    pub fn set_boxed(&self, value: Box<T>) {
        drop(self.0.replace(Pointer::from_boxed(value)).into_guard());
    }

    /// Takes the boxed value out of the `FlexCell`, leaving it empty.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let boxed_value = cell.take_boxed();
    /// assert_eq!(*boxed_value, 5);
    /// ```
    #[inline]
    #[track_caller]
    pub fn take_boxed(&self) -> Box<T> {
        self.try_take_boxed().unwrap()
    }

    /// Replaces the boxed value inside the `FlexCell`, returning the old boxed value.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let old_boxed_value = cell.replace_boxed(Box::new(10));
    /// assert_eq!(*old_boxed_value, 5);
    /// cell.with(|value| assert_eq!(*value, 10));
    /// ```
    #[inline]
    #[track_caller]
    #[must_use = "If you don't need the old value, consider using `set_boxed` instead."]
    pub fn replace_boxed(&self, value: Box<T>) -> Box<T> {
        self.try_replace_boxed(value).unwrap()
    }

    /// Attempts to consume the `FlexCell`, returning the boxed value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let boxed_value = cell.try_into_boxed().unwrap();
    /// assert_eq!(*boxed_value, 5);
    /// ```
    pub fn try_into_boxed(self) -> Result<Box<T>, ConsumeError> {
        if let Pointer::Boxed(ptr) = ManuallyDrop::new(self).0.get() {
            Ok(unsafe { Box::from_raw(ptr.as_ptr()) })
        } else {
            Err(ConsumeError)
        }
    }

    /// Attempts to take the boxed value out of the `FlexCell`, leaving it empty.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let boxed_value = cell.try_take_boxed().unwrap();
    /// assert_eq!(*boxed_value, 5);
    /// ```
    pub fn try_take_boxed(&self) -> Result<Box<T>, ConsumeError> {
        if let Pointer::Boxed(ptr) = self.0.get() {
            let value = unsafe { Box::from_raw(ptr.as_ptr()) };
            self.0.set(Pointer::Null);
            Ok(value)
        } else {
            Err(ConsumeError)
        }
    }

    /// Attempts to replace the boxed value inside the `FlexCell`, returning the old boxed value.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let old_boxed_value = cell.try_replace_boxed(Box::new(10)).unwrap();
    /// assert_eq!(*old_boxed_value, 5);
    /// cell.with(|value| assert_eq!(*value, 10));
    /// ```
    #[must_use = "If you don't need the old value, consider using `set_boxed` instead."]
    pub fn try_replace_boxed(&self, value: Box<T>) -> Result<Box<T>, ConsumeError> {
        if let Pointer::Boxed(ptr) = self.0.get() {
            self.0.set(Pointer::from_boxed(value));
            Ok(unsafe { Box::from_raw(ptr.as_ptr()) })
        } else {
            Err(ConsumeError)
        }
    }
}

impl<T: ?Sized> FlexCell<T> {
    /// Temporarily lends a mutable reference to an external value to the `FlexCell`.
    ///
    /// The `FlexCell` will point to the external value for the duration of the closure.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(String::from("original"));
    /// let mut external = String::from("external");
    ///
    /// cell.lend(&mut external, || {
    ///     cell.with_mut(|s| {
    ///         s.push_str(" modified");
    ///     });
    /// });
    ///
    /// assert_eq!(external, "external modified");
    /// cell.with(|val| {
    ///     assert_eq!(*val, "original");
    /// });
    /// ```
    #[inline]
    pub fn lend<R>(&self, value: &mut T, f: impl FnOnce() -> R) -> R {
        Guard::create(&self.0, Pointer::from_mut(value), f)
    }

    /// Temporarily lends a reference to an external value to the `FlexCell`.
    ///
    /// The `FlexCell` will point to the external value for the duration of the closure.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(String::from("original"));
    /// let external = String::from("external");
    ///
    /// cell.lend_ref(&external, || {
    ///     cell.with(|s| {
    ///         assert_eq!(*s, "external");
    ///     });
    /// });
    ///
    /// cell.with(|val| {
    ///     assert_eq!(*val, "original");
    /// });
    /// ```
    #[inline]
    pub fn lend_ref<R>(&self, value: &T, f: impl FnOnce() -> R) -> R {
        Guard::create(&self.0, Pointer::from_ref(value), f)
    }

    /// Borrows the value inside the `FlexCell` immutably for the duration of the closure.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently mutably borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// cell.with(|value| {
    ///     assert_eq!(*value, 5);
    /// });
    /// ```
    #[inline]
    #[track_caller]
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        self.try_with(f).unwrap()
    }

    /// Borrows the value inside the `FlexCell` mutably for the duration of the closure.
    ///
    /// # Panics
    ///
    /// Panics if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// cell.with_mut(|value| {
    ///     *value = 10;
    /// });
    /// cell.with(|value| {
    ///     assert_eq!(*value, 10);
    /// });
    /// ```
    #[inline]
    #[track_caller]
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
        self.try_with_mut(f).unwrap()
    }

    /// Attempts to borrow the value inside the `FlexCell` immutably for the duration of the closure.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently mutably borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let result = cell.try_with(|value| {
    ///     assert_eq!(*value, 5);
    /// });
    /// assert!(result.is_ok());
    /// ```
    pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Result<R, BorrowError> {
        if let Pointer::Ref(ptr) | Pointer::Mut(ptr) | Pointer::Boxed(ptr) = self.0.get() {
            Guard::create(&self.0, Pointer::Ref(ptr), move || {
                Ok(f(unsafe { ptr.as_ref() }))
            })
        } else {
            Err(BorrowError)
        }
    }

    /// Attempts to borrow the value inside the `FlexCell` mutably for the duration of the closure.
    ///
    /// # Errors
    ///
    /// Returns an error if the value is currently borrowed or the cell is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use flexcell::FlexCell;
    ///
    /// let cell = FlexCell::new(5);
    /// let result = cell.try_with_mut(|value| {
    ///     *value = 10;
    /// });
    /// assert!(result.is_ok());
    /// cell.with(|value| {
    ///     assert_eq!(*value, 10);
    /// });
    /// ```
    pub fn try_with_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> Result<R, BorrowMutError> {
        if let Pointer::Mut(mut ptr) | Pointer::Boxed(mut ptr) = self.0.get() {
            Guard::create(&self.0, Pointer::Null, move || {
                Ok(f(unsafe { ptr.as_mut() }))
            })
        } else {
            Err(BorrowMutError)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn borrow_ref() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|value| {
            assert_eq!(*value, vec![0, 0, 0]);
        });
    }

    #[test]
    fn borrow_mut() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|value| {
            assert_eq!(*value, vec![0, 0, 0]);
            value.push(1);
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
    }

    #[test]
    fn set() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.set(vec![1, 2, 3]);
        cell.with_mut(|value| assert_eq!(*value, vec![1, 2, 3]));
    }

    #[test]
    fn replace() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        let value = cell.replace(vec![1, 2, 3]);
        assert_eq!(value, vec![0, 0, 0]);
        cell.with_mut(|value| assert_eq!(*value, vec![1, 2, 3]));
    }

    #[test]
    fn take() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        let _ = cell.take();
        cell.try_with(|_| {}).unwrap_err();
    }

    #[test]
    fn borrow_ref_and_lend_ref_with_self() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|value| {
            cell.lend_ref(value, || {
                cell.with(|value| assert_eq!(*value, vec![0, 0, 0]));
            });
        });
    }

    #[test]
    fn borrow_ref_and_lend_ref_with_other() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|_| {
            let other = vec![1, 2, 3];
            cell.lend_ref(&other, || {
                cell.with(|value| assert_eq!(*value, vec![1, 2, 3]));
            });
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0]));
    }

    #[test]
    fn borrow_ref_and_set() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|_| {
            cell.set(vec![1, 2, 3]);
            cell.with(|value| assert_eq!(*value, vec![1, 2, 3]));
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0]));
    }

    #[test]
    #[should_panic = "ConsumeError"]
    fn borrow_ref_and_take() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|_| cell.take());
    }

    #[test]
    #[should_panic = "ConsumeError"]
    fn borrow_ref_and_replace() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|_| cell.replace(vec![1, 2, 3]));
    }

    #[test]
    fn borrow_ref_and_lend_mut_with_other() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with(|value| {
            let mut other = vec![1, 2, 3];
            cell.lend(&mut other, || {
                cell.with(|value| assert_eq!(*value, vec![1, 2, 3]));
                cell.with_mut(|value| value.push(4));
            });
            assert_eq!(other, vec![1, 2, 3, 4]);
            assert_eq!(*value, vec![0, 0, 0]);
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0]));
    }

    #[test]
    fn borrow_mut_and_lend_ref_with_self() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|value| {
            value.push(1);
            cell.lend_ref(value, || {
                cell.with(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
                cell.try_with_mut(|_| {}).unwrap_err();
            });
            assert_eq!(*value, vec![0, 0, 0, 1]);
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
    }

    #[test]
    fn borrow_mut_and_lend_ref_with_other() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|value| {
            value.push(1);
            let other = vec![1, 2, 3];
            cell.lend_ref(&other, || {
                cell.with(|value| assert_eq!(*value, vec![1, 2, 3]));
                cell.try_with_mut(|_| {}).unwrap_err();
            });
            assert_eq!(*value, vec![0, 0, 0, 1]);
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
    }

    #[test]
    fn borrow_mut_and_lend_mut_with_self() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|value| {
            value.push(1);
            cell.lend(value, || {
                cell.with_mut(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
            });
            assert_eq!(*value, vec![0, 0, 0, 1]);
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
    }

    #[test]
    fn borrow_mut_and_lend_mut_with_other() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|value| {
            value.push(1);
            let mut other = vec![1, 2, 3];
            cell.lend(&mut other, || {
                cell.with(|value| assert_eq!(*value, vec![1, 2, 3]));
                cell.with_mut(|value| value.push(4));
            });
            assert_eq!(other, vec![1, 2, 3, 4]);
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0, 1]));
    }

    #[test]
    fn borrow_mut_and_set() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|_| {
            cell.set(vec![1, 2, 3]);
            cell.with_mut(|value| assert_eq!(*value, vec![1, 2, 3]));
        });
        cell.with(|value| assert_eq!(*value, vec![0, 0, 0]));
    }

    #[test]
    #[should_panic = "ConsumeError"]
    fn borrow_mut_and_take() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|_| cell.take());
    }

    #[test]
    #[should_panic = "ConsumeError"]
    fn borrow_mut_and_replace() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        cell.with_mut(|_| cell.replace(vec![1, 2, 3]));
    }

    #[test]
    fn take_and_lend_ref_with_self() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        let value = cell.take();
        cell.lend_ref(&value, || {
            cell.with(|value| assert_eq!(*value, vec![0, 0, 0]));
            cell.try_with_mut(|_| {}).unwrap_err();
        });
        cell.try_with(|_| {}).unwrap_err();
    }

    #[test]
    fn take_and_lend_ref_with_other() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        let _ = cell.take();
        let other = vec![1, 2, 3];
        cell.lend_ref(&other, || {
            cell.with(|value| assert_eq!(*value, vec![1, 2, 3]));
            cell.try_with_mut(|_| {}).unwrap_err();
        });
        cell.try_with(|_| {}).unwrap_err();
    }

    #[test]
    fn take_and_lend_mut_with_self() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        let mut value = cell.take();
        cell.lend(&mut value, || {
            cell.with_mut(|value| assert_eq!(*value, vec![0, 0, 0]));
        });
        cell.try_with(|_| {}).unwrap_err();
    }

    #[test]
    fn take_and_lend_mut_with_other() {
        let cell = FlexCell::new(vec![0, 0, 0]);
        let _ = cell.take();
        let mut other = vec![1, 2, 3];
        cell.lend(&mut other, || {
            cell.with_mut(|value| assert_eq!(*value, vec![1, 2, 3]));
        });
        cell.try_with(|_| {}).unwrap_err();
    }
}