happylock 0.5.1

Free deadlock prevention
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
use std::mem::MaybeUninit;

/// A raw lock type that may be locked and unlocked
///
/// # Safety
///
/// A deadlock must never occur when using these methods correctly.
//
// Why not use a RawRwLock? Because that would be semantically incorrect, and I
// don't want an INIT or GuardMarker associated item.
// Originally, RawLock had a sister trait: RawSharableLock. I removed it
// because it'd be difficult to implement a separate type that takes a
// different kind of RawLock. But now the Sharable marker trait is needed to
// indicate if reads can be used.
pub unsafe trait RawLock {
	/// Causes all subsequent calls to the `lock` function on this lock to
	/// panic. This does not affect anything currently holding the lock.
	fn poison(&self);

	/// Blocks until the lock is acquired
	///
	/// # Safety
	///
	/// It is undefined behavior to use this without ownership or mutable
	/// access to the [`ThreadKey`], which should last as long as the lock is
	/// held.
	///
	/// [`ThreadKey`]: `crate::ThreadKey`
	unsafe fn raw_write(&self);

	/// Attempt to lock without blocking.
	///
	/// Returns `true` if successful, `false` otherwise.
	///
	/// # Safety
	///
	/// It is undefined behavior to use this without ownership or mutable
	/// access to the [`ThreadKey`], which should last as long as the lock is
	/// held.
	///
	/// [`ThreadKey`]: `crate::ThreadKey`
	unsafe fn raw_try_write(&self) -> bool;

	/// Releases the lock
	///
	/// # Safety
	///
	/// It is undefined behavior to use this if the lock is not acquired by the
	/// calling thread.
	unsafe fn raw_unlock_write(&self);

	/// Blocks until the data the lock protects can be safely read.
	///
	/// Some locks, but not all, will allow multiple readers at once. If
	/// multiple readers are allowed for a [`Lockable`] type, then the
	/// [`Sharable`] marker trait should be implemented.
	///
	/// # Safety
	///
	/// It is undefined behavior to use this without ownership or mutable
	/// access to the [`ThreadKey`], which should last as long as the lock is
	/// held.
	///
	/// [`ThreadKey`]: `crate::ThreadKey`
	unsafe fn raw_read(&self);

	// Attempt to read without blocking.
	///
	/// Returns `true` if successful, `false` otherwise.
	///
	/// Some locks, but not all, will allow multiple readers at once. If
	/// multiple readers are allowed for a [`Lockable`] type, then the
	/// [`Sharable`] marker trait should be implemented.
	///
	/// # Safety
	///
	/// It is undefined behavior to use this without ownership or mutable
	/// access to the [`ThreadKey`], which should last as long as the lock is
	/// held.
	///
	/// [`ThreadKey`]: `crate::ThreadKey`
	unsafe fn raw_try_read(&self) -> bool;

	/// Releases the lock after calling `read`.
	///
	/// # Safety
	///
	/// It is undefined behavior to use this if the read lock is not held by the
	/// calling thread.
	unsafe fn raw_unlock_read(&self);
}

/// A type that may be locked and unlocked.
///
/// This trait is usually implemented on collections of [`RawLock`]s. For
/// example, a `Vec<Mutex<i32>>`.
///
/// # Safety
///
/// Acquiring the locks returned by `get_ptrs` must allow access to the values
/// returned by `guard`.
///
/// Dropping the `Guard` must unlock those same locks.
///
/// The order of the resulting list from `get_ptrs` must be deterministic. As
/// long as the value is not mutated, the references must always be in the same
/// order.
///
/// The list returned by `get_ptrs` must contain any lock which could possibly
/// be referenced in another collection.
pub unsafe trait Lockable {
	/// The exclusive guard that does not hold a key
	type Guard<'g>
	where
		Self: 'g;

	/// A reference to the protected data
	type DataMut<'a>
	where
		Self: 'a;

	/// Yields a list of references to the [`RawLock`]s contained within this
	/// value.
	///
	/// These reference locks which must be locked before acquiring a guard,
	/// and unlocked when the guard is dropped. The order of the resulting list
	/// is deterministic. As long as the value is not mutated, the references
	/// will always be in the same order.
	fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>);

	/// Returns a guard that can be used to access the underlying data mutably.
	///
	/// # Safety
	///
	/// All locks given by calling [`Lockable::get_ptrs`] must be locked
	/// exclusively before calling this function. The locks must not be
	/// unlocked until this guard is dropped.
	#[must_use]
	unsafe fn guard(&self) -> Self::Guard<'_>;

	/// Returns a mutable reference to the data protected by this lock.
	///
	/// # Safety
	///
	/// All locks given by calling [`Lockable::get_ptrs`] must be locked
	/// exclusively before calling this function. The locks must not be unlocked
	/// until the lifetime of this reference ends.
	#[must_use]
	unsafe fn data_mut(&self) -> Self::DataMut<'_>;
}

/// Allows a lock to be accessed by multiple readers.
///
/// # Safety
///
/// Acquiring shared access to the locks returned by `get_ptrs` must allow
/// shared access to the values returned by `read_guard`.
///
/// Dropping the `ReadGuard` must unlock those same locks.
pub unsafe trait Sharable: Lockable {
	/// The shared guard type that does not hold a key
	type ReadGuard<'g>
	where
		Self: 'g;

	/// An immutable reference to the protected data
	type DataRef<'a>
	where
		Self: 'a;

	/// Returns a guard that can be used to immutably access the underlying
	/// data.
	///
	/// # Safety
	///
	/// All locks given by calling [`Lockable::get_ptrs`] must be locked using
	/// [`RawLock::raw_read`] before calling this function. The locks must not be
	/// unlocked until this guard is dropped.
	#[must_use]
	unsafe fn read_guard(&self) -> Self::ReadGuard<'_>;

	/// Creates an immutable reference to the data that is protected by this lock.
	///
	/// # Safety
	///
	/// All locks given by calling [`Lockable::get_ptrs`] must be locked using
	/// [`RawLock::raw_read`] before calling this function. The locks must not be
	/// unlocked until the lifetime of this reference ends.
	#[must_use]
	unsafe fn data_ref(&self) -> Self::DataRef<'_>;
}

/// A type that may be locked and unlocked, and is known to be the only valid
/// instance of the lock.
///
/// # Safety
///
/// There must not be any two values which can unlock the value at the same
/// time, i.e., this must either be an owned value or a mutable reference.
pub unsafe trait OwnedLockable: Lockable {}

/// A trait which indicates that `into_inner` is a valid operation for a
/// [`Lockable`].
///
/// This is used for types like [`Poisonable`] to access the inner value of a
/// lock. [`Poisonable::into_inner`] calls [`LockableIntoInner::into_inner`] to
/// return a mutable reference of the inner value. This isn't implemented for
/// some `Lockable`s, such as `&[T]`.
///
/// [`Poisonable`]: `crate::Poisonable`
/// [`Poisonable::into_inner`]: `crate::poisonable::Poisonable::into_inner`
pub trait LockableIntoInner: Lockable {
	/// The inner type that is behind the lock
	type Inner;

	/// Consumes the lock, returning the underlying the lock.
	fn into_inner(self) -> Self::Inner;
}

/// A trait which indicates that `as_mut` is a valid operation for a
/// [`Lockable`].
///
/// This is used for types like [`Poisonable`] to access the inner value of a
/// lock. [`Poisonable::get_mut`] calls [`LockableGetMut::get_mut`] to return a
/// mutable reference of the inner value. This isn't implemented for some
/// `Lockable`s, such as `&[T]`.
///
/// [`Poisonable`]: `crate::Poisonable`
/// [`Poisonable::get_mut`]: `crate::poisonable::Poisonable::get_mut`
pub trait LockableGetMut: Lockable {
	/// The inner type that is behind the lock
	type Inner<'a>
	where
		Self: 'a;

	/// Returns a mutable reference to the underlying data.
	fn get_mut(&mut self) -> Self::Inner<'_>;
}

unsafe impl<T: Lockable> Lockable for &T {
	type Guard<'g>
		= T::Guard<'g>
	where
		Self: 'g;

	type DataMut<'a>
		= T::DataMut<'a>
	where
		Self: 'a;

	fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
		(*self).get_ptrs(ptrs);
	}

	unsafe fn guard(&self) -> Self::Guard<'_> {
		(*self).guard()
	}

	unsafe fn data_mut(&self) -> Self::DataMut<'_> {
		(*self).data_mut()
	}
}

unsafe impl<T: Sharable> Sharable for &T {
	type ReadGuard<'g>
		= T::ReadGuard<'g>
	where
		Self: 'g;

	type DataRef<'a>
		= T::DataRef<'a>
	where
		Self: 'a;

	unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
		(*self).read_guard()
	}

	unsafe fn data_ref(&self) -> Self::DataRef<'_> {
		(*self).data_ref()
	}
}

unsafe impl<T: Lockable> Lockable for &mut T {
	type Guard<'g>
		= T::Guard<'g>
	where
		Self: 'g;

	type DataMut<'a>
		= T::DataMut<'a>
	where
		Self: 'a;

	fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
		(**self).get_ptrs(ptrs)
	}

	unsafe fn guard(&self) -> Self::Guard<'_> {
		(**self).guard()
	}

	unsafe fn data_mut(&self) -> Self::DataMut<'_> {
		(**self).data_mut()
	}
}

impl<T: LockableGetMut> LockableGetMut for &mut T {
	type Inner<'a>
		= T::Inner<'a>
	where
		Self: 'a;

	fn get_mut(&mut self) -> Self::Inner<'_> {
		(*self).get_mut()
	}
}

unsafe impl<T: Sharable> Sharable for &mut T {
	type ReadGuard<'g>
		= T::ReadGuard<'g>
	where
		Self: 'g;

	type DataRef<'a>
		= T::DataRef<'a>
	where
		Self: 'a;

	unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
		(**self).read_guard()
	}

	unsafe fn data_ref(&self) -> Self::DataRef<'_> {
		(**self).data_ref()
	}
}

unsafe impl<T: OwnedLockable> OwnedLockable for &mut T {}

/// Implements `Lockable`, `Sharable`, and `OwnedLockable` for tuples
/// ex: `tuple_impls!(A B C, 0 1 2);`
macro_rules! tuple_impls {
	($($generic:ident)*, $($value:tt)*) => {
		unsafe impl<$($generic: Lockable,)*> Lockable for ($($generic,)*) {
			type Guard<'g> = ($($generic::Guard<'g>,)*) where Self: 'g;

			type DataMut<'a> = ($($generic::DataMut<'a>,)*) where Self: 'a;

			fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
				$(self.$value.get_ptrs(ptrs));*
			}

			unsafe fn guard(&self) -> Self::Guard<'_> {
				($(self.$value.guard(),)*)
			}

			unsafe fn data_mut(&self) -> Self::DataMut<'_> {
				($(self.$value.data_mut(),)*)
			}
		}

		impl<$($generic: LockableGetMut,)*> LockableGetMut for ($($generic,)*) {
			type Inner<'a> = ($($generic::Inner<'a>,)*) where Self: 'a;

			fn get_mut(&mut self) -> Self::Inner<'_> {
				($(self.$value.get_mut(),)*)
			}
		}

		impl<$($generic: LockableIntoInner,)*> LockableIntoInner for ($($generic,)*) {
			type Inner = ($($generic::Inner,)*);

			fn into_inner(self) -> Self::Inner {
				($(self.$value.into_inner(),)*)
			}
		}

		unsafe impl<$($generic: Sharable,)*> Sharable for ($($generic,)*) {
			type ReadGuard<'g> = ($($generic::ReadGuard<'g>,)*) where Self: 'g;

			type DataRef<'a> = ($($generic::DataRef<'a>,)*) where Self: 'a;

			unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
				($(self.$value.read_guard(),)*)
			}

			unsafe fn data_ref(&self) -> Self::DataRef<'_> {
				($(self.$value.data_ref(),)*)
			}
		}

		unsafe impl<$($generic: OwnedLockable,)*> OwnedLockable for ($($generic,)*) {}
	};
}

tuple_impls!(A, 0);
tuple_impls!(A B, 0 1);
tuple_impls!(A B C, 0 1 2);
tuple_impls!(A B C D, 0 1 2 3);
tuple_impls!(A B C D E, 0 1 2 3 4);
tuple_impls!(A B C D E F, 0 1 2 3 4 5);
tuple_impls!(A B C D E F G, 0 1 2 3 4 5 6);

unsafe impl<T: Lockable, const N: usize> Lockable for [T; N] {
	type Guard<'g>
		= [T::Guard<'g>; N]
	where
		Self: 'g;

	type DataMut<'a>
		= [T::DataMut<'a>; N]
	where
		Self: 'a;

	fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
		for lock in self {
			lock.get_ptrs(ptrs);
		}
	}

	unsafe fn guard<'g>(&'g self) -> Self::Guard<'g> {
		// The MaybeInit helper functions for arrays aren't stable yet, so
		// we'll just have to implement it ourselves
		let mut guards = MaybeUninit::<[MaybeUninit<T::Guard<'g>>; N]>::uninit().assume_init();
		for i in 0..N {
			guards[i].write(self[i].guard());
		}

		guards.map(|g| g.assume_init())
	}

	unsafe fn data_mut<'a>(&'a self) -> Self::DataMut<'a> {
		let mut guards = MaybeUninit::<[MaybeUninit<T::DataMut<'a>>; N]>::uninit().assume_init();
		for i in 0..N {
			guards[i].write(self[i].data_mut());
		}

		guards.map(|g| g.assume_init())
	}
}

impl<T: LockableGetMut, const N: usize> LockableGetMut for [T; N] {
	type Inner<'a>
		= [T::Inner<'a>; N]
	where
		Self: 'a;

	fn get_mut(&mut self) -> Self::Inner<'_> {
		unsafe {
			let mut guards = MaybeUninit::<[MaybeUninit<T::Inner<'_>>; N]>::uninit().assume_init();
			for (i, lock) in self.iter_mut().enumerate() {
				guards[i].write(lock.get_mut());
			}

			guards.map(|g| g.assume_init())
		}
	}
}

impl<T: LockableIntoInner, const N: usize> LockableIntoInner for [T; N] {
	type Inner = [T::Inner; N];

	fn into_inner(self) -> Self::Inner {
		unsafe {
			let mut guards = MaybeUninit::<[MaybeUninit<T::Inner>; N]>::uninit().assume_init();
			for (i, lock) in self.into_iter().enumerate() {
				guards[i].write(lock.into_inner());
			}

			guards.map(|g| g.assume_init())
		}
	}
}

unsafe impl<T: Sharable, const N: usize> Sharable for [T; N] {
	type ReadGuard<'g>
		= [T::ReadGuard<'g>; N]
	where
		Self: 'g;

	type DataRef<'a>
		= [T::DataRef<'a>; N]
	where
		Self: 'a;

	unsafe fn read_guard<'g>(&'g self) -> Self::ReadGuard<'g> {
		let mut guards = MaybeUninit::<[MaybeUninit<T::ReadGuard<'g>>; N]>::uninit().assume_init();
		for i in 0..N {
			guards[i].write(self[i].read_guard());
		}

		guards.map(|g| g.assume_init())
	}

	unsafe fn data_ref<'a>(&'a self) -> Self::DataRef<'a> {
		let mut guards = MaybeUninit::<[MaybeUninit<T::DataRef<'a>>; N]>::uninit().assume_init();
		for i in 0..N {
			guards[i].write(self[i].data_ref());
		}

		guards.map(|g| g.assume_init())
	}
}

unsafe impl<T: OwnedLockable, const N: usize> OwnedLockable for [T; N] {}

unsafe impl<T: Lockable> Lockable for Box<[T]> {
	type Guard<'g>
		= Box<[T::Guard<'g>]>
	where
		Self: 'g;

	type DataMut<'a>
		= Box<[T::DataMut<'a>]>
	where
		Self: 'a;

	fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
		for lock in self {
			lock.get_ptrs(ptrs);
		}
	}

	unsafe fn guard(&self) -> Self::Guard<'_> {
		self.iter().map(|lock| lock.guard()).collect()
	}

	unsafe fn data_mut(&self) -> Self::DataMut<'_> {
		self.iter().map(|lock| lock.data_mut()).collect()
	}
}

impl<T: LockableGetMut + 'static> LockableGetMut for Box<[T]> {
	type Inner<'a>
		= Box<[T::Inner<'a>]>
	where
		Self: 'a;

	fn get_mut(&mut self) -> Self::Inner<'_> {
		self.iter_mut().map(LockableGetMut::get_mut).collect()
	}
}

impl<T: LockableIntoInner + 'static> LockableIntoInner for Box<[T]> {
	type Inner = Box<[T::Inner]>;

	fn into_inner(self) -> Self::Inner {
		Self::into_iter(self)
			.map(LockableIntoInner::into_inner)
			.collect()
	}
}

unsafe impl<T: Sharable> Sharable for Box<[T]> {
	type ReadGuard<'g>
		= Box<[T::ReadGuard<'g>]>
	where
		Self: 'g;

	type DataRef<'a>
		= Box<[T::DataRef<'a>]>
	where
		Self: 'a;

	unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
		self.iter().map(|lock| lock.read_guard()).collect()
	}

	unsafe fn data_ref(&self) -> Self::DataRef<'_> {
		self.iter().map(|lock| lock.data_ref()).collect()
	}
}

unsafe impl<T: Lockable> Lockable for Vec<T> {
	// There's no reason why I'd ever want to extend a list of lock guards
	type Guard<'g>
		= Box<[T::Guard<'g>]>
	where
		Self: 'g;

	type DataMut<'a>
		= Box<[T::DataMut<'a>]>
	where
		Self: 'a;

	fn get_ptrs<'a>(&'a self, ptrs: &mut Vec<&'a dyn RawLock>) {
		for lock in self {
			lock.get_ptrs(ptrs);
		}
	}

	unsafe fn guard(&self) -> Self::Guard<'_> {
		self.iter().map(|lock| lock.guard()).collect()
	}

	unsafe fn data_mut(&self) -> Self::DataMut<'_> {
		self.iter().map(|lock| lock.data_mut()).collect()
	}
}

unsafe impl<T: Sharable> Sharable for Vec<T> {
	type ReadGuard<'g>
		= Box<[T::ReadGuard<'g>]>
	where
		Self: 'g;

	type DataRef<'a>
		= Box<[T::DataRef<'a>]>
	where
		Self: 'a;

	unsafe fn read_guard(&self) -> Self::ReadGuard<'_> {
		self.iter().map(|lock| lock.read_guard()).collect()
	}

	unsafe fn data_ref(&self) -> Self::DataRef<'_> {
		self.iter().map(|lock| lock.data_ref()).collect()
	}
}

unsafe impl<T: OwnedLockable> OwnedLockable for Box<[T]> {}

// I'd make a generic impl<T: Lockable, I: IntoIterator<Item=T>> Lockable for I
// but I think that'd require sealing up this trait

impl<T: LockableGetMut + 'static> LockableGetMut for Vec<T> {
	type Inner<'a>
		= Box<[T::Inner<'a>]>
	where
		Self: 'a;

	fn get_mut(&mut self) -> Self::Inner<'_> {
		self.iter_mut().map(LockableGetMut::get_mut).collect()
	}
}

impl<T: LockableIntoInner> LockableIntoInner for Vec<T> {
	type Inner = Box<[T::Inner]>;

	fn into_inner(self) -> Self::Inner {
		self.into_iter()
			.map(LockableIntoInner::into_inner)
			.collect()
	}
}

unsafe impl<T: OwnedLockable> OwnedLockable for Vec<T> {}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{LockCollection, Mutex, RwLock, ThreadKey};

	#[test]
	fn mut_ref_get_ptrs() {
		let mut rwlock = RwLock::new(5);
		let mutref = &mut rwlock;
		let mut lock_ptrs = Vec::new();
		mutref.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 1);
		assert!(std::ptr::addr_eq(lock_ptrs[0], mutref));
	}

	#[test]
	fn array_get_ptrs_empty() {
		let locks: [Mutex<()>; 0] = [];
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert!(lock_ptrs.is_empty());
	}

	#[test]
	fn array_get_ptrs_length_one() {
		let locks: [Mutex<i32>; 1] = [Mutex::new(1)];
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 1);
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[0], locks[0].raw())) }
	}

	#[test]
	fn array_get_ptrs_length_two() {
		let locks: [Mutex<i32>; 2] = [Mutex::new(1), Mutex::new(2)];
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 2);
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[0], locks[0].raw())) }
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[1], locks[1].raw())) }
	}

	#[test]
	fn vec_get_ptrs_empty() {
		let locks: Vec<Mutex<()>> = Vec::new();
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert!(lock_ptrs.is_empty());
	}

	#[test]
	fn vec_get_ptrs_length_one() {
		let locks: Vec<Mutex<i32>> = vec![Mutex::new(1)];
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 1);
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[0], locks[0].raw())) }
	}

	#[test]
	fn vec_get_ptrs_length_two() {
		let locks: Vec<Mutex<i32>> = vec![Mutex::new(1), Mutex::new(2)];
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 2);
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[0], locks[0].raw())) }
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[1], locks[1].raw())) }
	}

	#[test]
	fn vec_as_mut() {
		let mut locks: Vec<Mutex<i32>> = vec![Mutex::new(1), Mutex::new(2)];
		let lock_ptrs = LockableGetMut::get_mut(&mut locks);

		assert_eq!(lock_ptrs.len(), 2);
		assert_eq!(*lock_ptrs[0], 1);
		assert_eq!(*lock_ptrs[1], 2);
	}

	#[test]
	fn vec_into_inner() {
		let locks: Vec<Mutex<i32>> = vec![Mutex::new(1), Mutex::new(2)];
		let lock_ptrs = LockableIntoInner::into_inner(locks);

		assert_eq!(lock_ptrs.len(), 2);
		assert_eq!(lock_ptrs[0], 1);
		assert_eq!(lock_ptrs[1], 2);
	}

	#[test]
	fn vec_guard_ref() {
		let key = ThreadKey::get().unwrap();
		let locks = vec![RwLock::new(1), RwLock::new(2)];
		let collection = LockCollection::new(locks);

		let mut guard = collection.lock(key);
		assert_eq!(*guard[0], 1);
		assert_eq!(*guard[1], 2);
		*guard[0] = 3;

		let key = LockCollection::<Vec<RwLock<_>>>::unlock(guard);
		let guard = collection.read(key);
		assert_eq!(*guard[0], 3);
		assert_eq!(*guard[1], 2);
	}

	#[test]
	fn vec_data_mut() {
		let mut key = ThreadKey::get().unwrap();
		let mutexes = vec![Mutex::new(1), Mutex::new(2)];
		let collection = LockCollection::new(mutexes);
		collection.scoped_lock(&mut key, |guard| {
			assert_eq!(*guard[0], 1);
			assert_eq!(*guard[1], 2);
			*guard[0] = 3;
		});

		collection.scoped_lock(&mut key, |guard| {
			assert_eq!(*guard[0], 3);
			assert_eq!(*guard[1], 2);
		})
	}

	#[test]
	fn vec_data_ref() {
		let mut key = ThreadKey::get().unwrap();
		let mutexes = vec![RwLock::new(1), RwLock::new(2)];
		let collection = LockCollection::new(mutexes);
		collection.scoped_lock(&mut key, |guard| {
			assert_eq!(*guard[0], 1);
			assert_eq!(*guard[1], 2);
			*guard[0] = 3;
		});

		collection.scoped_read(&mut key, |guard| {
			assert_eq!(*guard[0], 3);
			assert_eq!(*guard[1], 2);
		})
	}

	#[test]
	fn box_get_ptrs_empty() {
		let locks: Box<[Mutex<()>]> = Box::from([]);
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert!(lock_ptrs.is_empty());
	}

	#[test]
	fn box_get_ptrs_length_one() {
		let locks: Box<[Mutex<i32>]> = vec![Mutex::new(1)].into_boxed_slice();
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 1);
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[0], locks[0].raw())) }
	}

	#[test]
	fn box_get_ptrs_length_two() {
		let locks: Box<[Mutex<i32>]> = vec![Mutex::new(1), Mutex::new(2)].into_boxed_slice();
		let mut lock_ptrs = Vec::new();
		locks.get_ptrs(&mut lock_ptrs);

		assert_eq!(lock_ptrs.len(), 2);
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[0], locks[0].raw())) }
		unsafe { assert!(std::ptr::addr_eq(lock_ptrs[1], locks[1].raw())) }
	}

	#[test]
	fn box_as_mut() {
		let mut locks: Box<[Mutex<i32>]> = vec![Mutex::new(1), Mutex::new(2)].into_boxed_slice();
		let lock_ptrs = LockableGetMut::get_mut(&mut locks);

		assert_eq!(lock_ptrs.len(), 2);
		assert_eq!(*lock_ptrs[0], 1);
		assert_eq!(*lock_ptrs[1], 2);
	}

	#[test]
	fn box_guard_mut() {
		let key = ThreadKey::get().unwrap();
		let x = [Mutex::new(1), Mutex::new(2)];
		let collection: LockCollection<Box<[Mutex<_>]>> = LockCollection::new(Box::new(x));

		let mut guard = collection.lock(key);
		assert_eq!(*guard[0], 1);
		assert_eq!(*guard[1], 2);
		*guard[0] = 3;

		let key = LockCollection::<Box<[Mutex<_>]>>::unlock(guard);
		let guard = collection.lock(key);
		assert_eq!(*guard[0], 3);
		assert_eq!(*guard[1], 2);
	}

	#[test]
	fn box_data_mut() {
		let mut key = ThreadKey::get().unwrap();
		let mutexes = vec![Mutex::new(1), Mutex::new(2)].into_boxed_slice();
		let collection = LockCollection::new(mutexes);
		collection.scoped_lock(&mut key, |guard| {
			assert_eq!(*guard[0], 1);
			assert_eq!(*guard[1], 2);
			*guard[0] = 3;
		});

		collection.scoped_lock(&mut key, |guard| {
			assert_eq!(*guard[0], 3);
			assert_eq!(*guard[1], 2);
		});
	}

	#[test]
	fn box_guard_ref() {
		let key = ThreadKey::get().unwrap();
		let locks = [RwLock::new(1), RwLock::new(2)];
		let collection: LockCollection<Box<[RwLock<_>]>> = LockCollection::new(Box::new(locks));

		let mut guard = collection.lock(key);
		assert_eq!(*guard[0], 1);
		assert_eq!(*guard[1], 2);
		*guard[0] = 3;

		let key = LockCollection::<Box<[RwLock<_>]>>::unlock(guard);
		let guard = collection.read(key);
		assert_eq!(*guard[0], 3);
		assert_eq!(*guard[1], 2);
	}

	#[test]
	fn box_data_ref() {
		let mut key = ThreadKey::get().unwrap();
		let mutexes = vec![RwLock::new(1), RwLock::new(2)].into_boxed_slice();
		let collection = LockCollection::new(mutexes);
		collection.scoped_lock(&mut key, |guard| {
			assert_eq!(*guard[0], 1);
			assert_eq!(*guard[1], 2);
			*guard[0] = 3;
		});

		collection.scoped_read(&mut key, |guard| {
			assert_eq!(*guard[0], 3);
			assert_eq!(*guard[1], 2);
		});
	}
}