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 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
#![allow(unused)] //functions that are usefull for extension
use crate::{
Finaly, Generator, LazySequentializer, LockNature, LockResult, Phase, Phased, Sequential,
Sequentializer, StaticInfo, Uninit, UniqueLazySequentializer,
};
use core::cell::UnsafeCell;
use core::fmt::{self, Debug, Display, Formatter};
use core::hint::unreachable_unchecked;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ops::{Deref, DerefMut};
#[cfg(debug_mode)]
use crate::CyclicPanic;
#[cfg(any(feature = "parking_lot_core", debug_mode))]
use std::panic::RefUnwindSafe;
/// Policy for lazy initialization
pub(crate) trait LazyPolicy {
/// shall the initialization be performed (tested at each access)
fn shall_init(_: Phase) -> bool;
/// Is the object accessible in phase `p`
fn is_accessible(p: Phase) -> bool;
/// Is the object accessible in phase `p`
fn post_init_is_accessible(p: Phase) -> bool;
/// If the object is known to already be initialized, is the object accessible in phase `p`
fn initialized_is_accessible(p: Phase) -> bool;
}
/// Generic lazy interior data storage, uninitialized with interior mutability data storage
/// that call T::finaly when finalized
pub(crate) struct UnInited<T>(UnsafeCell<MaybeUninit<T>>);
impl<T: Finaly> Finaly for UnInited<T> {
#[inline(always)]
fn finaly(&self) {
//SAFETY: UnInited is only used as part of GenericLazy, that gives access
//only if the Sequentializer is a Lazy Sequentializer
//
//So the lazy Sequentializer should only execute finaly if the object initialization
//succeeded
unsafe { &*self.get() }.finaly();
}
}
impl<T> UnInited<T> {
pub const INIT: Self = Self(UnsafeCell::new(MaybeUninit::uninit()));
}
/// Generic lazy interior data storage, initialized with interior mutability data storage
/// that call T::finaly when finalized
pub(crate) struct Primed<T>(UnsafeCell<T>);
impl<T: Uninit> Finaly for Primed<T> {
#[inline(always)]
fn finaly(&self) {
//SAFETY: UnInited is only used as part of GenericLazy, that gives access
//only if the Sequentializer is a Lazy Sequentializer
//
//So the lazy Sequentializer should only execute finaly if the object initialization
//succeeded
unsafe { &mut *self.0.get() }.uninit();
}
}
impl<T> Primed<T> {
pub const fn prime(v: T) -> Self {
Self(UnsafeCell::new(v))
}
}
/// Generic lazy interior data storage, uninitialized with interior mutability data storage
/// that call drop when finalized
pub(crate) struct DropedUnInited<T>(UnsafeCell<MaybeUninit<T>>);
impl<T> Finaly for DropedUnInited<T> {
#[inline(always)]
fn finaly(&self) {
//SAFETY: UnInited is only used as part of GenericLazy, that gives access
//only if the Sequentializer is a Lazy Sequentializer
//
//So the lazy Sequentializer should only execute finaly if the object initialization
//succeeded
unsafe { self.get().drop_in_place() };
}
}
impl<T> DropedUnInited<T> {
pub const INIT: Self = Self(UnsafeCell::new(MaybeUninit::uninit()));
}
/// Trait implemented by generic lazy inner data.
///
/// Dereferencement of generic lazy will return a reference to
/// the inner data returned by the get method
pub(crate) trait LazyData {
type Target;
fn get(&self) -> *mut Self::Target;
/// # Safety
///
/// The reference to self should be unique
unsafe fn init(&self, v: Self::Target);
fn init_mut(&mut self, v: Self::Target);
}
impl<T> LazyData for UnInited<T> {
type Target = T;
#[inline(always)]
fn get(&self) -> *mut T {
self.0.get() as *mut T
}
#[inline(always)]
unsafe fn init(&self, v: T) {
self.get().write(v)
}
#[inline(always)]
fn init_mut(&mut self, v: T) {
*self.0.get_mut() = MaybeUninit::new(v)
}
}
impl<T> LazyData for DropedUnInited<T> {
type Target = T;
#[inline(always)]
fn get(&self) -> *mut T {
self.0.get() as *mut T
}
#[inline(always)]
unsafe fn init(&self, v: T) {
self.get().write(v)
}
#[inline(always)]
fn init_mut(&mut self, v: T) {
*self.0.get_mut() = MaybeUninit::new(v)
}
}
impl<T> LazyData for Primed<T> {
type Target = T;
#[inline(always)]
fn get(&self) -> *mut T {
self.0.get()
}
#[inline(always)]
unsafe fn init(&self, v: T) {
*self.get() = v
}
#[inline(always)]
fn init_mut(&mut self, v: T) {
*self.0.get_mut() = v
}
}
/// Lazy access error
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct AccessError {
pub phase: Phase,
}
impl Display for AccessError {
fn fmt(&self, ft: &mut Formatter<'_>) -> fmt::Result {
write!(ft, "Error: inaccessible lazy in {}", self.phase)
}
}
#[cfg(feature = "parking_lot_core")]
impl std::error::Error for AccessError {}
pub(crate) struct GenericLazySeq<T, M> {
value: T,
sequentializer: M,
}
pub(crate) struct GenericLockedLazySeq<T, M> {
value: T,
sequentializer: M,
}
/// A type that wrap a Sequentializer and a raw data, and that may
/// initialize the data, at each access depending on the LazyPolicy
/// provided as generic argument.
pub(crate) struct GenericLazy<T, F, M, S> {
seq: GenericLazySeq<T, M>,
generator: F,
phantom: PhantomData<S>,
#[cfg(debug_mode)]
_info: Option<StaticInfo>,
}
// SAFETY: The synchronization is ensured by the Sequentializer
// 1. GenericLazy fullfill the requirement that its sequentializer is a field
// of itself as is its target data.
// 2. The sequentializer ensure that the initialization is atomic
unsafe impl<T: LazyData, M: Sync> Sync for GenericLazySeq<T, M> where <T as LazyData>::Target: Sync {}
unsafe impl<T: LazyData, M: Sync> Send for GenericLazySeq<T, M> where <T as LazyData>::Target: Send {}
#[cfg(any(feature = "parking_lot_core", debug_mode))]
impl<T: LazyData, M: RefUnwindSafe> RefUnwindSafe for GenericLazySeq<T, M> where
<T as LazyData>::Target: RefUnwindSafe
{
}
// SAFETY: The synchronization is ensured by the Sequentializer
// 1. GenericLazy fullfill the requirement that its sequentializer is a field
// of itself as is its target data.
// 2. The sequentializer ensure that the initialization is atomic
unsafe impl<T: LazyData, M: Sync> Sync for GenericLockedLazySeq<T, M> where
<T as LazyData>::Target: Send
{
}
unsafe impl<T: LazyData, M: Sync> Send for GenericLockedLazySeq<T, M> where
<T as LazyData>::Target: Send
{
}
#[cfg(any(feature = "parking_lot_core", debug_mode))]
impl<T: LazyData, M: RefUnwindSafe> RefUnwindSafe for GenericLockedLazySeq<T, M> where
<T as LazyData>::Target: RefUnwindSafe
{
}
impl<T, F, M, S> GenericLazy<T, F, M, S> {
#[inline(always)]
/// const initialize the lazy, the inner data may be in an uninitialized state
///
/// # Safety
///
/// ## Constraint on T
///
/// Should initialize the object when init is called and the method get should
/// return a pointer without UB if the object is not initialized
///
/// ## Constraint on P
///
/// The parameter M should be a lazy sequentializer that ensure that:
/// 1. When finalize is called, no other shared reference to the inner data exist
/// 2. The finalization is run only if the object was previously initialized
///
/// ## Constraint on F
///
/// The parameter F should be a Generator that ensured that the object
/// is accessble after a call to generate succeeds
///
/// ## Constraint on S
///
/// S should be a lazy policy that report correctly when the object
/// is accessbile, this in adequation with M and F.
pub const unsafe fn new(generator: F, sequentializer: M, value: T) -> Self {
Self {
seq: GenericLazySeq {
value,
sequentializer,
},
generator,
phantom: PhantomData,
#[cfg(debug_mode)]
_info: None,
}
}
#[inline(always)]
/// const initialize the lazy, the inner data may be in an uninitialized state
///
/// # Safety
///
/// ## Constraint on T
///
/// Should initialize the object when init is called and the method get should
/// return a pointer without UB if the object is not initialized
///
/// ## Constraint on P
///
/// The parameter M should be a lazy sequentializer that ensure that:
/// 1. When finalize is called, no other shared reference to the inner data exist
/// 2. The finalization is run only if the object was previously initialized
///
/// ## Constraint on F
///
/// The parameter F should be a Generator that ensured that the object
/// is accessble after a call to generate succeeds
///
/// ## Constraint on S
///
/// S should be a lazy policy that report correctly when the object
/// is accessbile, this in adequation with M and F.
pub const unsafe fn new_with_info(
generator: F,
sequentializer: M,
value: T,
_info: StaticInfo,
) -> Self {
Self {
seq: GenericLazySeq {
value,
sequentializer,
},
generator,
phantom: PhantomData,
#[cfg(debug_mode)]
_info: Some(_info),
}
}
#[inline(always)]
///get access to the sequentializer
pub fn sequentializer(this: &Self) -> &M {
&this.seq.sequentializer
}
#[inline(always)]
///get a pointer to the raw data
pub fn get_raw_data(this: &Self) -> &T {
&this.seq.value
}
}
impl<'a, T, F, M, S> GenericLazy<T, F, M, S>
where
T: 'a + LazyData,
M: 'a,
M: LazySequentializer<'a, GenericLazySeq<T, M>>,
F: 'a + Generator<T::Target>,
S: 'a + LazyPolicy,
{
/// Get a reference to the target
///
/// # Safety
///
/// Undefined behaviour if the referenced value has not been initialized
#[inline(always)]
pub unsafe fn get_unchecked(&'a self) -> &'a T::Target {
&*self.seq.value.get()
}
/// Get a reference to the target, returning an error if the
/// target is not in the correct phase.
#[inline(always)]
pub fn try_get(&'a self) -> Result<&'a T::Target, AccessError> {
check_access::<*mut T::Target, S>(
self.seq.value.get(),
Phased::phase(&self.seq.sequentializer),
)
.map(|ptr| unsafe { &*ptr })
}
/// Get a reference to the target
///
/// # Panics
///
/// Panic if the target is not in the correct phase
#[inline(always)]
pub fn get(&'a self) -> &'a T::Target {
self.try_get().unwrap()
}
/// Get a mutable reference to the target
///
/// # Safety
///
/// Undefined behaviour if the referenced value has not been initialized
#[inline(always)]
pub unsafe fn get_mut_unchecked(&'a mut self) -> &'a mut T::Target {
&mut *self.seq.value.get()
}
/// Get a mutable reference to the target, returning an error if the
/// target is not in the correct phase.
#[inline(always)]
pub fn try_get_mut(&'a mut self) -> Result<&'a mut T::Target, AccessError> {
check_access::<*mut T::Target, S>(
self.seq.value.get(),
Phased::phase(&self.seq.sequentializer),
)
.map(|ptr| unsafe { &mut *ptr })
}
/// Get a reference to the target
///
/// # Panics
///
/// Panic if the target is not in the correct phase
#[inline(always)]
pub fn get_mut(&'a mut self) -> &'a mut T::Target {
self.try_get_mut().unwrap()
}
/// Attempt initialization then get a reference to the target
///
/// # Safety
///
/// Undefined behaviour if the referenced value has not been initialized
#[inline(always)]
pub unsafe fn init_then_get_unchecked(&'a self) -> &'a T::Target {
self.init();
self.get_unchecked()
}
/// Attempt initialization then get a reference to the target, returning an error if the
/// target is not in the correct phase.
#[inline(always)]
pub fn init_then_try_get(&'a self) -> Result<&'a T::Target, AccessError> {
let phase = self.init();
post_init_check_access::<*mut T::Target, S>(self.seq.value.get(), phase)
.map(|ptr| unsafe { &*ptr })
}
/// Attempt initialization then get a reference to the target, returning an error if the
/// target is not in the correct phase.
#[inline(always)]
pub fn init_then_get(&'a self) -> &'a T::Target {
Self::init_then_try_get(self).unwrap()
}
#[inline(always)]
/// Potentialy initialize the inner data, returning the
/// phase reached at the end of the initialization attempt
pub fn init(&'a self) -> Phase {
may_debug(
|| {
<M as LazySequentializer<'a, GenericLazySeq<T, M>>>::init(
&self.seq,
S::shall_init,
|data: &T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(&self.generator);
unsafe { data.init(d) };
},
)
},
#[cfg(debug_mode)]
&self._info,
)
}
}
impl<T, F, M, S> GenericLazy<T, F, M, S>
where
M: UniqueLazySequentializer<GenericLazySeq<T, M>>,
T: LazyData,
S: LazyPolicy,
F: Generator<T::Target>,
{
#[inline(always)]
/// Attempt initialization then get a mutable reference to the target
///
/// # Safety
///
/// Undefined behaviour if the referenced value has not been initialized
pub unsafe fn only_init_then_get_mut_unchecked(&mut self) -> &mut T::Target {
self.only_init_unique();
&mut *self.seq.value.get()
}
#[inline(always)]
/// Attempt initialization then get a mutable reference to the target, returning an error if the
/// target is not in the correct phase.
pub fn only_init_then_try_get_mut(&mut self) -> Result<&mut T::Target, AccessError> {
let phase = self.only_init_unique();
post_init_check_access::<*mut T::Target, S>(self.seq.value.get(), phase)
.map(|ptr| unsafe { &mut *ptr })
}
#[inline(always)]
/// Attempt initialization then get a mutable reference to the target, returning an error if the
/// target is not in the correct phase.
pub fn only_init_then_get_mut(&mut self) -> &mut T::Target {
Self::only_init_then_try_get_mut(self).unwrap()
}
#[inline(always)]
/// Potentialy initialize the inner data, returning the
/// phase reached at the end of the initialization attempt
pub fn only_init_unique(&mut self) -> Phase {
let generator = &self.generator;
let seq = &mut self.seq;
<M as UniqueLazySequentializer<GenericLazySeq<T, M>>>::init_unique(
seq,
S::shall_init,
|data: &mut T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(generator);
unsafe { data.init_mut(d) };
},
)
}
}
//SAFETY: data and sequentialize are two fields of Self.
unsafe impl<T: LazyData, M> Sequential for GenericLazySeq<T, M> {
type Data = T;
type Sequentializer = M;
#[inline(always)]
fn sequentializer(this: &Self) -> &Self::Sequentializer {
&this.sequentializer
}
#[inline(always)]
fn sequentializer_data_mut(this: &mut Self) -> (&mut Self::Sequentializer, &mut Self::Data) {
(&mut this.sequentializer, &mut this.value)
}
#[inline(always)]
fn data(this: &Self) -> &Self::Data {
&this.value
}
}
#[must_use = "If unused the write lock is immediatly released"]
pub(crate) struct WriteGuard<T>(T);
impl<T> Deref for WriteGuard<T>
where
T: Deref,
<T as Deref>::Target: LazyData,
{
type Target = <<T as Deref>::Target as LazyData>::Target;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*(*self.0).get() }
}
}
impl<T> DerefMut for WriteGuard<T>
where
T: Deref,
<T as Deref>::Target: LazyData,
{
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(*self.0).get() }
}
}
impl<T> Phased for WriteGuard<T>
where
T: Phased,
{
#[inline(always)]
fn phase(this: &Self) -> Phase {
Phased::phase(&this.0)
}
}
impl<T> Debug for WriteGuard<T>
where
T: Deref,
<T as Deref>::Target: LazyData,
<<T as Deref>::Target as LazyData>::Target: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("WriteGuard").field(&*self).finish()
}
}
#[must_use = "If unused the read lock is immediatly released"]
#[derive(Clone)]
pub(crate) struct ReadGuard<T>(T);
impl<T> Deref for ReadGuard<T>
where
T: Deref,
<T as Deref>::Target: LazyData,
{
type Target = <<T as Deref>::Target as LazyData>::Target;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*(*self.0).get() }
}
}
impl<T> Debug for ReadGuard<T>
where
T: Deref,
<T as Deref>::Target: LazyData,
<<T as Deref>::Target as LazyData>::Target: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_tuple("ReadGuard").field(&*self).finish()
}
}
impl<T, U> From<WriteGuard<T>> for ReadGuard<U>
where
U: From<T>,
{
#[inline(always)]
fn from(v: WriteGuard<T>) -> Self {
Self(v.0.into())
}
}
impl<T> Phased for ReadGuard<T>
where
T: Phased,
{
#[inline(always)]
fn phase(this: &Self) -> Phase {
Phased::phase(&this.0)
}
}
#[cfg(any(feature = "parking_lot_core", debug_mode))]
impl<T: LazyData> RefUnwindSafe for ReadGuard<T> where <T as LazyData>::Target: RefUnwindSafe {}
#[cfg(any(feature = "parking_lot_core", debug_mode))]
impl<T: LazyData> RefUnwindSafe for WriteGuard<T> where <T as LazyData>::Target: RefUnwindSafe {}
/// A type that wrap a Sequentializer and a raw data, and that may
/// initialize the data, at each access depending on the LazyPolicy
/// provided as generic argument.
pub(crate) struct GenericLockedLazy<T, F, M, S> {
seq: GenericLockedLazySeq<T, M>,
generator: F,
phantom: PhantomData<S>,
#[cfg(debug_mode)]
_info: Option<StaticInfo>,
}
impl<T, F, M, S> GenericLockedLazy<T, F, M, S> {
#[inline(always)]
/// const initialize the lazy, the inner data may be in an uninitialized state
///
/// # Safety
///
/// ## Constraint on T
///
/// Should initialize the object when init is called and the method get should
/// return a pointer without UB if the object is not initialized
///
/// ## Constraint on P
///
/// The parameter M should be a lazy sequentializer that ensure that:
/// 1. When finalize is called, no other shared reference to the inner data exist
/// 2. The finalization is run only if the object was previously initialized
///
/// ## Constraint on F
///
/// The parameter F should be a Generator that ensured that the object
/// is accessble after a call to generate succeeds
///
/// ## Constraint on S
///
/// S should be a lazy policy that report correctly when the object
/// is accessbile, this in adequation with M and F.
pub const unsafe fn new(generator: F, sequentializer: M, value: T) -> Self {
Self {
seq: GenericLockedLazySeq {
value,
sequentializer,
},
generator,
phantom: PhantomData,
#[cfg(debug_mode)]
_info: None,
}
}
#[inline(always)]
/// const initialize the lazy, the inner data may be in an uninitialized state
///
/// # Safety
///
/// ## Constraint on T
///
/// Should initialize the object when init is called and the method get should
/// return a pointer without UB if the object is not initialized
///
/// ## Constraint on P
///
/// The parameter M should be a lazy sequentializer that ensure that:
/// 1. When finalize is called, no other shared reference to the inner data exist
/// 2. The finalization is run only if the object was previously initialized
///
/// ## Constraint on F
///
/// The parameter F should be a Generator that ensured that the object
/// is accessble after a call to generate succeeds
///
/// ## Constraint on S
///
/// S should be a lazy policy that report correctly when the object
/// is accessbile, this in adequation with M and F.
pub const unsafe fn new_with_info(
generator: F,
sequentializer: M,
value: T,
_info: StaticInfo,
) -> Self {
Self {
seq: GenericLockedLazySeq {
value,
sequentializer,
},
generator,
phantom: PhantomData,
#[cfg(debug_mode)]
_info: Some(_info),
}
}
#[inline(always)]
///get access to the sequentializer
pub fn sequentializer(this: &Self) -> &M {
&this.seq.sequentializer
}
}
impl<'a, T, F, M, S> GenericLockedLazy<T, F, M, S>
where
T: 'a + LazyData,
M: 'a,
M: LazySequentializer<'a, GenericLockedLazySeq<T, M>>,
F: 'a + Generator<T::Target>,
S: 'a + LazyPolicy,
M::ReadGuard: Phased,
M::WriteGuard: Phased,
{
/// Get a mutable reference to the target
///
/// # Safety
///
/// Undefined behaviour if the referenced value has not been initialized
#[inline(always)]
pub unsafe fn get_mut_unchecked(&'a mut self) -> &'a mut T::Target {
&mut *self.seq.value.get()
}
/// Get a mutable reference to the target, returning an error if the
/// target is not in the correct phase.
#[inline(always)]
pub fn try_get_mut(&'a mut self) -> Result<&'a mut T::Target, AccessError> {
check_access::<*mut T::Target, S>(
self.seq.value.get(),
Phased::phase(&self.seq.sequentializer),
)
.map(|ptr| unsafe { &mut *ptr })
}
/// Get a reference to the target
///
/// # Panics
///
/// Panic if the target is not in the correct phase
#[inline(always)]
pub fn get_mut(&'a mut self) -> &'a mut T::Target {
self.try_get_mut().unwrap()
}
/// Attempt to get a read lock the LazyData object (not the target), returning None
/// if a unique lock is already held or in high contention cases.
///
/// # Safety
///
/// The obtained [ReadGuard] may reference an uninitialized target.
#[inline(always)]
pub unsafe fn fast_read_lock_unchecked(this: &'a Self) -> Option<ReadGuard<M::ReadGuard>> {
<M as Sequentializer<'a, GenericLockedLazySeq<T, M>>>::try_lock(
&this.seq,
|_| LockNature::Read,
M::INITIALIZED_HINT,
)
.map(|l| {
if let LockResult::Read(l) = l {
ReadGuard(l)
} else {
unreachable_unchecked()
}
})
}
/// Attempt to get a read lock the LazyData object (not the target), returning None
/// if a unique lock is already held or in high contention cases.
///
/// If the lock succeeds and the object is not in an accessible phase, some error is returned
#[inline(always)]
pub fn fast_try_read_lock(
this: &'a Self,
) -> Option<Result<ReadGuard<M::ReadGuard>, AccessError>> {
unsafe { Self::fast_read_lock_unchecked(this) }
.map(checked_access::<ReadGuard<M::ReadGuard>, S>)
}
/// Attempt to get a read lock the LazyData object (not the target), returning None
/// if a unique lock is already held or in high contention cases.
///
/// # Panics
///
/// Panics if the lock succeeds and the object is not in an accessible phase.
#[inline(always)]
pub fn fast_read_lock(this: &'a Self) -> Option<ReadGuard<M::ReadGuard>> {
Self::fast_try_read_lock(this).map(|r| r.unwrap())
}
/// Get a read lock the LazyData object (not the target)
///
/// # Safety
///
/// The obtained [ReadGuard] may reference an uninitialized target.
#[inline(always)]
pub unsafe fn read_lock_unchecked(this: &'a Self) -> ReadGuard<M::ReadGuard> {
if let LockResult::Read(l) = <M as Sequentializer<'a, GenericLockedLazySeq<T, M>>>::lock(
&this.seq,
|_| LockNature::Read,
M::INITIALIZED_HINT,
) {
ReadGuard(l)
} else {
unreachable_unchecked()
}
}
/// Get a read lock the LazyData object (not the target)
///
/// If the object is not in an accessible phase, some error is returned
#[inline(always)]
pub fn try_read_lock(this: &'a Self) -> Result<ReadGuard<M::ReadGuard>, AccessError> {
checked_access::<ReadGuard<M::ReadGuard>, S>(unsafe { Self::read_lock_unchecked(this) })
}
/// Get a read lock the LazyData object (not the target).
///
/// # Panics
///
/// Panics if the lock succeeds and the object is not in an accessible phase.
#[inline(always)]
pub fn read_lock(this: &'a Self) -> ReadGuard<M::ReadGuard> {
Self::try_read_lock(this).unwrap()
}
/// Attempt to get a write lock the LazyData object (not the target), returning None
/// if a lock is already held or in high contention cases.
///
/// # Safety
///
/// The obtained [ReadGuard] may reference an uninitialized target.
#[inline(always)]
pub unsafe fn fast_write_lock_unchecked(this: &'a Self) -> Option<WriteGuard<M::WriteGuard>> {
<M as Sequentializer<'a, GenericLockedLazySeq<T, M>>>::try_lock(
&this.seq,
|_| LockNature::Write,
M::INITIALIZED_HINT,
)
.map(|l| {
if let LockResult::Write(l) = l {
WriteGuard(l)
} else {
unreachable_unchecked()
}
})
}
/// Attempt to get a write lock the LazyData object (not the target), returning None
/// if a lock is already held or in high contention cases.
///
/// If the lock succeeds and the object is not in an accessible phase, some error is returned
#[inline(always)]
pub fn fast_try_write_lock(
this: &'a Self,
) -> Option<Result<WriteGuard<M::WriteGuard>, AccessError>> {
unsafe { Self::fast_write_lock_unchecked(this) }
.map(checked_access::<WriteGuard<M::WriteGuard>, S>)
}
/// Attempt to get a write lock the LazyData object (not the target), returning None
/// if a lock is already held or in high contention cases.
///
/// # Panics
///
/// Panics if the lock succeeds and the object is not in an accessible phase.
#[inline(always)]
pub fn fast_write_lock(this: &'a Self) -> Option<WriteGuard<M::WriteGuard>> {
Self::fast_try_write_lock(this).map(|r| r.unwrap())
}
/// Get a write lock the LazyData object (not the target)
///
/// # Safety
///
/// The obtained [ReadGuard] may reference an uninitialized target.
#[inline(always)]
pub unsafe fn write_lock_unchecked(this: &'a Self) -> WriteGuard<M::WriteGuard> {
if let LockResult::Write(l) = <M as Sequentializer<'a, GenericLockedLazySeq<T, M>>>::lock(
&this.seq,
|_| LockNature::Write,
M::INITIALIZED_HINT,
) {
WriteGuard(l)
} else {
unreachable_unchecked()
}
}
/// Get a read lock the LazyData object (not the target)
///
/// If the object is not in an accessible phase, an error is returned
#[inline(always)]
pub fn try_write_lock(this: &'a Self) -> Result<WriteGuard<M::WriteGuard>, AccessError> {
checked_access::<WriteGuard<M::WriteGuard>, S>(unsafe { Self::write_lock_unchecked(this) })
}
/// Get a write lock the LazyData object (not the target).
///
/// # Panics
///
/// Panics if the lock succeeds and the object is not in an accessible phase.
#[inline(always)]
pub fn write_lock(this: &'a Self) -> WriteGuard<M::WriteGuard> {
Self::try_write_lock(this).unwrap()
}
#[inline(always)]
/// Initialize if necessary then return a read lock
///
/// # Safety
///
/// Undefined behaviour if after initialization the return object is not in an accessible
/// state.
pub unsafe fn init_then_read_lock_unchecked(this: &'a Self) -> ReadGuard<M::ReadGuard> {
let r = may_debug(
|| {
<M as LazySequentializer<'a, GenericLockedLazySeq<T, M>>>::init_then_read_guard(
&this.seq,
S::shall_init,
|data: &T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(&this.generator);
#[allow(unused_unsafe)]
unsafe {
data.init(d)
};
},
)
},
#[cfg(debug_mode)]
&this._info,
);
ReadGuard(r)
}
/// Initialize if necessary then return a read lock
///
/// Returns an error if after initialization the return object is not in an accessible
/// state.
#[inline(always)]
pub fn init_then_try_read_lock(this: &'a Self) -> Result<ReadGuard<M::ReadGuard>, AccessError> {
post_init_checked_access::<ReadGuard<M::ReadGuard>, S>(unsafe {
Self::init_then_read_lock_unchecked(this)
})
}
/// Initialize if necessary then return a read lock
///
/// # Panics
///
/// Panics if after initialization the return object is not in an accessible
/// state.
#[inline(always)]
pub fn init_then_read_lock(this: &'a Self) -> ReadGuard<M::ReadGuard> {
Self::init_then_try_read_lock(this).unwrap()
}
/// If necessary attempt to get a write_lock initilialize the object then turn the write
/// lock into a read lock, otherwise attempt to get directly a read_lock. Attempt to take
/// a lock may fail because other locks are held or because of contention.
///
/// # Safety
///
/// If the target is not accessible this may cause undefined behaviour.
#[inline(always)]
pub unsafe fn fast_init_then_read_lock_unchecked(
this: &'a Self,
) -> Option<ReadGuard<M::ReadGuard>> {
may_debug(
|| {
<M as LazySequentializer<'a, GenericLockedLazySeq<T, M>>>::try_init_then_read_guard(
&this.seq,
S::shall_init,
|data: &T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(&this.generator);
#[allow(unused_unsafe)]
unsafe {
data.init(d)
};
},
)
},
#[cfg(debug_mode)]
&this._info,
)
.map(ReadGuard)
}
#[inline(always)]
/// If necessary attempt to get a write_lock initilialize the object then turn the write
/// lock into a read lock, otherwise attempt to get directly a read_lock. Attempt to take
/// a lock may fail because other locks are held or because of contention.
///
/// If the target is not accessible some error is returned.
pub fn fast_init_then_try_read_lock(
this: &'a Self,
) -> Option<Result<ReadGuard<M::ReadGuard>, AccessError>> {
unsafe { Self::fast_init_then_read_lock_unchecked(this) }
.map(post_init_checked_access::<ReadGuard<M::ReadGuard>, S>)
}
#[inline(always)]
/// If necessary attempt to get a write_lock initilialize the object then turn the write
/// lock into a read lock, otherwise attempt to get directly a read_lock. Attempt to take
/// a lock may fail because other locks are held or because of contention.
///
/// # Panics
///
/// If the target is not accessible some error is returned.
pub fn fast_init_then_read_lock(this: &'a Self) -> Option<ReadGuard<M::ReadGuard>> {
Self::fast_init_then_try_read_lock(this).map(|r| r.unwrap())
}
#[inline(always)]
/// Get a write locks, initialize the target if necessary then returns a readlock.
///
/// # Safety
///
/// If the target object is not accessible, this will cause undefined behaviour
pub unsafe fn init_then_write_lock_unchecked(this: &'a Self) -> WriteGuard<M::WriteGuard> {
let r = may_debug(
|| {
<M as LazySequentializer<'a, GenericLockedLazySeq<T, M>>>::init_then_write_guard(
&this.seq,
S::shall_init,
|data: &T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(&this.generator);
#[allow(unused_unsafe)]
unsafe {
data.init(d)
};
},
)
},
#[cfg(debug_mode)]
&this._info,
);
WriteGuard(r)
}
#[inline(always)]
/// Get a write locks, initialize the target if necessary then returns the write lock.
///
/// If the target object is not accessible an error is returned.
pub fn init_then_try_write_lock(
this: &'a Self,
) -> Result<WriteGuard<M::WriteGuard>, AccessError> {
post_init_checked_access::<WriteGuard<M::WriteGuard>, S>(unsafe {
Self::init_then_write_lock_unchecked(this)
})
}
#[inline(always)]
/// Get a write locks, initialize the target if necessary then returns a write lock.
///
/// Panics if the target object is not accessible.
#[inline(always)]
pub fn init_then_write_lock(this: &'a Self) -> WriteGuard<M::WriteGuard> {
Self::init_then_try_write_lock(this).unwrap()
}
#[inline(always)]
/// Attempt to get a write locks then initialize the target if necessary and returns the
/// writelock.
///
/// # Safety
///
/// Undefined behavior if the target object is not accessible.
pub unsafe fn fast_init_then_write_lock_unchecked(
this: &'a Self,
) -> Option<WriteGuard<M::WriteGuard>> {
may_debug(
|| {
<M as LazySequentializer<'a, GenericLockedLazySeq<T, M>>>::try_init_then_write_guard(
&this.seq,
S::shall_init,
|data: &T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(&this.generator);
#[allow(unused_unsafe)]
unsafe { data.init(d) };
},
)
},
#[cfg(debug_mode)]
&this._info,
)
.map(WriteGuard)
}
/// Attempt to get a write locks then initialize the target if necessary and returns the
/// writelock.
///
/// Returns an error if the target object is not accessible.
#[inline(always)]
pub fn fast_init_then_try_write_lock(
this: &'a Self,
) -> Option<Result<WriteGuard<M::WriteGuard>, AccessError>> {
unsafe { Self::fast_init_then_write_lock_unchecked(this) }
.map(post_init_checked_access::<WriteGuard<M::WriteGuard>, S>)
}
/// Attempt to get a write locks then initialize the target if necessary and returns the
/// writelock.
///
/// # Panics
///
/// Panics if the target object is not accessible.
#[inline(always)]
pub fn fast_init_then_write_lock(this: &'a Self) -> Option<WriteGuard<M::WriteGuard>> {
Self::fast_init_then_try_write_lock(this).map(|r| r.unwrap())
}
}
impl<T, F, M, S> GenericLockedLazy<T, F, M, S>
where
M: UniqueLazySequentializer<GenericLockedLazySeq<T, M>>,
T: LazyData,
S: LazyPolicy,
F: Generator<T::Target>,
{
#[inline(always)]
/// Attempt initialization then get a mutable reference to the target
///
/// # Safety
///
/// Undefined behaviour if the referenced value has not been initialized
pub unsafe fn only_init_then_get_mut_unchecked(&mut self) -> &mut T::Target {
self.only_init_unique();
&mut *self.seq.value.get()
}
#[inline(always)]
/// Attempt initialization then get a mutable reference to the target, returning an error if the
/// target is not in the correct phase.
pub fn only_init_then_try_get_mut(&mut self) -> Result<&mut T::Target, AccessError> {
let phase = self.only_init_unique();
check_access::<*mut T::Target, S>(self.seq.value.get(), phase)
.map(|ptr| unsafe { &mut *ptr })
}
#[inline(always)]
/// Attempt initialization then get a mutable reference to the target, returning an error if the
/// target is not in the correct phase.
pub fn only_init_then_get_mut(&mut self) -> &mut T::Target {
Self::only_init_then_try_get_mut(self).unwrap()
}
#[inline(always)]
/// Potentialy initialize the inner data, returning the
/// phase reached at the end of the initialization attempt
pub fn only_init_unique(&mut self) -> Phase {
let generator = &self.generator;
let seq = &mut self.seq;
<M as UniqueLazySequentializer<GenericLockedLazySeq<T, M>>>::init_unique(
seq,
S::shall_init,
|data: &mut T| {
// SAFETY
// This function is called only once within the init function
// Only one thread can ever get this mutable access
let d = Generator::generate(generator);
unsafe { data.init_mut(d) };
},
)
}
}
//SAFETY: data and sequentialize are two fields of Self.
unsafe impl<T: LazyData, M> Sequential for GenericLockedLazySeq<T, M> {
type Data = T;
type Sequentializer = M;
#[inline(always)]
fn sequentializer(this: &Self) -> &Self::Sequentializer {
&this.sequentializer
}
#[inline(always)]
fn sequentializer_data_mut(this: &mut Self) -> (&mut Self::Sequentializer, &mut Self::Data) {
(&mut this.sequentializer, &mut this.value)
}
#[inline(always)]
fn data(this: &Self) -> &Self::Data {
&this.value
}
}
impl<F, T, M, S> Deref for GenericLockedLazy<T, F, M, S> {
type Target = T;
#[inline(always)]
///get a pointer to the raw data
fn deref(&self) -> &T {
&self.seq.value
}
}
impl<T, M> Deref for GenericLockedLazySeq<T, M> {
type Target = T;
#[inline(always)]
///get a pointer to the raw data
fn deref(&self) -> &T {
&self.value
}
}
impl<F, T, M: Phased, S> Phased for GenericLockedLazy<T, F, M, S> {
#[inline(always)]
fn phase(this: &Self) -> Phase {
Phased::phase(&this.seq.sequentializer)
}
}
impl<F, T, M: Phased, S> Phased for GenericLazy<T, F, M, S> {
#[inline(always)]
fn phase(this: &Self) -> Phase {
Phased::phase(&this.seq.sequentializer)
}
}
#[inline(always)]
fn may_debug<R, F: FnOnce() -> R>(f: F, #[cfg(debug_mode)] info: &Option<StaticInfo>) -> R {
#[cfg(not(debug_mode))]
{
f()
}
#[cfg(debug_mode)]
{
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f())) {
Ok(r) => r,
Err(x) => {
if x.is::<CyclicPanic>() {
match info {
Some(info) => panic!("Circular initialization of {:#?}", info),
None => panic!("Circular lazy initialization detected"),
}
} else {
std::panic::resume_unwind(x)
}
}
}
}
}
#[inline(always)]
fn check_access<T, S: LazyPolicy>(l: T, phase: Phase) -> Result<T, AccessError> {
if S::is_accessible(phase) {
Ok(l)
} else {
Err(AccessError { phase })
}
}
#[inline(always)]
fn checked_access<T: Phased, S: LazyPolicy>(l: T) -> Result<T, AccessError> {
let phase = Phased::phase(&l);
check_access::<T, S>(l, phase)
}
#[inline(always)]
fn post_init_check_access<T, S: LazyPolicy>(l: T, phase: Phase) -> Result<T, AccessError> {
if S::post_init_is_accessible(phase) {
Ok(l)
} else {
Err(AccessError { phase })
}
}
#[inline(always)]
fn post_init_checked_access<T: Phased, S: LazyPolicy>(l: T) -> Result<T, AccessError> {
let phase = Phased::phase(&l);
post_init_check_access::<T, S>(l, phase)
}