async_borrow/
lib.rs

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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
use std::{borrow::{Borrow, BorrowMut}, cell::UnsafeCell, future::Future, marker::PhantomData, mem::MaybeUninit, ops::{Deref, DerefMut}, pin::Pin, ptr::NonNull, sync::{atomic::{AtomicUsize, Ordering}, Mutex}, usize};

use futures::{future::FusedFuture, StreamExt};

mod graph;
pub mod scope;
pub mod slice;
pub mod prelude;
pub mod tuple;

use graph::Graph;
use scope::{Anchor, Spawner};

// MARK: Inner

struct BorrowInner<T> {
    weak: AtomicUsize,
    graph: Mutex<Graph>,
    data: UnsafeCell<MaybeUninit<T>>
}

// MARK: Raw Pointers

struct SharedPtr<T> {
    inner: NonNull<BorrowInner<T>>
}

unsafe impl<T> Send for SharedPtr<T> {}

unsafe impl<T> Sync for SharedPtr<T> {}

impl<T> SharedPtr<T> {
    pub fn new(data: T) -> Self {
        SharedPtr {
            inner: unsafe { NonNull::new_unchecked(Box::into_raw(Box::new(BorrowInner {
                weak: 1.into(),
                graph: Mutex::new(Graph::new()),
                data: UnsafeCell::new(MaybeUninit::new(data)),
            }))) }
        }
    }

    pub fn inner(&self) -> &BorrowInner<T> {
        unsafe { self.inner.as_ref() }
    }

    pub unsafe fn get_ref(&self) -> &T {
        self.inner().data.get().as_ref().unwrap_unchecked().assume_init_ref()
    }

    pub unsafe fn get_mut(&mut self) -> &mut T {
        self.inner().data.get().as_mut().unwrap_unchecked().assume_init_mut()
    }

    pub fn into_raw(self) -> *mut T {
        let ptr = unsafe { self.inner.as_ptr().cast::<T>().byte_add(std::mem::offset_of!(BorrowInner<T>, data)) };
        std::mem::forget(self);
        ptr
    }

    pub unsafe fn from_raw(ptr: *mut T) -> Self {
        SharedPtr {
            inner: NonNull::new_unchecked(ptr.byte_sub(std::mem::offset_of!(BorrowInner<T>, data)).cast::<BorrowInner<T>>()),
        }
    }
}

impl<T> Clone for SharedPtr<T> {
    fn clone(&self) -> Self {
        self.inner().weak.fetch_add(1, Ordering::Relaxed);
        SharedPtr { inner: self.inner }
    }
}

impl<T> Drop for SharedPtr<T> {
    fn drop(&mut self) {
        if self.inner().weak.fetch_sub(1, Ordering::Release) == 1 {
            drop(unsafe { Box::from_raw(self.inner.as_ptr()) })
        }
    }
}

struct BorrowPtr<T> {
    shared: SharedPtr<T>,
    index: usize,
}

impl<T> Deref for BorrowPtr<T> {
    type Target = SharedPtr<T>;

    fn deref(&self) -> &Self::Target {
        &self.shared
    }
}

impl<T> DerefMut for BorrowPtr<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.shared
    }
}

impl<T> Clone for BorrowPtr<T> {
    fn clone(&self) -> Self {
        let mut graph = self.inner().graph.lock().unwrap();
        unsafe { graph.track_borrow_unchecked(self.index) };
        BorrowPtr {
            shared: self.shared.clone(),
            index: self.index
        }
    }
}

impl<T> Drop for BorrowPtr<T> {
    fn drop(&mut self) {
        let Ok(mut graph) = self.inner().graph.lock() else { return }; // TODO: handle poisoning
        unsafe {
            if graph.untrack_borrow_unchecked(self.index) {
                self.inner().data.get().as_mut().unwrap_unchecked().assume_init_drop();
            }
        }
    }
}

trait Index: Unpin {
    fn get(&self) -> usize;
}

impl Index for usize {
    fn get(&self) -> usize {
        *self
    }
}

struct First;

impl Index for First {
    fn get(&self) -> usize {
        0
    }
}

struct FuturePtr<T, I: Index> {
    shared: Option<SharedPtr<T>>,
    index: I
}

impl<T, I: Index> FuturePtr<T, I> {
    pub fn generalise(mut self) -> FuturePtr<T, usize> {
        FuturePtr { shared: self.shared.take(), index: self.index.get() }
    }

    pub fn poll_shared(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<SharedPtr<T>> {
        Pin::new(self).poll(cx).map(|(_, shared)| shared)
    }

    pub fn poll_borrow(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<BorrowPtr<T>> {
        Pin::new(self).poll(cx).map(|(index, shared)|
            BorrowPtr { shared, index }
        )
    }
} 

impl<T, I: Index> Future for FuturePtr<T, I> {
    type Output = (usize, SharedPtr<T>);

    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        let mut graph = self.shared.as_ref().unwrap().inner().graph.lock().unwrap();
        let poll = unsafe { graph.poll_unchecked(self.index.get(), cx) };
        drop(graph); // release mutex
        poll.map(|index| (index, unsafe { self.shared.take().unwrap_unchecked() }))
    }
}

impl<T, I: Index> FusedFuture for FuturePtr<T, I> {
    fn is_terminated(&self) -> bool {
        self.shared.is_none()
    }
}

impl<T, I: Index> Drop for FuturePtr<T, I> {
    fn drop(&mut self) {
        let Some(shared) = self.shared.take() else { return };
        let mut graph = shared.inner().graph.lock().unwrap();
        if unsafe { graph.close_future_unchecked(self.index.get()) } {
            unsafe { shared.inner().data.get().as_mut().unwrap_unchecked().assume_init_drop() };
            drop(graph); // release mutex
            drop(shared)
        }
    }
}

// MARK: Black Magic

pub struct Context<'a, T> {
    ptr: BorrowPtr<T>,
    _contextualise_ref: PhantomData<fn(&'a T) -> Ref<T>>,
    _contextualise_mut: PhantomData<fn(&'a mut T) -> RefMut<T>>,
}

unsafe impl<'a, T: Send> Send for Context<'a, T> {}

unsafe impl<'a, T: Send> Sync for Context<'a, T> {}

impl<'a, T> Clone for Context<'a, T> {
    fn clone(&self) -> Self {
        Self {
            ptr: self.ptr.clone(),
            _contextualise_ref: PhantomData,
            _contextualise_mut: PhantomData
        }
    }
}

impl<'a, T> Context<'a, T> {
    pub fn contextualise_ref<B: ?Sized>(self, rf: &'a B) -> Ref<T, B> {
        Ref {
            ptr: self.ptr,
            borrow: rf,
        }
    }

    pub fn contextualise_mut<B: ?Sized>(self, rf: &'a mut B) -> RefMut<T, B> {
        RefMut {
            ptr: self.ptr,
            borrow: rf,
        }
    }

    pub fn lift_ref<B: ?Sized>(&self, rf: &'a B) -> Ref<T, B> {
        self.clone().contextualise_ref(rf)
    }

    pub fn lift_mut<B: ?Sized>(&self, rf_mut: &'a mut B) -> RefMut<T, B> {
        self.clone().contextualise_mut(rf_mut)
    }
}

// MARK: Smart Pointers

pub struct ShareBox<T> {
    ptr: SharedPtr<T>,
    _share: PhantomData<*const T>
}

unsafe impl<T: Send> Send for ShareBox<T> {}

unsafe impl<T: Sync> Sync for ShareBox<T> {}

impl<T> ShareBox<T> {
    pub fn new(value: T) -> Self {
        ShareBox {
            ptr: SharedPtr::new(value),
             _share: PhantomData
        }
    }

    fn into_shared(self) -> SharedPtr<T> {
        let ptr = SharedPtr { inner: self.ptr.inner };
        std::mem::forget(self);
        ptr
    }

    /// Converts self into a new ready `RefShare` future.
    pub fn into_ref_share(self) -> RefShare<T> {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        debug_assert_eq!(graph.share(), 0, r#"
            Graph should only have one root and it must be the last to be freed,
            hence it should be at the start of the free list / stack
            "#
        );
        let index = 0;
        unsafe { graph.untrack_borrow_unchecked(index) };
        drop(graph);
        let ptr = self.into_shared();
        RefShare {
            ptr: FuturePtr { shared: Some(ptr), index: First },
            _borrow: PhantomData,
        }
    }

    /// Converts self into a new ready `RefMutShare` future.
    pub fn into_mut_share(self) -> RefMutShare<T> {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        debug_assert_eq!(graph.share(), 0, r#"
            Graph should only have one root and it must be the last to be freed,
            hence it should be at the start of the free list / stack
            "#
        );
        let index = 0;
        unsafe { graph.untrack_borrow_unchecked(index) };
        drop(graph);
        let ptr = self.into_shared();
        RefMutShare {
            ptr: FuturePtr { shared: Some(ptr), index: First },
            _borrow: PhantomData,
        }
    }

    pub fn share_ref(self) -> (RefShare<T>, Ref<T>) {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        debug_assert_eq!(graph.share(), 0, r#"
            Graph should only have one root and it must be the last to be freed,
            hence it should be at the start of the free list / stack
            "#
        );
        let index = 0;
        drop(graph);
        let shared = self.into_shared();
        let borrow = shared.inner().data.get() as *mut T;
        let ptr = shared.clone();
        (
            RefShare {
                ptr: FuturePtr { shared: Some(ptr), index: First },
                _borrow: PhantomData,
            },
            Ref {
                ptr: BorrowPtr { shared, index },
                borrow,
            }
        )
    }

    pub fn share_mut(self) -> (RefMutShare<T>, RefMut<T>) {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        debug_assert_eq!(graph.share(), 0, r#"
            Graph should only have one root and it must be the last to be freed,
            hence it should be at the start of the free list / stack
            "#
        );
        let index = 0;
        drop(graph);
        let shared = self.into_shared();
        let borrow = shared.inner().data.get() as *mut T;
        let ptr = shared.clone();
        (
            RefMutShare {
                ptr: FuturePtr { shared: Some(ptr), index: First },
                _borrow: PhantomData,
            },
            RefMut {
                ptr: BorrowPtr { shared, index },
                borrow,
            }
        )
    }

    pub fn spawn_ref<U>(self, f: impl FnOnce(Ref<T>) -> U) -> RefShare<T> {
        let (fut, rf) = self.share_ref();
        f(rf);
        fut
    }

    pub fn spawn_mut<U>(self, f: impl FnOnce(RefMut<T>) -> U) -> RefMutShare<T> {
        let (fut, rf_mut) = self.share_mut();
        f(rf_mut);
        fut
    }

    pub fn into_ref(self) -> Ref<T> {
        let index = 0;
        let shared = self.into_shared();
        let borrow = shared.inner().data.get() as *const T;
        Ref {
            ptr: BorrowPtr { shared, index },
            borrow,
        }

    }

    pub fn into_mut(self) -> RefMut<T> {
        let index = 0;
        let shared = self.into_shared();
        let borrow = shared.inner().data.get() as *mut T;
        RefMut {
            ptr: BorrowPtr { shared, index },
            borrow,
        }
    }

    pub fn into_inner(self) -> T {
        unsafe { self.into_shared().inner().data.get().as_mut().unwrap_unchecked().assume_init_read() }
    }

    pub fn into_raw(self) -> *const T {
        self.into_shared().into_raw()
    }

    pub unsafe fn from_raw(ptr: *const T) -> ShareBox<T> {
        ShareBox {
            ptr: SharedPtr::from_raw(ptr as *mut T),
            _share: PhantomData
        }
    }
}

impl<T> Deref for ShareBox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { self.ptr.get_ref() }
    }
}

impl<T> DerefMut for ShareBox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.ptr.get_mut() }
    }
}

impl<T: Clone> Clone for ShareBox<T> {
    fn clone(&self) -> Self {
        ShareBox::new(T::clone(&*self))
    }
}

impl<T> Drop for ShareBox<T> {
    fn drop(&mut self) {
        unsafe { self.ptr.inner().data.get().as_mut().unwrap_unchecked().assume_init_drop() }
    }
}

#[derive(Clone)]
pub struct Weak<T, B: ?Sized = T> {
    shared: SharedPtr<T>,
    borrow: *const B,
    index: usize,
    version: u64,
}

unsafe impl<T: Send, B: ?Sized + Sync> Send for Weak<T, B> {}

unsafe impl<T: Send, B: ?Sized + Sync> Sync for Weak<T, B> {}

impl<T, B: ?Sized> Weak<T, B> {
    pub fn upgrade(self) -> Option<Ref<T, B>> {
        let mut graph = self.shared.inner().graph.lock().unwrap();
        unsafe { graph.try_upgrade_weak_unchecked(self.index, self.version) }
            .then_some(drop(graph))
            .map(|_| Ref {
                ptr: BorrowPtr { shared: self.shared, index: self.index, },
                borrow: self.borrow,
            })
    }
}

pub struct Ref<T, B: ?Sized = T> {
    ptr: BorrowPtr<T>,
    borrow: *const B,
}

unsafe impl<T: Send, B: ?Sized + Sync> Send for Ref<T, B> {}

unsafe impl<T: Send, B: ?Sized + Sync> Sync for Ref<T, B> {}

impl<T, B: ?Sized> Ref<T, B> {
    pub fn downgrade(&self) -> Weak<T, B> {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        let version = unsafe { graph.track_weak_unchecked(self.ptr.index) };
        Weak {
            shared: self.ptr.shared.clone(),
            borrow: self.borrow,
            index: self.ptr.index,
            version,
        }
    }

    /// Given that `f` works for all lifetimes `'a`, it will also work for
    /// the indeterminable, yet existant, lifetime of the `BorrowInner`.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn map<C: ?Sized>(self, f: impl for<'a> FnOnce(&'a B) -> &'a C) -> Ref<T, C> {
        Ref {
            ptr: self.ptr,
            borrow: f(unsafe { self.borrow.as_ref().unwrap_unchecked() }) as *const C
        }
    }

    /// Uses the same principle behind other scoping APIs to provide additional support to specific lifetimes.
    /// 
    /// The lifetime in question here is the same `'a` as referenced in `Ref::map`, as the true `'a` can not be know
    /// the lifetime `'_` will be used as a stand_in as it is truly anonymous.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn context<R>(self, f: impl for<'a> FnOnce(&'a B, Context<'a, T>) -> R) -> R {
        let Ref {
            ptr,
            borrow
        } = self;
        let context = Context::<'_, T> {
            ptr,
            _contextualise_ref: PhantomData,
            _contextualise_mut: PhantomData,
        };
        f(unsafe { borrow.as_ref().unwrap() }, context)
    }

    /// Uses the same principle behind other scoping APIs to provide additional support to specific lifetimes.
    /// 
    /// The lifetime in question here is the same `'a` as referenced in `Ref::map`, as the true `'a` can not be know
    /// the lifetime `'_` will be used as a stand_in as it is truly anonymous.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub async fn scope<F: Future>(self, f: impl for<'a> FnOnce(&'a B, Context<'a, T>, Spawner<'a>) -> F) -> F::Output {
        let Ref {
            ptr,
            borrow
        } = self;
        let context = Context::<'_, T> {
            ptr,
            _contextualise_ref: PhantomData,
            _contextualise_mut: PhantomData,
        };
        let anchor = Anchor::new();
        let fut = f(unsafe { borrow.as_ref().unwrap() }, context, anchor.spawner.clone());
        let ((), output) = futures::join!(anchor.stream().collect::<()>(), fut);
        output
    }

    /// A special case of `Ref::map` to handle dereferencing.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn into_deref(self) -> Ref<T, B::Target> where B: Deref {
        self.map(B::deref)
    }

    /// A special case of `Ref::map` to handle borrowing.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn into_borrow<C>(self) -> Ref<T, C> where B: Borrow<C> {
        self.map(B::borrow)
    }
}

impl<T, B: ?Sized> Deref for Ref<T, B> {
    type Target = B;

    fn deref(&self) -> &Self::Target {
        unsafe { self.borrow.as_ref().unwrap_unchecked() }
    }
}

impl<T, B: ?Sized> Clone for Ref<T, B> {
    fn clone(&self) -> Self {
        Ref {
            ptr: self.ptr.clone(),
            borrow: self.borrow
        }
    }
}

impl<T, B: ?Sized> From<RefMut<T, B>> for Ref<T, B> {
    fn from(value: RefMut<T, B>) -> Self {
        value.into_ref()
    }
}

pub struct RefMut<T, B: ?Sized = T> {
    ptr: BorrowPtr<T>,
    borrow: *mut B,
}

unsafe impl<T: Send, B: ?Sized + Send> Send for RefMut<T, B> {}

unsafe impl<T, B: ?Sized + Sync> Sync for RefMut<T, B> {}

impl<T, B: ?Sized> RefMut<T, B> {
    pub fn into_ref(self) -> Ref<T, B> {
        let RefMut {
            ptr,
            borrow
        } = self;
        Ref {
            ptr,
            borrow,
        }
    }

    /// Converts self into a new ready `RefForward` future.
    pub fn into_ref_forward(self) -> RefForward<T, B> {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        let index = graph.forward(self.ptr.index);
        unsafe { graph.untrack_borrow_unchecked(index) };
        drop(graph);
        let ptr = SharedPtr { inner: self.ptr.inner };
        let borrow = self.borrow;
        std::mem::forget(self.ptr);
        RefForward {
            ptr: FuturePtr { shared: Some(ptr), index },
            borrow,
        }
    }

    /// Converts self into a new ready `RefMutForward` future.
    pub fn into_mut_forward(self) -> RefMutForward<T, B> {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        let index = graph.forward(self.ptr.index);
        unsafe { graph.untrack_borrow_unchecked(index) };
        drop(graph);
        let ptr = SharedPtr { inner: self.ptr.inner };
        let borrow = self.borrow;
        std::mem::forget(self.ptr);
        RefMutForward {
            ptr: FuturePtr { shared: Some(ptr), index },
            borrow,
        }
    }

    pub fn forward_ref(self) -> (RefForward<T, B>, Ref<T, B>) {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        let index = graph.forward(self.ptr.index);
        drop(graph);
        let shared = SharedPtr { inner: self.ptr.inner };
        let borrow = self.borrow;
        let ptr = shared.clone();
        std::mem::forget(self.ptr);
        (
            RefForward {
                ptr: FuturePtr { shared: Some(ptr), index },
                borrow,
            },
            Ref {
                ptr: BorrowPtr { shared, index },
                borrow,
            }
        )
    }

    pub fn forward_mut(self) -> (RefMutForward<T, B>, RefMut<T, B>) {
        let mut graph = self.ptr.inner().graph.lock().unwrap();
        let index = graph.forward(self.ptr.index);
        drop(graph);
        let shared = SharedPtr { inner: self.ptr.inner };
        let borrow = self.borrow;
        let ptr = shared.clone();
        std::mem::forget(self.ptr);
        (
            RefMutForward {
                ptr: FuturePtr { shared: Some(ptr), index },
                borrow,
            },
            RefMut {
                ptr: BorrowPtr { shared, index },
                borrow,
            }
        )
    }

    pub fn cleave_ref<U>(self, f: impl FnOnce(Ref<T, B>) -> U) -> RefForward<T, B> {
        let (fut, rf) = self.forward_ref();
        f(rf);
        fut
    }

    pub fn cleave_mut<U>(self, f: impl FnOnce(RefMut<T, B>) -> U) -> RefMutForward<T, B> {
        let (fut, rf_mut) = self.forward_mut();
        f(rf_mut);
        fut
    }

    /// Given that `f` works for all lifetimes `'a`, it will also work for
    /// the indeterminable, yet existant, lifetime of the `BorrowInner`.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn map<C: ?Sized>(self, f: impl for<'a> FnOnce(&'a mut B) -> &'a mut C) -> RefMut<T, C> {
        RefMut {
            ptr: self.ptr,
            borrow: f(unsafe { self.borrow.as_mut().unwrap_unchecked() }) as *mut C
        }
    }

    /// Uses the same principle behind other scoping APIs to provide additional support to specific lifetimes.
    /// 
    /// The lifetime in question here is the same `'a` as referenced in `RefMut::map`, as the true `'a` can not be know
    /// the lifetime `'_` will be used as a stand_in as it is truly anonymous.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn context<R>(self, f: impl for<'a> FnOnce(&'a mut B, Context<'a, T>) -> R) -> R {
        let RefMut {
            ptr,
            borrow
        } = self;
        let context = Context::<'_, T> {
            ptr,
            _contextualise_ref: PhantomData,
            _contextualise_mut: PhantomData,
        };
        f(unsafe { borrow.as_mut().unwrap() }, context)
    }

    /// Uses the same principle behind other scoping APIs to provide additional support to specific lifetimes.
    /// 
    /// The lifetime in question here is the same `'a` as referenced in `RefMut::map`, as the true `'a` can not be know
    /// the lifetime `'_` will be used as a stand_in as it is truly anonymous.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub async fn scope<F: Future>(self, f: impl for<'a> FnOnce(&'a mut B, Context<'a, T>, Spawner<'a>) -> F) -> F::Output {
        let RefMut {
            ptr,
            borrow
        } = self;
        let context = Context::<'_, T> {
            ptr,
            _contextualise_ref: PhantomData,
            _contextualise_mut: PhantomData,
        };
        let anchor = Anchor::new();
        let fut = f(unsafe { borrow.as_mut().unwrap() }, context, anchor.spawner.clone());
        let ((), output) = futures::join!(anchor.stream().collect::<()>(), fut);
        output
    }

    /// A special case of `RefMut::map` to handle dereferencing.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn into_deref_mut(self) -> RefMut<T, B::Target> where B: DerefMut {
        self.map(B::deref_mut)
    }

    /// A special case of `RefMut::map` to handle borrowing.
    /// 
    /// # Experimental
    /// 
    /// This is intended to be a safe API, and I believe that it is safe,
    /// however the work to prove this thoroughly is complex and has not yet been undertaken.
    /// This work will be done before v1.0.0.
    /// 
    /// > **Do not rely on this being safe in safety critical contexts**
    pub fn into_borrow_mut<C>(self) -> RefMut<T, C> where B: BorrowMut<C> {
        self.map(B::borrow_mut)
    }
}

impl<T, B: ?Sized> Deref for RefMut<T, B> {
    type Target = B;

    fn deref(&self) -> &Self::Target {
        unsafe { self.borrow.as_ref().unwrap_unchecked() }
    }
}

impl<T, B: ?Sized> DerefMut for RefMut<T, B> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.borrow.as_mut().unwrap_unchecked() }
    }
}

// MARK: Futures

pub struct RefShare<T> {
    ptr: FuturePtr<T, First>,
    _borrow: PhantomData<*const T>,
}

unsafe impl<T: Send + Sync> Send for RefShare<T> {}

unsafe impl<T: Send + Sync> Sync for RefShare<T> {}

impl<T> RefShare<T> {
    pub fn get(&self) -> Option<&T> {
        unsafe { self.ptr.shared.as_ref().map(|shared| shared.get_ref()) }
    }

    pub fn as_ref(&self) -> Ref<T> {
        let shared = self.ptr.shared.as_ref().unwrap().clone();
        let borrow = shared.inner().data.get() as *mut T;
        let mut graph = shared.inner().graph.lock().unwrap();
        let index = self.ptr.index.get();
        unsafe { graph.track_borrow_unchecked(index) };
        drop(graph);
        Ref {
            ptr: BorrowPtr { shared, index },
            borrow,
        }
    }

    pub fn generalise(self) -> RefForward<T> {
        let borrow = self.ptr.shared.as_ref().unwrap().inner().data.get() as *mut T;
        RefForward { ptr: self.ptr.generalise(), borrow }
    }

    pub fn into_raw(mut self) -> Option<*const T> {
        self.ptr.shared.take().map(|shared| shared.into_raw() as *const T)
    }

    pub unsafe fn from_raw(ptr: *const T) -> RefShare<T> {
        RefShare {
            ptr: FuturePtr {
                shared: Some(SharedPtr::from_raw(ptr as *mut T)),
                index: First
            },
            _borrow: PhantomData,
        }
    }
}

impl<T> Future for RefShare<T> {
    type Output = ShareBox<T>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        self.ptr.poll_shared(cx).map(|ptr| ShareBox { ptr, _share: PhantomData })
    }
}

impl<T> FusedFuture for RefShare<T> {
    fn is_terminated(&self) -> bool {
        self.ptr.is_terminated()
    }
}

pub struct RefMutShare<T> {
    ptr: FuturePtr<T, First>,
    _borrow: PhantomData<*const T>,
}

unsafe impl<T: Send> Send for RefMutShare<T> {}

unsafe impl<T: Sync> Sync for RefMutShare<T> {}

impl<T> RefMutShare<T> {
    pub fn generalise(self) -> RefMutForward<T> {
        let borrow = self.ptr.shared.as_ref().unwrap().inner().data.get() as *mut T;
        RefMutForward { ptr: self.ptr.generalise(), borrow }
    }

    pub fn into_raw(mut self) -> Option<*const T> {
        self.ptr.shared.take().map(|shared| shared.into_raw() as *const T)
    }

    pub unsafe fn from_raw(ptr: *const T) -> RefMutShare<T> {
        RefMutShare {
            ptr: FuturePtr {
                shared: Some(SharedPtr::from_raw(ptr as *mut T)),
                index: First
            },
            _borrow: PhantomData,
        }
    }
}

impl<T> Future for RefMutShare<T> {
    type Output = ShareBox<T>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        self.ptr.poll_shared(cx).map(|ptr| ShareBox { ptr, _share: PhantomData })
    }
}

impl<T> FusedFuture for RefMutShare<T> {
    fn is_terminated(&self) -> bool {
        self.ptr.is_terminated()
    }
}

impl<T> From<RefShare<T>> for RefMutShare<T> {
    fn from(value: RefShare<T>) -> Self {
        RefMutShare { ptr: value.ptr, _borrow: value._borrow }
    }
}

pub struct RefForward<T, B: ?Sized = T> {
    ptr: FuturePtr<T, usize>,
    borrow: *mut B,
}

unsafe impl<T: Send, B: ?Sized + Sync> Send for RefForward<T, B> {}

unsafe impl<T: Send, B: ?Sized + Sync> Sync for RefForward<T, B> {}

impl<T, B: ?Sized> RefForward<T, B> {
    pub fn get(&self) -> Option<&T> {
        unsafe { self.ptr.shared.as_ref().map(|shared| shared.get_ref()) }
    }

    pub fn as_ref(&self) -> Ref<T, B> {
        let shared = self.ptr.shared.as_ref().unwrap().clone();
        let borrow = self.borrow;
        let mut graph = shared.inner().graph.lock().unwrap();
        let index = self.ptr.index.get();
        unsafe { graph.track_borrow_unchecked(index) };
        drop(graph);
        Ref {
            ptr: BorrowPtr { shared, index },
            borrow
        }
    }
}

impl<T, B: ?Sized> Future for RefForward<T, B> {
    type Output = RefMut<T, B>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        self.ptr.poll_borrow(cx).map(|ptr| RefMut { ptr, borrow: self.borrow })
    }
}

impl<T, B: ?Sized> FusedFuture for RefForward<T, B> {
    fn is_terminated(&self) -> bool {
        self.ptr.is_terminated()
    }
}

pub struct RefMutForward<T, B: ?Sized = T> {
    ptr: FuturePtr<T, usize>,
    borrow: *mut B,
}

unsafe impl<T: Send, B: ?Sized + Send> Send for RefMutForward<T, B> {}

unsafe impl<T, B: ?Sized + Sync> Sync for RefMutForward<T, B> {}

impl<T, B: ?Sized> Future for RefMutForward<T, B> {
    type Output = RefMut<T, B>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        self.ptr.poll_borrow(cx).map(|ptr| RefMut { ptr, borrow: self.borrow })
    }
}

impl<T, B: ?Sized> FusedFuture for RefMutForward<T, B> {
    fn is_terminated(&self) -> bool {
        self.ptr.is_terminated()
    }
}

impl<T, B: ?Sized> From<RefForward<T, B>> for RefMutForward<T, B> {
    fn from(value: RefForward<T, B>) -> Self {
        RefMutForward { ptr: value.ptr, borrow: value.borrow }
    }
}

// MARK: Wide

#[allow(type_alias_bounds)]
pub type WideShareBox<T: ?Sized> = ShareBox<Box<T>>;

impl<T: ?Sized> WideShareBox<T> {
    pub fn share_wide_ref(self) -> (WideRefShare<T>, WideRef<T>) {
        let (fut, rf) = self.share_ref();
        (fut, rf.into_deref())
    }

    pub fn share_wide_mut(self) -> (WideRefMutShare<T>, WideRefMut<T>) {
        let (fut, rf_mut) = self.share_mut();
        (fut, rf_mut.into_deref_mut())
    }

    pub fn spawn_wide_ref<U>(self, f: impl FnOnce(WideRef<T>) -> U) -> WideRefShare<T> {
        self.spawn_ref(|rf| f(rf.into_deref()))
    }

    pub fn spawn_wide_mut<U>(self, f: impl FnOnce(WideRefMut<T>) -> U) -> WideRefMutShare<T> {
        self.spawn_mut(|rf_mut| f(rf_mut.into_deref_mut()))
    }
}

#[allow(type_alias_bounds)]
pub type WideWeak<T: ?Sized, B: ?Sized = T> = Weak<Box<T>, B>;

#[allow(type_alias_bounds)]
pub type WideRef<T: ?Sized, B: ?Sized = T> = Ref<Box<T>, B>;

#[allow(type_alias_bounds)]
pub type WideRefMut<T: ?Sized, B: ?Sized = T> = RefMut<Box<T>, B>;

#[allow(type_alias_bounds)]
pub type WideRefShare<T: ?Sized> = RefShare<Box<T>>;

impl<T: ?Sized> WideRefShare<T> {
    pub fn as_wide_ref(&self) -> WideRef<T> {
        self.as_ref().into_deref()
    }
}

#[allow(type_alias_bounds)]
pub type WideRefMutShare<T: ?Sized> = RefMutShare<Box<T>>;

#[allow(type_alias_bounds)]
pub type WideRefForward<T: ?Sized, B: ?Sized = T> = RefForward<Box<T>, B>;

#[allow(type_alias_bounds)]
pub type WideRefMutForward<T: ?Sized, B: ?Sized = T> = RefMutForward<Box<T>, B>;

// MARK: Tests

#[cfg(test)]
mod test {
    use std::sync::Mutex;

    use crate::ShareBox;

    #[tokio::test]
    async fn vibe_check() {
        use tokio::{task::spawn, time::{sleep, Duration}};
        let mut example = ShareBox::new(Mutex::new(0));
        *example.get_mut().unwrap() += 1;
        let mut example = example
            // borrow mut
            .spawn_mut(|mut example| spawn(async move {
                *example.get_mut().unwrap() += 1;
            }))
            .await
            // borrow mut
            .spawn_mut(|example| spawn(async move {
                *example
                    // forwarding borrow mut
                    .cleave_mut(|mut example| spawn(async move {
                        *example.get_mut().unwrap() += 1;
                    }))
                    .await
                    // forwarding borrow
                    .cleave_ref(|example| spawn(async move {
                        let a = example.clone();
                        let b = example.clone();
                        let c = example;
                        spawn(async move {
                            sleep(Duration::from_millis(3)).await;
                            *a.lock().unwrap() += 1;
                        });
                        spawn(async move {
                            sleep(Duration::from_millis(2)).await;
                            *b.lock().unwrap() += 1;
                        });
                        spawn(async move {
                            sleep(Duration::from_millis(1)).await;
                            *c.lock().unwrap() += 1;
                        });
                    }))
                    .await
                    // reaquisition
                    .get_mut().unwrap() += 1;
            }))
            .await
            // borrow mut
            .spawn_ref(|example| spawn(async move {
                let a = example.clone();
                let b = example.clone();
                let c = example;
                spawn(async move {
                    sleep(Duration::from_millis(3)).await;
                    *a.lock().unwrap() += 1;
                });
                spawn(async move {
                    sleep(Duration::from_millis(2)).await;
                    *b.lock().unwrap() += 1;
                });
                spawn(async move {
                    sleep(Duration::from_millis(1)).await;
                    *c.lock().unwrap() += 1;
                });
            }))
            .await
            // borrow
            .spawn_mut(|mut example| spawn(async move {
                *example.get_mut().unwrap() += 1;
            }))
            .await;
        // reaquisition
        *example.get_mut().unwrap() += 1;
        assert_eq!(12, example.into_inner().into_inner().unwrap());
    }

    #[test]
    fn new_drop() {
        let example = ShareBox::new(());
        drop(example);
    }

    #[test]
    fn new_take() {
        let example = ShareBox::new(());
        example.into_inner();
    }

    #[test]
    fn new_into_ref() {
        let example = ShareBox::new(());
        drop(example.into_ref());
    }

    #[tokio::test]
    async fn lil_test() {
        let example = ShareBox::new(());
        let (fut, rm) = example.share_mut();
        drop(rm);
        let example = fut.await;
        example.into_inner();
    }

    #[tokio::test]
    async fn context_test() {
        use futures::FutureExt;
        let x =
            ShareBox::new((0_i8, 0_i8))
            .spawn_mut(|rf_mut| tokio::spawn(async move {
                rf_mut
                    .cleave_mut(|rf_mut| {
                        let (mut rf_mut_left, mut rf_mut_right) = rf_mut.context(|(a, b), context| {
                            (context.lift_mut(a), context.lift_mut(b))
                        });
                        tokio::spawn(async move {
                            *rf_mut_left += 1
                        });
                        tokio::spawn(async move {
                            *rf_mut_right -= 1
                        });
                    })
                    .map(|mut rf_mut| {
                        let ab = &mut* rf_mut;
                        std::mem::swap(&mut ab.0, &mut ab.1)
                    })
                    .await
            }))
            .await
            .into_inner();
            assert_eq!(x, (-1_i8, 1_i8));
    }

    #[tokio::test]
    async fn test_into_mut_share() {
        ShareBox::new(())
            .into_mut_share()
            .await
            .into_inner()
    }

    #[tokio::test]
    async fn test_into_mut_forward() {
        ShareBox::new(())
            .spawn_mut(|rf_mut| tokio::spawn(async move {
                rf_mut
                    .into_mut_forward()
                    .await
            }))
            .await
            .into_inner()
    }

    #[tokio::test]
    async fn test_drop_forward_then_drop_future() {
        ShareBox::new(())
            .spawn_mut(|rf_mut| tokio::spawn(async move {
                let (fut, rf_mut) = rf_mut
                    .forward_mut();
                drop(rf_mut);
                drop(fut);
            }))
            .await
            .into_inner()
    }

    #[tokio::test]
    async fn test_drop_future_then_drop_forward() {
        ShareBox::new(())
            .spawn_mut(|rf_mut| tokio::spawn(async move {
                let (fut, rf_mut) = rf_mut
                    .forward_mut();
                drop(fut);
                drop(rf_mut);
            }))
            .await
            .into_inner()
    }
}