-
Notifications
You must be signed in to change notification settings - Fork 6
/
prc.rs
1517 lines (1379 loc) · 44.7 KB
/
prc.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
//! Single-threaded reference-counting persistent pointers
//!
//! [`Prc`] is a persistent pointer sharing the underlying data between multiple
//! owners. To create a new strong reference, you may use [`pclone`] function.
//! When the last owner of data goes out of scope, the strong reference count
//! becomes zero, and the owner drops the allocation.
//!
//! # Cyclic References
//! If there is a cycle in the chain of references, dropping the link may yield
//! a memory leak. For example, assume that we have three nodes of `A`, `B`, and
//! `C`, which are connected together like figure (a) below:
//!
//! ```text
//! Strong Refs: 1 2 1 1 1 1 1 1 1
//! A -▷ B -▷ C A B -▷ C A -▷ B -▷ C
//! △ │ △ │ △ ┆
//! └────┘ └────┘ └----┘
//! (a) (b) (c)
//! ```
//!
//! In this topology, `B` has two strong references: `A` and `C`. Therefore,
//! when the `A -▷ B` link drops, it loses only one strong references allowing
//! the other strong reference to keep the cycle it in memory while the nodes
//! are unreachable. The resulting network is shown in figure (b).
//!
//! [`Weak`] is provided to fix this issue. Although it is not enforced, the
//! programmer can take benefits out of it. A weak link does not increment the
//! strong reference counter. Making `C -▷ B` weak, which is shown in figure (c),
//! resolves this problem. Since `B`'s strong reference counter is 1, dropping
//! `A -▷ B` makes it zero and `B`'s drop function gets called.
//!
//! # Example
//!
//! The following example does not use a weak pointer leading to a memory leak.
//! It creates the following links: `A -> B`, `B -> C`, and `C -> B`. The last
//! two links create a cycle. Therefore, when `A` goes of scope, it cannot drop
//! `B` and `C` because the strong reference count for both of them is non-zero.
//! Nodes `B` and `C` remain in memory forever.
//!
//! ```
//! use corundum::default::*;
//! type P = Allocator;
//!
//! struct Node {
//! val: char,
//! link: PRefCell<Option<Prc<Node>>>
//! }
//!
//! impl Node {
//! fn new(val: char) -> Self {
//! println!("{} is created", val);
//! Self { val, link: PRefCell::new(None) }
//! }
//! }
//!
//! impl Drop for Node {
//! fn drop(&mut self) {
//! println!("{} is dropped", self.val);
//! }
//! }
//!
//! let _pool = P::open_no_root("net.pool", O_CF).unwrap();
//!
//! transaction(|j| {
//! let A = Prc::new(Node::new('A'), j);
//! let B = Prc::new(Node::new('B'), j);
//! let C = Prc::new(Node::new('C'), j);
//! let mut a_link = A.link.borrow_mut(j);
//! let mut b_link = B.link.borrow_mut(j);
//! let mut c_link = C.link.borrow_mut(j);
//! *a_link = Some(B.pclone(j));
//! *b_link = Some(C.pclone(j));
//! *c_link = Some(B.pclone(j));
//! }).unwrap();
//! ```
//!
//! The output of the example above is as follows (`B` and `C` do not drop the
//! allocation):
//!
//! ```text
//! A is created
//! B is created
//! C is created
//! A is dropped
//! ```
//!
//! To prevent the memory leak, we can use a weak link. The following example
//! shows how to manually prevent cycles. The `C -> B` link is weak, so the
//! strong reference counter becomes zero when `A -> B` is eliminated.
//!
//! ```
//! use corundum::default::*;
//! type P = Allocator;
//!
//! enum Link<T: PSafe> {
//! Strong(Prc<T>),
//! Weak(prc::PWeak<T>),
//! Null
//! }
//!
//! struct Node {
//! val: char,
//! link: PRefCell<Link<Node>>
//! }
//!
//! impl Node {
//! fn new(val: char) -> Self {
//! println!("{} is created", val);
//! Self { val, link: PRefCell::new(Null) }
//! }
//! }
//!
//! impl Drop for Node {
//! fn drop(&mut self) {
//! println!("{} is dropped", self.val);
//! }
//! }
//! # use Link::*;
//!
//! let _pool = P::open_no_root("net.pool", O_CF).unwrap();
//!
//! transaction(|j| {
//! let A = Prc::new(Node::new('A'), j);
//! let B = Prc::new(Node::new('B'), j);
//! let C = Prc::new(Node::new('C'), j);
//! let mut a_link = A.link.borrow_mut(j);
//! let mut b_link = B.link.borrow_mut(j);
//! let mut c_link = C.link.borrow_mut(j);
//! *a_link = Strong(B.pclone(j));
//! *b_link = Strong(C.pclone(j));
//! *c_link = Weak(Prc::downgrade(&B, j));
//! }).unwrap();
//! ```
//!
//! The output shows that no `Node` remains in memory.
//!
//! ```text
//! A is created
//! B is created
//! C is created
//! A is dropped
//! B is dropped
//! C is dropped
//! ```
//!
//! [`pclone`]: ./struct.Prc.html#method.pclone
//!
use std::panic::RefUnwindSafe;
use std::panic::UnwindSafe;
use crate::alloc::{MemPool, PmemUsage};
use crate::cell::VCell;
use crate::clone::*;
use crate::ptr::Ptr;
use crate::stm::*;
use crate::*;
use std::fmt::{self,Debug};
use std::cmp::Ordering;
use std::hash::Hash;
use std::hash::Hasher;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::Deref;
use std::*;
#[cfg(any(feature = "use_pspd", feature = "use_vspd"))]
use crate::cell::TCell;
struct Counter<A: MemPool> {
strong: usize,
weak: usize,
#[cfg(not(any(
feature = "no_log_rc",
feature = "use_pspd",
feature = "use_vspd"
)))]
has_log: u8,
#[cfg(any(feature = "use_pspd", feature = "use_vspd"))]
temp: TCell<Option<*mut Self>, A>,
phantom: PhantomData<A>
}
unsafe impl<A: MemPool> PSafe for Counter<A> {}
unsafe impl<A: MemPool> TxInSafe for Counter<A> {}
impl<A: MemPool> Debug for Counter<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{{strong: {}, weak: {}}}", self.strong, self.weak)?;
#[cfg(any(feature = "use_pspd", feature = "use_vspd"))]
write!(f, "(temp: {:?})", self.temp)?;
Ok(())
}
}
pub struct PrcBox<T: ?Sized, A: MemPool> {
counter: Counter<A>,
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell<VWeakList, A>,
dummy: [A; 0],
value: T,
}
unsafe impl<T: ?Sized, A: MemPool> PSafe for PrcBox<T, A> {}
unsafe impl<T: ?Sized, A: MemPool> TxInSafe for PrcBox<T, A> {}
impl<T: ?Sized, A: MemPool> UnwindSafe for PrcBox<T, A> {}
impl<T: ?Sized, A: MemPool> RefUnwindSafe for PrcBox<T, A> {}
impl<T: ?Sized, A: MemPool> !VSafe for PrcBox<T, A> {}
impl<T: ?Sized, A: MemPool> !PSend for PrcBox<T, A> {}
unsafe fn set_data_ptr<T: ?Sized, U>(mut ptr: *mut T, data: *mut U) -> *mut T {
std::ptr::write(&mut ptr as *mut _ as *mut *mut u8, data as *mut u8);
ptr
}
/// A single-thread reference-counting persistent pointer. 'Prc' stands for
/// 'Persistent Reference Counted'.
///
/// The main aspect of `Prc<T>` is that its counters are transactional which
/// means that functions [`pclone`], [`downgrade`], and [`upgrade`] require a
/// [`Journal`] to operate. In other words, you need to wrap them in a
/// [`transaction`].
///
/// `Prc` uses reference counting to manage memory. Although it provides a fast
/// solution for deallocation without scan, cyclic references yield a memory
/// leak. At this point, we have not provided a static solution to detect cyclic
/// references. However, following Rust's partial solution for that, you may use
/// [`Weak`] references for reference cycles.
///
/// References to data can be strong (using [`pclone`]), weak (using [`downgrade`]),
/// or volatile weak (using [`demote`]). The first two generate NV-to-NV
/// pointers, while the last on is a V-to-NV pointer. Please see [`Weak`] and
/// [`VWeak`] for more details on their implementation and safety. Please also
/// visit the [module-level documentation](index.html) for the cyclic references
/// issue.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
/// use corundum::clone::PClone;
///
/// # #[allow(unused)]
/// P::transaction(|j| {
/// let p = Prc::<i32,P>::new(1, j);
///
/// // Create a new persistent strong reference
/// let s = p.pclone(j);
///
/// assert_eq!(*p, *s);
/// assert_eq!(2, Prc::strong_count(&p));
/// assert_eq!(0, Prc::weak_count(&p));
///
/// // Create a new persistent weak reference
/// let w = Prc::downgrade(&p, j);
/// assert_eq!(2, Prc::strong_count(&p));
/// assert_eq!(1, Prc::weak_count(&p));
///
/// // Create a new volatile weak reference
/// let v = Prc::demote(&p);
/// assert_eq!(2, Prc::strong_count(&p));
/// assert_eq!(1, Prc::weak_count(&p));
///
/// // Upgrade the persistent weak ref to a strong ref
/// let ws = w.upgrade(j).unwrap();
/// assert_eq!(3, Prc::strong_count(&p));
/// assert_eq!(1, Prc::weak_count(&p));
///
/// // Upgrade the volatile weak ref to a strong ref
/// let vs = w.upgrade(j).unwrap();
/// assert_eq!(4, Prc::strong_count(&p));
/// assert_eq!(1, Prc::weak_count(&p));
/// }).unwrap();
/// ```
///
/// [`pclone`]: #method.pclone
/// [`downgrade`]: #method.downgrade
/// [`demote`]: #method.demote
/// [`upgrade`]: ./struct.Weak.html#method.upgrade
/// [`promote`]: ./struct.Weak.html#method.promote
/// [`Journal`]: ../stm/journal/struct.Journal.html
/// [`transaction`]: ../stm/fn.transaction.html
pub struct Prc<T: PSafe + ?Sized, A: MemPool> {
ptr: Ptr<PrcBox<T, A>, A>,
phantom: PhantomData<T>,
}
impl<T: ?Sized, A: MemPool> !TxOutSafe for Prc<T, A> {}
impl<T: ?Sized, A: MemPool> !Send for Prc<T, A> {}
impl<T: ?Sized, A: MemPool> !Sync for Prc<T, A> {}
impl<T: ?Sized, A: MemPool> !VSafe for Prc<T, A> {}
impl<T: ?Sized, A: MemPool> !PSend for Prc<T, A> {}
impl<T: PSafe, A: MemPool> Prc<T, A> {
/// Constructs a new `Prc<T>`.
///
/// It also creates a `DropOnFailure` log to make sure that if the program
/// crashes, the allocation drops of recovery.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let five = Prc::new(5, j);
/// }).unwrap();
/// ```
pub fn new(value: T, journal: &Journal<A>) -> Prc<T, A> {
unsafe {
let ptr = Ptr::new_unchecked(A::new(
PrcBox::<T, A> {
counter: Counter {
strong: 1,
weak: 1,
#[cfg(not(any(
feature = "no_log_rc",
feature = "use_pspd",
feature = "use_vspd"
)))]
has_log: 0,
#[cfg(any(feature = "use_pspd", feature = "use_vspd"))]
temp: TCell::new_invalid(None),
phantom: PhantomData
},
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell::new(VWeakList::default()),
dummy: [],
value,
},
journal,
));
Self::from_inner(ptr)
}
}
/// Constructs a new `Prc` with uninitialized contents.
///
/// A `DropOnFailure` log is taken for the allocation.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let mut five = Prc::<u32,Heap>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Prc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5)
/// }).unwrap();
/// ```
pub fn new_uninit(journal: &Journal<A>) -> Prc<MaybeUninit<T>, A> {
unsafe {
Prc::from_inner(Ptr::from_mut(A::new(
PrcBox {
counter: Counter {
strong: 1,
weak: 1,
#[cfg(not(any(
feature = "no_log_rc",
feature = "use_pspd",
feature = "use_vspd"
)))]
has_log: 0,
#[cfg(any(feature = "use_pspd", feature = "use_vspd"))]
temp: TCell::new_invalid(None),
phantom: PhantomData
},
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell::new(VWeakList::default()),
dummy: [],
value: MaybeUninit::<T>::uninit(),
},
journal,
)))
}
}
/// Constructs a new `Prc` with uninitialized contents, with the memory
/// being filled with `0` bytes.
///
/// See `MaybeUninit::zeroed` for examples of correct and incorrect usage of
/// this method.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let zero = Prc::<i32,P>::new_zeroed(j);
/// let zero = unsafe { zero.assume_init() };
///
/// assert_eq!(*zero, 0)
/// }).unwrap();
/// ```
///
pub fn new_zeroed(journal: &Journal<A>) -> Prc<mem::MaybeUninit<T>, A> {
unsafe {
let mut uninit = Self::new_uninit(journal);
std::ptr::write_bytes::<T>(Prc::get_mut_unchecked(&mut uninit).as_mut_ptr(), 0, 1);
uninit
}
}
/// Owns contents of `p` without cloning, leaving `p` untouched
pub fn from(p: Prc<T, A>) -> Self {
let res = Self::from_inner(p.ptr);
mem::forget(p);
res
}
}
impl<T: PSafe + ?Sized, A: MemPool> Prc<T, A> {
#[inline]
fn from_inner(ptr: Ptr<PrcBox<T, A>, A>) -> Self {
Prc {
ptr,
phantom: PhantomData,
}
}
#[inline(always)]
fn inner(&self) -> &PrcBox<T, A> {
self.ptr.as_ref()
}
#[allow(clippy::missing_safety_doc)]
unsafe fn from_ptr(ptr: *mut PrcBox<T, A>, j: &Journal<A>) -> Self {
let off = A::off_unchecked(ptr);
let res = Self::from_inner(Ptr::from_off_unchecked(off));
res.inc_strong(j);
res
}
}
impl<T: PSafe, A: MemPool> Prc<mem::MaybeUninit<T>, A> {
/// Converts to `Rc<T>`.
///
/// # Safety
///
/// As with [`MaybeUninit::assume_init`],
/// it is up to the caller to guarantee that the inner value
/// really is in an initialized state.
/// Calling this when the content is not yet fully initialized
/// causes immediate undefined behavior.
///
/// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// corundum::transaction(|j| {
/// let mut five = Prc::<u32,P>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Prc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5);
/// }).unwrap();
/// ```
#[inline]
pub unsafe fn assume_init(self) -> Prc<T, A> {
Prc::from_inner(mem::ManuallyDrop::new(self).ptr.cast())
}
}
impl<T: PSafe, A: MemPool> Prc<MaybeUninit<T>, A> {
#[inline]
/// Returns a mutable reference into the given `Prc`, if there are
/// no other `Prc` or `Weak` pointers to the same allocation.
///
/// Returns `None` otherwise, because it is not safe to mutate a shared
/// value. It only works for `Prc<MaybeUninit<T>>` to be able to defer the
/// initialization.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let mut five = Prc::<u32,P>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Prc::get_mut(&mut five).unwrap().as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5)
/// }).unwrap();
/// ```
pub fn get_mut(this: &mut Self) -> Option<&mut MaybeUninit<T>> {
if Prc::is_unique(this) {
unsafe { Some(Prc::get_mut_unchecked(this)) }
} else {
None
}
}
#[inline]
/// Returns a mutable reference into the given `Prc`,
/// without any check.
///
/// It only works for `Prc<MaybeUninit<T>>` to be able to defer the
/// initialization.
///
/// # Safety
///
/// Any other `Prc` or `Weak` pointers to the same allocation must not be
/// dereferenced for the duration of the returned borrow.
/// This is trivially the case if no such pointers exist,
/// for example immediately after `Rc::new`.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let mut five = Prc::<i32,P>::new_uninit(j);
///
/// let five = unsafe {
/// // Deferred initialization:
/// Prc::get_mut_unchecked(&mut five).as_mut_ptr().write(5);
///
/// five.assume_init()
/// };
///
/// assert_eq!(*five, 5);
/// }).unwrap();
/// ```
pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut MaybeUninit<T> {
&mut this.ptr.value
}
}
impl<T: PSafe + ?Sized, A: MemPool> Prc<T, A> {
/// Creates a new `Weak` persistent pointer to this allocation.
///
/// The `Weak` pointer can later be [`upgrade`]d to a `Prc`.
///
/// [`upgrade`]: ./struct.Weak.html#upgrade
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let five = Prc::new(5, j);
/// let _weak_five = Prc::downgrade(&five, j);
/// }).unwrap()
/// ```
pub fn downgrade(this: &Self, journal: &Journal<A>) -> Weak<T, A> {
this.inc_weak(journal);
debug_assert!(!this.ptr.is_dangling());
Weak { ptr: this.ptr }
}
/// Creates a new `Weak` volatile to this allocation.
///
/// The `Weak` pointer can later be [`promote`]d to a `Prc`.
///
/// [`promote`]: ./struct.VWeak.html#upgrade
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let five = Prc::new(5, j);
/// let weak_five = Prc::demote(&five);
///
/// assert_eq!(Prc::strong_count(&five), 1);
///
/// if let Some(f) = weak_five.promote(j) {
/// assert_eq!(*f, 5);
/// assert_eq!(Prc::strong_count(&five), 2);
/// }
///
/// assert_eq!(Prc::strong_count(&five), 1);
/// }).unwrap()
/// ```
pub fn demote(this: &Self) -> VWeak<T, A> {
debug_assert!(!this.ptr.is_dangling());
VWeak::new(this)
}
/// Demote without dynamically checking transaction boundaries
pub unsafe fn unsafe_demote(&self) -> VWeak<T, A> {
debug_assert!(!self.ptr.is_dangling());
VWeak::new(self)
}
#[inline]
/// Gets the number of `Weak` pointers to this allocation.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
///
/// P::transaction(|j| {
/// let five = Prc::new(5, j);
///
/// let _weak_five = Prc::downgrade(&five, j);
/// assert_eq!(1, Prc::weak_count(&five));
/// }).unwrap()
/// ```
pub fn weak_count(this: &Self) -> usize {
this.weak() - 1
}
#[inline]
/// Gets the number of `Weak` pointers to this allocation.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
/// use corundum::clone::PClone;
///
/// P::transaction(|j| {
/// let five = Prc::new(5, j);
/// let _also_five = Prc::pclone(&five, j);
/// assert_eq!(2, Prc::strong_count(&five));
/// }).unwrap();
/// ```
pub fn strong_count(this: &Self) -> usize {
this.strong()
}
#[inline]
fn is_unique(this: &Self) -> bool {
Prc::weak_count(this) == 0 && Prc::strong_count(this) == 1
}
#[inline]
/// Returns `true` if the two `Prc`s point to the same allocation
/// (in a vein similar to [`ptr::eq`]).
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
/// use corundum::clone::PClone;
///
/// P::transaction(|j| {
/// let five = Prc::new(5, j);
/// let same_five = Prc::pclone(&five, j);
/// let other_five = Prc::new(5, j);
///
/// assert!(Prc::ptr_eq(&five, &same_five));
/// assert!(!Prc::ptr_eq(&five, &other_five));
/// }).unwrap();
/// ```
///
/// [`ptr::eq`]: std::ptr::eq
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
this.ptr.off() == other.ptr.off()
}
}
impl<T: PSafe, A: MemPool> PmemUsage for Prc<T, A> {
default fn size_of() -> usize {
Ptr::<PrcBox<T, A>, A>::size_of()
}
}
impl<T: PSafe + PmemUsage + ?Sized, A: MemPool> PmemUsage for Prc<T, A> {
fn size_of() -> usize {
Ptr::<PrcBox<T, A>, A>::size_of() + T::size_of()
}
}
impl<T: PSafe + ?Sized, A: MemPool> Deref for Prc<T, A> {
type Target = T;
#[inline(always)]
fn deref(&self) -> &T {
&self.inner().value
}
}
impl<T: PSafe, A: MemPool> Prc<T, A> {
/// Initializes boxed data with `value` in-place if it is `None`
///
/// This function should not be called from a transaction as it updates
/// data without taking high-level logs. If transaction is unsuccessful,
/// there is no way to recover data.
/// However, it is safe to use it outside a transaction because it uses
/// low-level logs to provide safety for a single update without drop.
/// A dynamic check at the beginning makes sure of that.
///
/// # Examples
///
/// ```
/// use corundum::default::*;
///
/// type P = Allocator;
///
/// let root = P::open::<Option<Prc<i32>>>("foo.pool", O_CF).unwrap();
///
/// Prc::initialize(&*root, 25);
///
/// let value = **root.as_ref().unwrap();
/// assert_eq!(value, 25);
/// ```
///
pub fn initialize(rc: &Option<Prc<T, A>>, value: T) -> crate::result::Result<()> {
assert!(
!Journal::<A>::is_running(),
"Prc::initialize() cannot be used inside a transaction"
);
match rc {
Some(_) => Err("already initialized".to_string()),
None => if A::valid(rc) {
unsafe {
let new = A::atomic_new(
PrcBox::<T, A> {
counter: Counter {
strong: 1,
weak: 1,
#[cfg(not(any(
feature = "no_log_rc",
feature = "use_pspd",
feature = "use_vspd"
)))]
has_log: 0,
#[cfg(any(feature = "use_pspd", feature = "use_vspd"))]
temp: TCell::new_invalid(None),
phantom: PhantomData
},
#[cfg(not(feature = "no_volatile_pointers"))]
vlist: VCell::new(VWeakList::default()),
dummy: [],
value,
});
let pnew = Some(Prc::<T, A>::from_inner(Ptr::from_off_unchecked(new.1)));
let src = crate::utils::as_slice64(&pnew);
let mut base = A::off_unchecked(rc);
for i in src {
A::log64(base, *i, new.3);
base += 8;
}
A::perform(new.3);
}
Ok(())
} else {
Err("The object is not in the PM".to_string())
}
}
}
}
unsafe impl<#[may_dangle] T: PSafe + ?Sized, A: MemPool> Drop for Prc<T, A> {
/// Drops the `Prc` safely
///
/// This will decrement the strong reference count. If the strong reference
/// count reaches zero then the only other references (if any) are
/// `Weak`, so we `drop` the inner value on commit using a `DropOnCommit` log.
///
/// # Examples
///
/// ```
/// # use corundum::alloc::heap::*;
/// # type P = Heap;
/// use corundum::prc::Prc;
/// use corundum::clone::PClone;
///
/// struct Foo;
///
/// impl Drop for Foo {
/// fn drop(&mut self) {
/// println!("dropped!");
/// }
/// }
///
/// P::transaction(|j| {
/// let foo = Prc::new(Foo, j);
/// let foo2 = Prc::pclone(&foo, j);
///
/// drop(foo); // Doesn't print anything
/// drop(foo2); // Prints "dropped!"
/// }).unwrap();
/// ```
///
fn drop(&mut self) {
unsafe {
let journal = Journal::<A>::current(true).unwrap();
let j = &*journal.0;
self.dec_strong(j);
if self.strong() == 0 { // TODO: Add "or it is unreachable from the root"
// destroy the contained object
std::ptr::drop_in_place(&mut self.ptr.as_mut().value);
self.dec_weak(j);
if self.weak() == 0 {
A::free(self.ptr.as_mut());
#[cfg(not(feature = "no_volatile_pointers"))]
std::ptr::drop_in_place(&mut self.ptr.as_mut().vlist);
}
}
}
}
}
impl<T: PSafe + ?Sized, A: MemPool> PClone<A> for Prc<T, A> {
#[inline]
/// Creates a new strong reference to the object
///
/// It increments the strong reference counter in a failure-atomic manner.
/// When a transaction is aborted or power fails, every strong references
/// to the object should be gone, and the counters should rollback to the
/// consistent state before the transaction.
///
/// # Examples
///
/// ```
/// # use corundum::default::*;
/// # type P = Allocator;
/// let root = P::open::<Prc<i32>>("foo.pool", O_CF).unwrap();
///
/// let _ = P::transaction(|j| {
/// let _n1 = root.pclone(j);
/// let _n2 = root.pclone(j);
/// let _n3 = root.pclone(j);
/// assert_eq!(4, Prc::strong_count(&root));
/// panic!("abort")
/// });
///
/// assert_eq!(1, Prc::strong_count(&root));
/// ```
fn pclone(&self, journal: &Journal<A>) -> Prc<T, A> {
self.inc_strong(journal);
Self::from_inner(self.ptr)
}
}
impl<T: RootObj<A> + PSafe, A: MemPool> RootObj<A> for Prc<T, A> {
#[inline]
default fn init(journal: &Journal<A>) -> Prc<T, A> {
Prc::new(T::init(journal), journal)
}
}
// impl<T: Default + PSafe + ?Sized, A: MemPool> RootObj<A> for Prc<T, A> {
// #[inline]
// default fn init(journal: &Journal<A>) -> Prc<T, A> {
// Prc::new(T::default(), journal)
// }
// }
trait RcEqIdent<T: PartialEq + PSafe + ?Sized, A: MemPool> {
fn eq(&self, other: &Prc<T, A>) -> bool;
fn ne(&self, other: &Prc<T, A>) -> bool;
}
impl<T: PartialEq + PSafe + ?Sized, A: MemPool> RcEqIdent<T, A> for Prc<T, A> {
#[inline]
fn eq(&self, other: &Prc<T, A>) -> bool {
**self == **other
}
#[inline]
fn ne(&self, other: &Prc<T, A>) -> bool {
**self != **other
}
}
impl<T: PartialEq + PSafe + ?Sized, A: MemPool> PartialEq for Prc<T, A> {
#[inline]
fn eq(&self, other: &Prc<T, A>) -> bool {
RcEqIdent::eq(self, other)
}
}
impl<T: Eq + PSafe + ?Sized, A: MemPool> Eq for Prc<T, A> {}
impl<T: PartialOrd + PSafe + ?Sized, A: MemPool> PartialOrd for Prc<T, A> {
#[inline(always)]
fn partial_cmp(&self, other: &Prc<T, A>) -> Option<Ordering> {
(**self).partial_cmp(&**other)
}
#[inline(always)]
fn lt(&self, other: &Prc<T, A>) -> bool {
**self < **other
}
#[inline(always)]
fn le(&self, other: &Prc<T, A>) -> bool {
**self <= **other
}
#[inline(always)]
fn gt(&self, other: &Prc<T, A>) -> bool {
**self > **other
}
#[inline(always)]
fn ge(&self, other: &Prc<T, A>) -> bool {
**self >= **other
}
}
impl<T: Ord + PSafe + ?Sized, A: MemPool> Ord for Prc<T, A> {
#[inline]
fn cmp(&self, other: &Prc<T, A>) -> Ordering {
(**self).cmp(&**other)
}
}
impl<T: Hash + PSafe + ?Sized, A: MemPool> Hash for Prc<T, A> {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl<T: fmt::Display + PSafe + ?Sized, A: MemPool> fmt::Display for Prc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<T: fmt::Debug + PSafe + ?Sized, A: MemPool> fmt::Debug for Prc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.deref().fmt(f)
}
}
impl<T: PSafe + ?Sized, A: MemPool> fmt::Pointer for Prc<T, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&(&**self as *const T), f)
}
}