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
//! A simple object pool.
//!
//! `ObjPool<T>` is basically just a `Vec<Option<T>>`, which allows you to:
//!
//! * Insert an object (reuse an existing `None` element, or append to the end) and get an `ObjId`
//!   in return.
//! * Remove object with a specified `ObjId`.
//! * Access object with a specified `ObjId`.
//! * Convert `ObjId` to index and back for specified `ObjPool`.
//!
//! # Limitations:
//!
//! * `ObjId` is always 32-bit long.
//!
//! # Examples
//!
//! Some data structures built using `ObjPool<T>`:
//!
//! * [Doubly linked list](https://github.com/artemshein/obj-pool/blob/master/examples/linked_list.rs)
//! * [Splay tree](https://github.com/artemshein/obj-pool/blob/master/examples/splay_tree.rs)
use std::{
    fmt, iter, mem,
    num::{NonZeroU32, ParseIntError},
    ops::{Index, IndexMut},
    ptr,
    str::FromStr,
    vec,
};

use std::ops::Deref;
use std::slice;
use unreachable::unreachable;

#[cfg(feature = "serde_support")]
use serde::{Deserialize, Serialize};

mod par;
pub use par::*;

/// A slot, which is either vacant or occupied.
///
/// Vacant slots in object pool are linked together into a singly linked list. This allows the object pool to
/// efficiently find a vacant slot before inserting a new object, or reclaiming a slot after
/// removing an object.
#[derive(Clone)]
enum Slot<T> {
    /// Vacant slot, containing index to the next slot in the linked list.
    Vacant(u32),

    /// Occupied slot, containing a value.
    Occupied(T),
}

/// An id of the object in an `ObjPool`.
///
/// In release it is basically just an index in the underlying vector, but in debug it's an `index` +
/// `ObjPool`-specific `offset`. This is made to be able to check `ObjId` if it's from the same
/// `ObjPool` we are trying to get an object from.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct ObjId(pub NonZeroU32);

impl ObjId {
    pub fn from_index(index: u32) -> Self {
        Self(NonZeroU32::new(index + 1).expect("invalid index"))
    }

    pub const fn into_index(self) -> u32 {
        self.0.get() - 1
    }
}

impl std::fmt::Display for ObjId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.0.fmt(f)
    }
}

impl FromStr for ObjId {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(ObjId(s.parse::<NonZeroU32>()?))
    }
}

impl Deref for ObjId {
    type Target = NonZeroU32;

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

impl From<NonZeroU32> for ObjId {
    fn from(v: NonZeroU32) -> ObjId {
        ObjId(v)
    }
}

/// An object pool.
///
/// `ObjPool<T>` holds an array of slots for storing objects.
/// Every slot is always in one of two states: occupied or vacant.
///
/// Essentially, this is equivalent to `Vec<Option<T>>`.
///
/// # Insert and remove
///
/// When inserting a new object into object pool, a vacant slot is found and then the object is placed
/// into the slot. If there are no vacant slots, the array is reallocated with bigger capacity.
/// The cost of insertion is amortized `O(1)`.
///
/// When removing an object, the slot containing it is marked as vacant and the object is returned.
/// The cost of removal is `O(1)`.
///
/// ```
/// use obj_pool::ObjPool;
///
/// let mut obj_pool = ObjPool::new();
/// let a = obj_pool.insert(10);
/// assert_eq!(a.into_index(), 0);
/// let b = obj_pool.insert(20);
/// assert_eq!(b.into_index(), 1);
///
/// assert_ne!(a, b); // ids are not the same
///
/// assert_eq!(obj_pool.remove(a), Some(10));
/// assert_eq!(obj_pool.get(a), None); // there is no object with this `ObjId` anymore
///
/// assert_eq!(obj_pool.insert(30), a); // slot is reused, got the same `ObjId`
/// ```
///
/// # Indexing
///
/// You can also access objects in an object pool by `ObjId`.
/// However, accessing an object with invalid `ObjId` will result in panic.
///
/// ```
/// use obj_pool::ObjPool;
///
/// let mut obj_pool = ObjPool::new();
/// let a = obj_pool.insert(10);
/// let b = obj_pool.insert(20);
///
/// assert_eq!(obj_pool[a], 10);
/// assert_eq!(obj_pool[b], 20);
///
/// obj_pool[a] += obj_pool[b];
/// assert_eq!(obj_pool[a], 30);
/// ```
///
/// To access slots without fear of panicking, use `get` and `get_mut`, which return `Option`s.
pub struct ObjPool<T> {
    /// Slots in which objects are stored.
    slots: Vec<Slot<T>>,

    /// Number of occupied slots in the object pool.
    len: u32,

    /// Index of the first vacant slot in the linked list.
    head: u32,
}

impl<T> AsRef<ObjPool<T>> for ObjPool<T> {
    fn as_ref(&self) -> &ObjPool<T> {
        self
    }
}

impl<T> AsMut<ObjPool<T>> for ObjPool<T> {
    fn as_mut(&mut self) -> &mut ObjPool<T> {
        self
    }
}

impl<T> ObjPool<T> {
    /// Constructs a new, empty object pool.
    ///
    /// The object pool will not allocate until objects are inserted into it.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool: ObjPool<i32> = ObjPool::new();
    /// ```
    #[inline]
    pub const fn new() -> Self {
        ObjPool {
            slots: Vec::new(),
            len: 0,
            head: u32::MAX,
        }
    }

    /// Get an index in the `ObjPool` for the given `ObjId`.
    #[inline]
    pub const fn obj_id_to_index(obj_id: ObjId) -> u32 {
        obj_id.into_index()
    }

    /// Make an `ObjId` from an index in this `ObjPool`.
    #[inline]
    pub fn index_to_obj_id(index: u32) -> ObjId {
        ObjId::from_index(index)
    }

    /// Constructs a new, empty object pool with the specified capacity (number of slots).
    ///
    /// The object pool will be able to hold exactly `capacity` objects without reallocating.
    /// If `capacity` is 0, the object pool will not allocate.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::with_capacity(10);
    ///
    /// assert_eq!(obj_pool.len(), 0);
    /// assert_eq!(obj_pool.capacity(), 10);
    ///
    /// // These inserts are done without reallocating...
    /// for i in 0..10 {
    ///     obj_pool.insert(i);
    /// }
    /// assert_eq!(obj_pool.capacity(), 10);
    ///
    /// // ... but this one will reallocate.
    /// obj_pool.insert(11);
    /// assert!(obj_pool.capacity() > 10);
    /// ```
    #[inline]
    pub fn with_capacity(cap: usize) -> Self {
        ObjPool {
            slots: Vec::with_capacity(cap),
            len: 0,
            head: u32::MAX,
        }
    }

    /// Returns the number of slots in the object pool.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let obj_pool: ObjPool<i32> = ObjPool::with_capacity(10);
    /// assert_eq!(obj_pool.capacity(), 10);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.slots.capacity()
    }

    /// Returns the number of occupied slots in the object pool.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// assert_eq!(obj_pool.len(), 0);
    ///
    /// for i in 0..10 {
    ///     obj_pool.insert(());
    ///     assert_eq!(obj_pool.len(), i + 1);
    /// }
    /// ```
    #[inline]
    pub fn len(&self) -> u32 {
        self.len
    }

    /// Returns `true` if all slots are vacant.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// assert!(obj_pool.is_empty());
    ///
    /// obj_pool.insert(1);
    /// assert!(!obj_pool.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the `ObjId` of the next inserted object if no other
    /// mutating calls take place in between.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    ///
    /// let a = obj_pool.next_vacant();
    /// let b = obj_pool.insert(1);
    /// assert_eq!(a, b);
    /// let c = obj_pool.next_vacant();
    /// let d = obj_pool.insert(2);
    /// assert_eq!(c, d);
    /// ```
    #[inline]
    pub fn next_vacant(&mut self) -> ObjId {
        Self::index_to_obj_id(if self.head == u32::MAX {
            self.len
        } else {
            self.head
        })
    }

    /// Inserts an object into the object pool and returns the `ObjId` of this object.
    /// The object pool will reallocate if it's full.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    ///
    /// let a = obj_pool.insert(1);
    /// let b = obj_pool.insert(2);
    /// assert!(a != b);
    /// ```
    pub fn insert(&mut self, object: T) -> ObjId {
        self.len += 1;

        if self.head == u32::MAX {
            self.slots.push(Slot::Occupied(object));
            Self::index_to_obj_id(self.len - 1)
        } else {
            let index = self.head;
            match self.slots[index as usize] {
                Slot::Vacant(next) => {
                    self.head = next;
                    self.slots[index as usize] = Slot::Occupied(object);
                }
                Slot::Occupied(_) => unreachable!(),
            }
            Self::index_to_obj_id(index)
        }
    }

    /// Removes the object stored by `ObjId` from the object pool and returns it.
    ///
    /// `None` is returned in case the there is no object with such an `ObjId`.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// let a = obj_pool.insert("hello");
    ///
    /// assert_eq!(obj_pool.len(), 1);
    /// assert_eq!(obj_pool.remove(a), Some("hello"));
    ///
    /// assert_eq!(obj_pool.len(), 0);
    /// assert_eq!(obj_pool.remove(a), None);
    /// ```
    pub fn remove(&mut self, obj_id: ObjId) -> Option<T> {
        let index = Self::obj_id_to_index(obj_id);
        match self.slots.get_mut(index as usize) {
            None => None,
            Some(&mut Slot::Vacant(_)) => None,
            Some(slot @ &mut Slot::Occupied(_)) => {
                if let Slot::Occupied(object) = mem::replace(slot, Slot::Vacant(self.head)) {
                    self.head = index;
                    self.len -= 1;
                    Some(object)
                } else {
                    unreachable!();
                }
            }
        }
    }

    /// Clears the object pool, removing and dropping all objects it holds. Keeps the allocated memory
    /// for reuse.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// for i in 0..10 {
    ///     obj_pool.insert(i);
    /// }
    ///
    /// assert_eq!(obj_pool.len(), 10);
    /// obj_pool.clear();
    /// assert_eq!(obj_pool.len(), 0);
    /// ```
    #[inline]
    pub fn clear(&mut self) {
        self.slots.clear();
        self.len = 0;
        self.head = u32::MAX;
    }

    /// Returns a reference to the object by its `ObjId`.
    ///
    /// If object is not found with given `obj_id`, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// let obj_id = obj_pool.insert("hello");
    ///
    /// assert_eq!(obj_pool.get(obj_id), Some(&"hello"));
    /// obj_pool.remove(obj_id);
    /// assert_eq!(obj_pool.get(obj_id), None);
    /// ```
    pub fn get(&self, obj_id: ObjId) -> Option<&T> {
        let index = Self::obj_id_to_index(obj_id) as usize;
        match self.slots.get(index) {
            None => None,
            Some(&Slot::Vacant(_)) => None,
            Some(&Slot::Occupied(ref object)) => Some(object),
        }
    }

    /// Returns a mutable reference to the object by its `ObjId`.
    ///
    /// If object can't be found, `None` is returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// let obj_id = obj_pool.insert(7);
    ///
    /// assert_eq!(obj_pool.get_mut(obj_id), Some(&mut 7));
    /// *obj_pool.get_mut(obj_id).unwrap() *= 10;
    /// assert_eq!(obj_pool.get_mut(obj_id), Some(&mut 70));
    /// ```
    #[inline]
    pub fn get_mut(&mut self, obj_id: ObjId) -> Option<&mut T> {
        let index = Self::obj_id_to_index(obj_id) as usize;
        match self.slots.get_mut(index) {
            None => None,
            Some(&mut Slot::Vacant(_)) => None,
            Some(&mut Slot::Occupied(ref mut object)) => Some(object),
        }
    }

    /// Returns a reference to the object by its `ObjId`.
    ///
    /// # Safety
    ///
    /// Behavior is undefined if object can't be found.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// let obj_id = obj_pool.insert("hello");
    ///
    /// unsafe { assert_eq!(&*obj_pool.get_unchecked(obj_id), &"hello") }
    /// ```
    pub unsafe fn get_unchecked(&self, obj_id: ObjId) -> &T {
        match self.slots.get(Self::obj_id_to_index(obj_id) as usize) {
            None => unreachable(),
            Some(&Slot::Vacant(_)) => unreachable(),
            Some(&Slot::Occupied(ref object)) => object,
        }
    }

    /// Returns a mutable reference to the object by its `ObjId`.
    ///
    /// # Safety
    ///
    /// Behavior is undefined if object can't be found.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// let obj_id = obj_pool.insert("hello");
    ///
    /// unsafe { assert_eq!(&*obj_pool.get_unchecked_mut(obj_id), &"hello") }
    /// ```
    pub unsafe fn get_unchecked_mut(&mut self, obj_id: ObjId) -> &mut T {
        let index = Self::obj_id_to_index(obj_id) as usize;
        match self.slots.get_mut(index) {
            Some(&mut Slot::Vacant(_)) => unreachable(),
            Some(&mut Slot::Occupied(ref mut object)) => object,
            _ => unreachable(),
        }
    }

    /// Swaps two objects in the object pool.
    ///
    /// The two `ObjId`s are `a` and `b`.
    ///
    /// # Panics
    ///
    /// Panics if any of the `ObjId`s is invalid.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// let a = obj_pool.insert(7);
    /// let b = obj_pool.insert(8);
    ///
    /// obj_pool.swap(a, b);
    /// assert_eq!(obj_pool.get(a), Some(&8));
    /// assert_eq!(obj_pool.get(b), Some(&7));
    /// ```
    #[inline]
    pub fn swap(&mut self, a: ObjId, b: ObjId) {
        unsafe {
            let fst = self.get_mut(a).unwrap() as *mut _;
            let snd = self.get_mut(b).unwrap() as *mut _;
            if a != b {
                ptr::swap(fst, snd);
            }
        }
    }

    /// Reserves capacity for at least `additional` more objects to be inserted. The object pool may
    /// reserve more space to avoid frequent reallocations.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `u32`.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// obj_pool.insert("hello");
    ///
    /// obj_pool.reserve(10);
    /// assert!(obj_pool.capacity() >= 11);
    /// ```
    pub fn reserve(&mut self, additional: u32) {
        let vacant = self.slots.len() as u32 - self.len;
        if additional > vacant {
            self.slots.reserve((additional - vacant) as usize);
        }
    }

    /// Reserves the minimum capacity for exactly `additional` more objects to be inserted.
    ///
    /// Note that the allocator may give the object pool more space than it requests.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `u32`.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// obj_pool.insert("hello");
    ///
    /// obj_pool.reserve_exact(10);
    /// assert!(obj_pool.capacity() >= 11);
    /// ```
    pub fn reserve_exact(&mut self, additional: u32) {
        let vacant = self.slots.len() as u32 - self.len;
        if additional > vacant {
            self.slots.reserve_exact((additional - vacant) as usize);
        }
    }

    /// Returns an iterator over occupied slots.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// obj_pool.insert(1);
    /// obj_pool.insert(2);
    /// obj_pool.insert(4);
    ///
    /// let mut iterator = obj_pool.iter();
    /// assert_eq!(iterator.next(), Some((ObjPool::<usize>::index_to_obj_id(0), &1)));
    /// assert_eq!(iterator.next(), Some((ObjPool::<usize>::index_to_obj_id(1), &2)));
    /// assert_eq!(iterator.next(), Some((ObjPool::<usize>::index_to_obj_id(2), &4)));
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<T> {
        Iter {
            slots: self.slots.iter().enumerate(),
        }
    }

    /// Returns an iterator that returns mutable references to objects.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::new();
    /// obj_pool.insert("zero".to_string());
    /// obj_pool.insert("one".to_string());
    /// obj_pool.insert("two".to_string());
    ///
    /// for (obj_id, object) in obj_pool.iter_mut() {
    ///     *object = obj_id.into_index().to_string() + " " + object;
    /// }
    ///
    /// let mut iterator = obj_pool.iter();
    /// assert_eq!(iterator.next(), Some((ObjPool::<String>::index_to_obj_id(0), &"0 zero".to_string())));
    /// assert_eq!(iterator.next(), Some((ObjPool::<String>::index_to_obj_id(1), &"1 one".to_string())));
    /// assert_eq!(iterator.next(), Some((ObjPool::<String>::index_to_obj_id(2), &"2 two".to_string())));
    /// ```
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<T> {
        IterMut {
            slots: self.slots.iter_mut().enumerate(),
        }
    }

    /// Shrinks the capacity of the object pool as much as possible.
    ///
    /// It will drop down as close as possible to the length but the allocator may still inform
    /// the object pool that there is space for a few more elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use obj_pool::ObjPool;
    ///
    /// let mut obj_pool = ObjPool::with_capacity(10);
    /// obj_pool.insert("first".to_string());
    /// obj_pool.insert("second".to_string());
    /// obj_pool.insert("third".to_string());
    /// assert_eq!(obj_pool.capacity(), 10);
    /// obj_pool.shrink_to_fit();
    /// assert!(obj_pool.capacity() >= 3);
    /// ```
    pub fn shrink_to_fit(&mut self) {
        self.slots.shrink_to_fit();
    }
}

impl<T> fmt::Debug for ObjPool<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "ObjPool {{ ... }}")
    }
}

impl<T> Index<ObjId> for ObjPool<T> {
    type Output = T;

    #[inline]
    fn index(&self, obj_id: ObjId) -> &T {
        self.get(obj_id).expect("object not found")
    }
}

impl<T> IndexMut<ObjId> for ObjPool<T> {
    #[inline]
    fn index_mut(&mut self, obj_id: ObjId) -> &mut T {
        self.get_mut(obj_id).expect("object not found")
    }
}

impl<T> Default for ObjPool<T> {
    fn default() -> Self {
        ObjPool::new()
    }
}

impl<T: Clone> Clone for ObjPool<T> {
    fn clone(&self) -> Self {
        ObjPool {
            slots: self.slots.clone(),
            len: self.len,
            head: self.head,
        }
    }
}

/// An iterator over the occupied slots in a `ObjPool`.
pub struct IntoIter<T> {
    slots: iter::Enumerate<vec::IntoIter<Slot<T>>>,
}

impl<T> IntoIter<T> {
    #[inline]
    pub const fn obj_id_to_index(obj_id: ObjId) -> u32 {
        obj_id.into_index()
    }

    #[inline]
    pub fn index_to_obj_id(index: u32) -> ObjId {
        ObjId::from_index(index)
    }
}

impl<T> Iterator for IntoIter<T> {
    type Item = (ObjId, T);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while let Some((index, slot)) = self.slots.next() {
            if let Slot::Occupied(object) = slot {
                return Some((Self::index_to_obj_id(index as u32), object));
            }
        }
        None
    }
}

impl<T> IntoIterator for ObjPool<T> {
    type Item = (ObjId, T);
    type IntoIter = IntoIter<T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            slots: self.slots.into_iter().enumerate(),
        }
    }
}

impl<T> iter::FromIterator<T> for ObjPool<T> {
    fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> ObjPool<T> {
        let iter = iter.into_iter();
        let mut obj_pool = ObjPool::with_capacity(iter.size_hint().0);
        for i in iter {
            obj_pool.insert(i);
        }
        obj_pool
    }
}

impl<T> fmt::Debug for IntoIter<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "IntoIter {{ ... }}")
    }
}

/// An iterator over references to the occupied slots in a `ObjPool`.
pub struct Iter<'a, T: 'a> {
    slots: iter::Enumerate<slice::Iter<'a, Slot<T>>>,
}

impl<'a, T: 'a> Iter<'a, T> {
    #[inline]
    pub fn index_to_obj_id(index: u32) -> ObjId {
        ObjId::from_index(index)
    }
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = (ObjId, &'a T);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while let Some((index, slot)) = self.slots.next() {
            if let Slot::Occupied(ref object) = *slot {
                return Some((Self::index_to_obj_id(index as u32), object));
            }
        }
        None
    }
}

impl<'a, T> IntoIterator for &'a ObjPool<T> {
    type Item = (ObjId, &'a T);
    type IntoIter = Iter<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a, T> fmt::Debug for Iter<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Iter {{ ... }}")
    }
}

/// An iterator over mutable references to the occupied slots in a `Arena`.
pub struct IterMut<'a, T: 'a> {
    slots: iter::Enumerate<slice::IterMut<'a, Slot<T>>>,
}

impl<'a, T: 'a> IterMut<'a, T> {
    #[inline]
    pub const fn obj_id_to_index(obj_id: ObjId) -> u32 {
        obj_id.into_index()
    }

    #[inline]
    pub fn index_to_obj_id(index: u32) -> ObjId {
        ObjId::from_index(index)
    }
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = (ObjId, &'a mut T);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        while let Some((index, slot)) = self.slots.next() {
            if let Slot::Occupied(ref mut object) = *slot {
                return Some((Self::index_to_obj_id(index as u32), object));
            }
        }
        None
    }
}

impl<'a, T> IntoIterator for &'a mut ObjPool<T> {
    type Item = (ObjId, &'a mut T);
    type IntoIter = IterMut<'a, T>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

impl<'a, T> fmt::Debug for IterMut<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "IterMut {{ ... }}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new() {
        let obj_pool = ObjPool::<i32>::new();
        assert!(obj_pool.is_empty());
        assert_eq!(obj_pool.len(), 0);
        assert_eq!(obj_pool.capacity(), 0);
    }

    #[test]
    fn insert() {
        let mut obj_pool = ObjPool::new();

        for i in 0..10 {
            let a = obj_pool.insert(i * 10);
            assert_eq!(obj_pool[a], i * 10);
        }
        assert!(!obj_pool.is_empty());
        assert_eq!(obj_pool.len(), 10);
    }

    #[test]
    fn with_capacity() {
        let mut obj_pool = ObjPool::with_capacity(10);
        assert_eq!(obj_pool.capacity(), 10);

        for _ in 0..10 {
            obj_pool.insert(());
        }
        assert_eq!(obj_pool.len(), 10);
        assert_eq!(obj_pool.capacity(), 10);

        obj_pool.insert(());
        assert_eq!(obj_pool.len(), 11);
        assert!(obj_pool.capacity() > 10);
    }

    #[test]
    fn remove() {
        let mut obj_pool = ObjPool::new();

        let a = obj_pool.insert(0);
        let b = obj_pool.insert(10);
        let c = obj_pool.insert(20);
        obj_pool.insert(30);
        assert_eq!(obj_pool.len(), 4);

        assert_eq!(obj_pool.remove(b), Some(10));
        assert_eq!(obj_pool.remove(c), Some(20));
        assert_eq!(obj_pool.len(), 2);

        obj_pool.insert(-1);
        obj_pool.insert(-1);
        assert_eq!(obj_pool.len(), 4);

        assert_eq!(obj_pool.remove(a), Some(0));
        obj_pool.insert(-1);
        assert_eq!(obj_pool.len(), 4);

        obj_pool.insert(400);
        assert_eq!(obj_pool.len(), 5);
    }

    #[test]
    fn clear() {
        let mut obj_pool = ObjPool::new();
        obj_pool.insert(10);
        obj_pool.insert(20);

        assert!(!obj_pool.is_empty());
        assert_eq!(obj_pool.len(), 2);

        let cap = obj_pool.capacity();
        obj_pool.clear();

        assert!(obj_pool.is_empty());
        assert_eq!(obj_pool.len(), 0);
        assert_eq!(obj_pool.capacity(), cap);
    }

    #[test]
    fn indexing() {
        let mut obj_pool = ObjPool::new();

        let a = obj_pool.insert(10);
        let b = obj_pool.insert(20);
        let c = obj_pool.insert(30);

        obj_pool[b] += obj_pool[c];
        assert_eq!(obj_pool[a], 10);
        assert_eq!(obj_pool[b], 50);
        assert_eq!(obj_pool[c], 30);
    }

    #[test]
    #[should_panic]
    fn indexing_vacant() {
        let mut obj_pool = ObjPool::new();

        let _ = obj_pool.insert(10);
        let b = obj_pool.insert(20);
        let _ = obj_pool.insert(30);

        obj_pool.remove(b);
        obj_pool[b];
    }

    #[test]
    #[should_panic]
    fn invalid_indexing() {
        let mut obj_pool = ObjPool::new();

        obj_pool.insert(10);
        obj_pool.insert(20);
        let a = obj_pool.insert(30);
        obj_pool.remove(a);

        obj_pool[a];
    }

    #[test]
    fn get() {
        let mut obj_pool = ObjPool::new();

        let a = obj_pool.insert(10);
        let b = obj_pool.insert(20);
        let c = obj_pool.insert(30);

        *obj_pool.get_mut(b).unwrap() += *obj_pool.get(c).unwrap();
        assert_eq!(obj_pool.get(a), Some(&10));
        assert_eq!(obj_pool.get(b), Some(&50));
        assert_eq!(obj_pool.get(c), Some(&30));

        obj_pool.remove(b);
        assert_eq!(obj_pool.get(b), None);
        assert_eq!(obj_pool.get_mut(b), None);
    }

    #[test]
    fn reserve() {
        let mut obj_pool = ObjPool::new();
        obj_pool.insert(1);
        obj_pool.insert(2);

        obj_pool.reserve(10);
        assert!(obj_pool.capacity() >= 11);
    }

    #[test]
    fn reserve_exact() {
        let mut obj_pool = ObjPool::new();
        obj_pool.insert(1);
        obj_pool.insert(2);
        obj_pool.reserve(10);
        assert!(obj_pool.capacity() >= 11);
    }

    #[test]
    fn iter() {
        let mut arena = ObjPool::new();
        let a = arena.insert(10);
        let b = arena.insert(20);
        let c = arena.insert(30);
        let d = arena.insert(40);

        arena.remove(b);

        let mut it = arena.iter();
        assert_eq!(it.next(), Some((a, &10)));
        assert_eq!(it.next(), Some((c, &30)));
        assert_eq!(it.next(), Some((d, &40)));
        assert_eq!(it.next(), None);
    }

    #[test]
    fn iter_mut() {
        let mut obj_pool = ObjPool::new();
        let a = obj_pool.insert(10);
        let b = obj_pool.insert(20);
        let c = obj_pool.insert(30);
        let d = obj_pool.insert(40);

        obj_pool.remove(b);

        {
            let mut it = obj_pool.iter_mut();
            assert_eq!(it.next(), Some((a, &mut 10)));
            assert_eq!(it.next(), Some((c, &mut 30)));
            assert_eq!(it.next(), Some((d, &mut 40)));
            assert_eq!(it.next(), None);
        }

        for (obj_id, value) in &mut obj_pool {
            *value += obj_id.get();
        }

        let mut it = obj_pool.iter_mut();
        assert_eq!(*it.next().unwrap().1, 10 + a.get());
        assert_eq!(*it.next().unwrap().1, 30 + c.get());
        assert_eq!(*it.next().unwrap().1, 40 + d.get());
        assert_eq!(it.next(), None);
    }

    #[test]
    fn from_iter() {
        let obj_pool: ObjPool<usize> = [10, 20, 30, 40].iter().cloned().collect();

        let mut it = obj_pool.iter();
        assert_eq!(it.next(), Some((ObjPool::<usize>::index_to_obj_id(0), &10)));
        assert_eq!(it.next(), Some((ObjPool::<usize>::index_to_obj_id(1), &20)));
        assert_eq!(it.next(), Some((ObjPool::<usize>::index_to_obj_id(2), &30)));
        assert_eq!(it.next(), Some((ObjPool::<usize>::index_to_obj_id(3), &40)));
        assert_eq!(it.next(), None);
    }
}