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
//! A concurrent, unordered collection where each element has an internally generated ID and a
//! read-write lock.
//!
//! A store has O(1) time complexity for insertion, removal and lookups, although memory
//! allocations triggered by insertion may cause a performance spike.
//!
//! # Example
//!
//! ```
//! # use read_write_store::RwStore;
//! # use read_write_store::timeout::Timeout::DontBlock;
//! // Note that we only need an immutable reference to the store
//! let store = RwStore::new();
//!
//! // Inserting an element yields an ID
//! let id = store.insert(42);
//!
//! {
//! // You can read the element's value using that ID
//! let read_lock = store.read(id).unwrap();
//! assert_eq!(*read_lock, 42);
//!
//! // Concurrent reads are possible
//! assert!(store.read_with_timeout(id, DontBlock).is_ok());
//! // But reading and writing at the same time won't work
//! assert!(store.write_with_timeout(id, DontBlock).is_err());
//! }
//!
//! {
//! // You can also acquire a write lock using an ID
//! let mut write_lock = store.write(id).unwrap();
//! *write_lock = 24;
//! assert_eq!(*write_lock, 24);
//!
//! // Predictably, you cannot have multiple writers
//! assert!(store.write_with_timeout(id, DontBlock).is_err());
//! }
//!
//! // Elements can of course be removed using their ID
//! assert_eq!(store.remove(id), Some(24));
//!
//! // Now if we try to read using the ID, it will fail gracefully
//! assert!(store.read(id).is_none());
//! ```
//!
//! # Allocation behavior
//!
//! * An empty store does not require any allocation.
//! * Once an element is inserted, a fixed size block of element slots will be allocated.
//! * As more space is needed, more blocks will be allocated which tend to increase in size. All
//! allocated blocks are used alongside all previously allocated blocks; elements are never moved.
//! * All removed elements whose memory is ready for reuse are tracked, so removing an element may
//! allocate.
//!
//! # Caveats
//!
//! * When a block of elements is allocated internally, it won't be deallocated until the store is
//! dropped. This allows the element ID's to contain a pointer to the element that is valid for
//! the lifetime of the store.
//! * Every element has 8 bytes of overhead.
//! * The store itself has a non-trivial memory overhead.
//! * For performance reasons, no facilities are provided for querying the number of elements in the
//! store.
//! * A maximum of 2<sup>32</sup> - 1 elements can ever be inserted into any given store, including
//! elements that have been removed. When debug assertions are enabled, breaking this invariant
//! will panic, but when debug assertions are not enabled (i.e. in release mode) inserting more
//! than 2<sup>32</sup> - 1 elements *may cause undefined behavior*.
//!
//! # Safety
//!
//! Each element inserted into a store is given an *internal* unique ID. This begs the question,
//! what happens when an ID from one store is used with another? When debug assertions are enabled,
//! a best effort attempt is made to panic when using an ID from a different store, but when they
//! are disabled (i.e. in release mode), or if this best effort fails, this
//! *may cause undefined behavior*.
//!
//! Similarly, inserting more than 2<sup>32</sup> - 1 elements, including removed elements, into a
//! store will panic when debug assertions are enabled but *may cause undefined behavior* when they
//! are not.

#![feature(option_result_unwrap_unchecked)]
#![feature(ptr_metadata)]
#![feature(maybe_uninit_array_assume_init)]
#![feature(maybe_uninit_uninit_array)]
#![feature(option_zip)]
#![warn(missing_docs)]

use std::panic::{RefUnwindSafe, UnwindSafe};
use std::ptr::NonNull;

use bucket::Bucket;

use crate::block::Block;
pub use crate::id::*;
use crate::iter::{IntoIter, IterMut};
use crate::lock::{ReadLock, WriteLock};
use crate::rwstore_id::RwStoreId;
pub use crate::timeout::*;
use crate::timeout::{BlockResult, Timeout};
use crate::util::sync::concurrent_queue::ConcurrentQueue;
use crossbeam_utils::CachePadded;
use std::cell::UnsafeCell;
use std::mem::MaybeUninit;
use util::sync::thread;

mod block;
mod bucket;
mod header;
pub mod id;
mod id_generator;
pub mod iter;
pub mod lock;
#[cfg(all(test, loom))]
mod loom;
mod rwstore_id;
pub mod timeout;
mod util;

const BUCKET_COUNT: usize = 16;

/// A concurrent, unordered collection where each element has an internally generated ID and a
/// read-write lock. See the [module-level documentation](crate) for more.
pub struct RwStore<Element> {
    buckets: [CachePadded<Bucket<Element>>; BUCKET_COUNT],
    // Contains slots ready for insertion
    erasures: ConcurrentQueue<Erasure>,
    // A globally unique ID for the store to ensure IDs from other stores are not used with this
    // one. When debug assertions are disabled this is elided
    store_id: RwStoreId,
    // Ensures that the maximum number of inserts is respected. When debug assertions are disabled
    // this is elided
    insert_enforcer: MaximumInsertEnforcer,
}

impl<Element> RwStore<Element> {
    /// Creates a new, empty store.
    pub fn new() -> Self {
        let store_id = RwStoreId::generate();

        let buckets = unsafe {
            let mut buckets = MaybeUninit::uninit_array();

            for bucket in &mut buckets {
                *bucket = MaybeUninit::new(CachePadded::new(Bucket::new(store_id)));
            }

            MaybeUninit::array_assume_init(buckets)
        };

        Self {
            store_id,
            buckets,
            erasures: ConcurrentQueue::new(),
            insert_enforcer: MaximumInsertEnforcer::new(),
        }
    }

    /// Inserts an element into the store, returning it's generated unique ID. The returned ID can
    /// be used to subsequently read, modify or remove the element.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// ```
    ///
    /// # Safety
    ///
    /// This should not be called more than 2<sup>32</sup> - 1 times on any given store. When debug
    /// assertions are enabled, doing so will panic, but when they are disabled (i.e. in release
    /// mode), doing so *may cause undefined behavior*.
    pub fn insert(&self, element: Element) -> Id {
        self.insert_enforcer.assert_may_insert();

        let (bucket_id, bucket, slot_address) = if let Some(erasure) = self.erasures.pop() {
            let bucket_id = erasure.bucket_id;
            let bucket = &self.buckets[bucket_id as usize];
            (erasure.bucket_id, bucket, erasure.slot_address)
        } else {
            let bucket_id = self.arbitrary_bucket_id();
            let bucket = &self.buckets[bucket_id as usize];
            let slot_address = bucket.next_insert_location();
            (bucket_id, bucket, slot_address)
        };

        let id = bucket.id_generator.next();

        unsafe { Block::insert(id, bucket_id, slot_address, element, self.store_id) }
    }

    /// Removes an element from the store using its ID if it has not already been removed. Returns
    /// the element if it was present.
    ///
    /// If a read or write lock is held on the element, this will block until it is released.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// assert_eq!(store.remove(id), Some(42));
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn remove(&self, id: Id) -> Option<Element> {
        self.remove_with_timeout(id, Timeout::BlockIndefinitely)
            .unwrap()
    }

    /// Removes an element from the store using its ID if it has not already been removed. Returns
    /// the element if it was present.
    ///
    /// If a read or write lock is held on the element, this will block until it is released or the
    /// given timeout expires.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// # use read_write_store::timeout::Timeout::DontBlock;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// let read_lock = store.read(id);
    /// assert!(store.remove_with_timeout(id, DontBlock).is_err());
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn remove_with_timeout(&self, id: Id, timeout: Timeout) -> BlockResult<Option<Element>> {
        self.assert_native_id(id);

        unsafe {
            if let Some(value) = Block::<Element>::remove(id, timeout)? {
                self.push_erasure(id);
                Ok(Some(value))
            } else {
                Ok(None)
            }
        }
    }

    /// Removes an element from the store directly using a write lock held over the element. This is
    /// likely more efficient than unlocking and removing the element, and is guaranteed to succeed
    /// atomically, without blocking.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// let write_lock = store.write(id).unwrap();
    /// assert_eq!(store.remove_locked(write_lock), 42);
    /// ```
    ///
    /// # Safety
    ///
    /// The given lock must have been acquired from one of the locking methods on this store. Using
    /// a lock from another store will panic when debug assertions are enabled, but *may cause
    /// undefined behavior* when they are disabled (i.e. in release mode).
    pub fn remove_locked(&self, lock: WriteLock<Element>) -> Element {
        let id = lock.forget();

        self.assert_native_id(id);

        let element = unsafe { Block::<Element>::remove_locked(id) };
        self.push_erasure(id);

        element
    }

    fn push_erasure(&self, id: Id) {
        self.erasures.push(Erasure {
            bucket_id: id.bucket_id(),
            slot_address: id.slot(),
        });
    }

    /// Acquires a read lock on an element given its ID, if it is still present in the store.
    ///
    /// If a write lock is held on the element, this will block until it is released.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// let read_lock = store.read(id).unwrap();
    /// assert_eq!(*read_lock, 42);
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn read(&self, id: Id) -> Option<ReadLock<Element>> {
        self.read_with_timeout(id, Timeout::BlockIndefinitely)
            .unwrap()
    }

    /// Acquires a read lock on an element given its ID, if it is still present in the store.
    ///
    /// If a write lock is held on the element, this will block until it is released or the given
    /// timeout expires.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// # use read_write_store::timeout::Timeout::DontBlock;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// let write_lock = store.write(id).unwrap();
    /// assert!(store.read_with_timeout(id, DontBlock).is_err());
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn read_with_timeout(
        &self,
        id: Id,
        timeout: Timeout,
    ) -> BlockResult<Option<ReadLock<Element>>> {
        self.assert_native_id(id);

        unsafe {
            if Block::<Element>::lock_read(id, timeout)? {
                let lock = ReadLock::new(id);
                Ok(Some(lock))
            } else {
                Ok(None)
            }
        }
    }

    /// Acquires a write lock on an element given its ID, if it is still present in the store.
    ///
    /// If a read or write lock is held on the element, this will block until it is released.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// let mut write_lock = store.write(id).unwrap();
    /// *write_lock = 24;
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn write(&self, id: Id) -> Option<WriteLock<Element>> {
        self.write_with_timeout(id, Timeout::BlockIndefinitely)
            .unwrap()
    }

    /// Acquires a write lock on an element given its ID, if it is still present in the store.
    ///
    /// If a read or write lock is held on the element, this will block until it is released or the
    /// given timeout expires.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// # use read_write_store::timeout::Timeout::DontBlock;
    /// let store = RwStore::new();
    /// let id = store.insert(42);
    /// let read_lock = store.read(id).unwrap();
    /// assert!(store.write_with_timeout(id, DontBlock).is_err());
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn write_with_timeout(
        &self,
        id: Id,
        timeout: Timeout,
    ) -> BlockResult<Option<WriteLock<Element>>> {
        self.assert_native_id(id);

        unsafe {
            if Block::<Element>::lock_write(id, timeout)? {
                let lock = WriteLock::new(id);
                Ok(Some(lock))
            } else {
                Ok(None)
            }
        }
    }

    /// Directly obtains a mutable reference to an element given its ID, if it is still present in
    /// the store.
    ///
    /// Because a mutable reference is held over the store, this can avoid the overhead of locking.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let mut store = RwStore::new();
    /// let id = store.insert(42);
    /// assert_eq!(store.get_mut(id), Some(&mut 42));
    /// ```
    ///
    /// # Safety
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub fn get_mut(&mut self, id: Id) -> Option<&mut Element> {
        self.assert_native_id(id);

        unsafe { Block::<Element>::get_exclusive(id).map(|mut ptr| ptr.as_mut()) }
    }

    /// Directly obtains a mutable reference to an element given its ID, assuming it is still
    /// present in the store.
    ///
    /// Because a mutable reference is held over the store, this can avoid the overhead of locking.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let mut store = RwStore::new();
    /// let id = store.insert(42);
    ///
    /// unsafe {
    ///     assert_eq!(store.get_mut_unchecked(id), &mut 42);
    /// }
    /// ```
    ///
    /// # Safety
    ///
    /// If the element whose ID is passed to this method has been removed, then this *may cause
    /// undefined behavior*.
    ///
    /// The given ID must have been created by this store, see the
    /// [struct-level documentation](RwStore).
    pub unsafe fn get_mut_unchecked(&mut self, id: Id) -> &mut Element {
        self.assert_native_id(id);
        Block::<Element>::get_unchecked(id).as_mut()
    }

    /// Creates an iterator that visits each element still present in the store, yielding its ID and
    /// a mutable reference to it.
    ///
    /// The order in which this iterator traverses elements is unspecified.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let mut store = RwStore::new();
    /// let id = store.insert(42);
    /// let mut iter = store.iter_mut();
    /// assert_eq!(iter.next().unwrap().1, &mut 42);
    /// assert!(iter.next().is_none());
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<Element> {
        IterMut::new(self)
    }

    /// Determines the touched and allocated capacity for this store, and returns them in that
    /// order. These should be regarded as hints, if the store is being accessed concurrently the
    /// actual capacity values may be larger (but not smaller) than those returned by this method.
    ///
    /// The touched capacity is equal to the largest number of elements ever contained in this store
    /// at the same time. The allocated capacity is the total number of element slots allocated for
    /// use with this store. Neither of these numbers ever decrease.
    ///
    /// # Example
    ///
    /// ```
    /// # use read_write_store::RwStore;
    /// let store = RwStore::new();
    /// assert_eq!(store.capacity(), (0, 0));
    ///
    /// store.insert(42);
    /// let (touched, allocated) = store.capacity();
    /// assert_eq!(touched, 1);
    /// assert!(allocated >= 1);
    /// ```
    pub fn capacity(&self) -> (u32, u32) {
        let (mut total_touched, mut total_allocated) = (0, 0);

        for bucket in &self.buckets {
            let (touched, allocated) = bucket.capacity();
            total_touched += touched;
            total_allocated += allocated;
        }

        (total_touched, total_allocated)
    }

    /// Generates a pseudo-random bucket ID for element insertion. This will return different
    /// results on different threads and invocations.
    fn arbitrary_bucket_id(&self) -> u32 {
        // Here we use a linear congruential generator using thread local state

        thread_local! {
            static STATE: UnsafeCell<u32> = UnsafeCell::new(thread::current_thread_hash() as u32);
        }

        STATE.with(|state| unsafe {
            const MULTIPLIER: u32 = 1103515245;
            const CONSTANT: u32 = 12345;

            let state = &mut *state.get();
            *state = state.wrapping_mul(MULTIPLIER).wrapping_add(CONSTANT);
            *state % BUCKET_COUNT as u32
        })
    }

    fn assert_native_id(&self, id: Id) {
        debug_assert!(
            self.store_id == id.store_id(),
            "attempted to use an ID created with a different store"
        )
    }
}

impl<Element> Default for RwStore<Element> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Element> IntoIterator for RwStore<Element> {
    type Item = (Id, Element);
    type IntoIter = IntoIter<Element>;

    /// Creates a consuming iterator that visits each element still present in the store, yielding its
    /// ID and value.
    ///
    /// The order in which this iterator traverses elements is unspecified.
    fn into_iter(self) -> IntoIter<Element> {
        IntoIter::new(self)
    }
}

unsafe impl<Element: Send + Sync> Sync for RwStore<Element> {}

unsafe impl<Element: Send> Send for RwStore<Element> {}

impl<Element: UnwindSafe> UnwindSafe for RwStore<Element> {}

impl<Element: RefUnwindSafe> RefUnwindSafe for RwStore<Element> {}

#[cfg(debug_assertions)]
struct MaximumInsertEnforcer {
    inserts_remaining: crate::util::sync::atomic::AtomicU32,
}

#[cfg(debug_assertions)]
impl MaximumInsertEnforcer {
    pub fn new() -> Self {
        Self {
            inserts_remaining: crate::util::sync::atomic::AtomicU32::new(u32::MAX - 1),
        }
    }

    fn assert_may_insert(&self) {
        use crate::util::sync::atomic::Ordering;

        let count = self.inserts_remaining.load(Ordering::Acquire);

        if count == 0 {
            panic!("too many elements have been inserted into this store");
        }

        let result = self.inserts_remaining.compare_exchange_weak(
            count,
            count - 1,
            Ordering::Release,
            Ordering::Relaxed,
        );

        if result.is_err() {
            self.assert_may_insert();
        }
    }
}

#[cfg(not(debug_assertions))]
struct MaximumInsertEnforcer {
    _private: (),
}

#[cfg(not(debug_assertions))]
impl MaximumInsertEnforcer {
    pub fn new() -> Self {
        Self { _private: () }
    }

    fn assert_may_insert(&self) {}
}

struct Erasure {
    bucket_id: u32,
    slot_address: NonNull<()>,
}

#[cfg(test)]
mod test {
    use std::ops::Deref;
    use std::panic::{RefUnwindSafe, UnwindSafe};

    use crate::Timeout::DontBlock;
    use crate::{BlockResult, Id, RwStore};

    #[test]
    fn insert_creates_disparate_ids() {
        let store = RwStore::new();
        let id_a = store.insert(42);
        let id_b = store.insert(42);

        assert_ne!(
            (id_a.ordinal(), id_a.bucket_id()),
            (id_b.ordinal(), id_b.bucket_id())
        );
        assert_ne!(id_a.slot::<()>(), id_b.slot());
    }

    #[test]
    fn insert_reuses_space_after_removal() {
        let store = RwStore::new();

        let id_a = store.insert(42);
        store.remove(id_a).unwrap();

        let id_b = store.insert(42);

        assert_eq!(id_a.slot::<()>(), id_b.slot());
    }

    #[test]
    fn insert_reuses_space_after_locked_removal() {
        let store = RwStore::new();

        let id_a = store.insert(42);
        store.remove_locked(store.write(id_a).unwrap());

        let id_b = store.insert(42);

        assert_eq!(id_a.slot::<()>(), id_b.slot());
    }

    #[test]
    fn insert_doesnt_reuse_id_ordinals() {
        let store = RwStore::new();

        let id_a = store.insert(42);
        store.remove(id_a).unwrap();

        let id_b = store.insert(42);

        assert_ne!(id_a.ordinal(), id_b.ordinal());
    }

    #[test]
    fn remove_returns_the_element() {
        gen_remove_returns_the_element(|store, id| store.remove(id));
    }

    #[test]
    fn remove_returns_none_after_removal() {
        gen_remove_returns_none_after_removal(|store, id| store.remove(id));
    }

    #[test]
    fn remove_with_timeout_returns_the_element() {
        gen_remove_returns_the_element(|store, id| {
            store.remove_with_timeout(id, DontBlock).unwrap()
        });
    }

    #[test]
    fn remove_with_timeout_returns_none_after_removal() {
        gen_remove_returns_none_after_removal(|store, id| {
            store.remove_with_timeout(id, DontBlock).unwrap()
        });
    }

    #[test]
    fn remove_with_timeout_fails_when_read_locked() {
        let store = RwStore::new();
        let id = store.insert(42);

        let _lock = store.read(id).unwrap();

        assert!(store.remove_with_timeout(id, DontBlock).is_err());
    }

    #[test]
    fn remove_with_timeout_fails_when_write_locked() {
        let store = RwStore::new();
        let id = store.insert(42);

        let _lock = store.write(id).unwrap();

        assert!(store.remove_with_timeout(id, DontBlock).is_err());
    }

    fn gen_remove_returns_the_element(remover: impl Fn(&RwStore<u32>, Id) -> Option<u32>) {
        let store = RwStore::new();
        let id = store.insert(42);

        assert_eq!(remover(&store, id), Some(42));
    }

    fn gen_remove_returns_none_after_removal(remover: impl Fn(&RwStore<u32>, Id) -> Option<u32>) {
        let store = RwStore::new();
        let id = store.insert(42);
        store.remove(id);

        assert_eq!(remover(&store, id), None);
    }

    #[test]
    fn remove_locked_returns_the_element() {
        let store = RwStore::new();
        let id = store.insert(42);

        let lock = store.write(id).unwrap();

        assert_eq!(store.remove_locked(lock), 42);
    }

    #[test]
    fn remove_locked_removes_the_element() {
        let store = RwStore::new();
        let id = store.insert(42);

        let lock = store.write(id).unwrap();
        store.remove_locked(lock);

        assert!(store.read(id).is_none());
    }

    #[test]
    fn read_references_the_element() {
        access_references_the_element::<ReadOperation>();
    }

    #[test]
    fn write_references_the_element() {
        access_references_the_element::<WriteOperation>();
    }

    #[test]
    fn read_with_timeout_references_the_element() {
        access_references_the_element::<ReadWithTimeoutOperation>();
    }

    #[test]
    fn write_with_timeout_references_the_element() {
        access_references_the_element::<WriteWithTimeoutOperation>();
    }

    fn access_references_the_element<A: AccessOperation>() {
        let store = RwStore::new();
        let id = store.insert(42);

        let lock = A::access(&store, id).unwrap().unwrap();

        assert_eq!(**lock, 42);
    }

    #[test]
    fn read_fails_returns_none_removal() {
        access_returns_none_after_removal::<ReadOperation>();
    }

    #[test]
    fn write_fails_returns_none_removal() {
        access_returns_none_after_removal::<WriteOperation>();
    }

    #[test]
    fn read_with_timeout_returns_none_after_removal() {
        access_returns_none_after_removal::<ReadWithTimeoutOperation>();
    }

    #[test]
    fn write_with_timeout_returns_none_after_removal() {
        access_returns_none_after_removal::<WriteWithTimeoutOperation>();
    }

    fn access_returns_none_after_removal<A: AccessOperation>() {
        let store = RwStore::new();
        let id = store.insert(42);

        store.remove(id).unwrap();

        assert!(A::access(&store, id).unwrap().is_none());
    }

    #[test]
    fn write_with_timeout_fails_when_write_locked() {
        access_fails_when_locked::<WriteOperation, WriteWithTimeoutOperation>();
    }

    #[test]
    fn write_with_timeout_fails_when_read_locked() {
        access_fails_when_locked::<ReadOperation, WriteWithTimeoutOperation>();
    }

    #[test]
    fn read_with_timeout_fails_when_write_locked() {
        access_fails_when_locked::<WriteOperation, ReadWithTimeoutOperation>();
    }

    fn access_fails_when_locked<Lock: AccessOperation, A: AccessOperation>() {
        let store = RwStore::new();
        let id = store.insert(42);

        let _lock = Lock::access(&store, id);

        assert!(A::access(&store, id).is_err());
    }

    #[test]
    fn read_succeeds_when_read_locked() {
        access_succeeds_when_locked::<ReadOperation, ReadOperation>();
    }

    #[test]
    fn read_with_timeout_succeeds_when_read_locked() {
        access_succeeds_when_locked::<ReadWithTimeoutOperation, ReadOperation>();
    }

    fn access_succeeds_when_locked<Lock: AccessOperation, A: AccessOperation>() {
        let store = RwStore::new();
        let id = store.insert(42);

        let _lock = Lock::access(&store, id);

        assert!(A::access(&store, id).is_ok());
    }

    #[test]
    fn get_mut_references_the_element() {
        let mut store = RwStore::new();
        let id = store.insert(42);

        assert_eq!(store.get_mut(id), Some(&mut 42));
    }

    #[test]
    fn get_mut_returns_none_after_removal() {
        let mut store = RwStore::new();
        let id = store.insert(42);

        store.remove(id).unwrap();

        assert_eq!(store.get_mut(id), None);
    }

    #[test]
    fn get_mut_unchecked_references_the_element() {
        let mut store = RwStore::new();
        let id = store.insert(42);

        unsafe {
            assert_eq!(store.get_mut_unchecked(id), &mut 42);
        }
    }

    #[test]
    fn capacity_returns_zeroes_initially() {
        let store = RwStore::<u32>::new();
        assert_eq!(store.capacity(), (0, 0));
    }

    #[test]
    fn capacity_increases_on_first_insertion() {
        let store = RwStore::<u32>::new();
        store.insert(42);
        assert_eq!(store.capacity().0, 1);
        assert!(store.capacity().1 >= 1);
    }

    #[test]
    fn capacity_increases_on_second_insertion() {
        let store = RwStore::<u32>::new();
        store.insert(42);
        store.insert(42);
        assert_eq!(store.capacity().0, 2);
        assert!(store.capacity().1 >= 2);
    }

    #[test]
    fn capacity_doesnt_decrease_after_removal() {
        let store = RwStore::<u32>::new();
        let id = store.insert(42);
        store.remove(id).unwrap();
        assert_eq!(store.capacity().0, 1);
        assert!(store.capacity().1 >= 1);
    }

    #[test]
    fn capacity_doesnt_increase_on_insertion_after_removal() {
        let store = RwStore::<u32>::new();
        let id = store.insert(42);
        store.remove(id).unwrap();
        store.insert(42);
        assert_eq!(store.capacity().0, 1);
        assert!(store.capacity().1 >= 1);
    }

    #[test]
    fn capacity_doesnt_increase_on_insertion_after_locked_removal() {
        let store = RwStore::<u32>::new();
        let id = store.insert(42);
        store.remove_locked(store.write(id).unwrap());
        store.insert(42);
        assert_eq!(store.capacity().0, 1);
        assert!(store.capacity().1 >= 1);
    }

    #[test]
    fn implements_sync() {
        let store = RwStore::<u32>::new();
        &store as &dyn Sync;
    }

    #[test]
    fn implements_send() {
        let store = RwStore::<u32>::new();
        &store as &dyn Send;
    }

    #[test]
    fn implements_unwind_safe() {
        let store = RwStore::<u32>::new();
        &store as &dyn UnwindSafe;
    }

    #[test]
    fn implements_ref_unwind_safe() {
        let store = RwStore::<u32>::new();
        &store as &dyn RefUnwindSafe;
    }

    trait AccessOperation {
        fn access<'a>(
            store: &'a RwStore<u32>,
            id: Id,
        ) -> BlockResult<Option<Box<dyn Deref<Target = u32> + 'a>>>;
    }

    struct ReadOperation;

    impl AccessOperation for ReadOperation {
        fn access<'a>(
            store: &'a RwStore<u32>,
            id: Id,
        ) -> BlockResult<Option<Box<dyn Deref<Target = u32> + 'a>>> {
            let result = store
                .read(id)
                .map(|lock| Box::new(lock) as Box<dyn Deref<Target = u32>>);

            Ok(result)
        }
    }

    struct WriteOperation;

    impl AccessOperation for WriteOperation {
        fn access<'a>(
            store: &'a RwStore<u32>,
            id: Id,
        ) -> BlockResult<Option<Box<dyn Deref<Target = u32> + 'a>>> {
            let result = store
                .write(id)
                .map(|lock| Box::new(lock) as Box<dyn Deref<Target = u32>>);

            Ok(result)
        }
    }

    struct ReadWithTimeoutOperation;

    impl AccessOperation for ReadWithTimeoutOperation {
        fn access<'a>(
            store: &'a RwStore<u32>,
            id: Id,
        ) -> BlockResult<Option<Box<dyn Deref<Target = u32> + 'a>>> {
            store
                .read_with_timeout(id, DontBlock)
                .map(|result| result.map(|lock| Box::new(lock) as Box<dyn Deref<Target = u32>>))
        }
    }

    struct WriteWithTimeoutOperation;

    impl AccessOperation for WriteWithTimeoutOperation {
        fn access<'a>(
            store: &'a RwStore<u32>,
            id: Id,
        ) -> BlockResult<Option<Box<dyn Deref<Target = u32> + 'a>>> {
            store
                .write_with_timeout(id, DontBlock)
                .map(|result| result.map(|lock| Box::new(lock) as Box<dyn Deref<Target = u32>>))
        }
    }
}