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
//! [![](https://img.shields.io/crates/v/id-arena.svg)](https://crates.io/crates/id-arena)
//! [![](https://img.shields.io/crates/d/id-arena.svg)](https://crates.io/crates/id-arena)
//! [![Travis CI Build Status](https://travis-ci.org/fitzgen/id-arena.svg?branch=master)](https://travis-ci.org/fitzgen/id-arena)
//!
//! A simple, id-based arena.
//!
//! ## Id-based
//!
//! Allocate objects and get an identifier for that object back, *not* a
//! reference to the allocated object. Given an id, you can get a shared or
//! exclusive reference to the allocated object from the arena. This id-based
//! approach is useful for constructing mutable graph data structures.
//!
//! If you want allocation to return a reference, consider [the `typed-arena`
//! crate](https://github.com/SimonSapin/rust-typed-arena/) instead.
//!
//! ## No Deletion
//!
//! This arena does not support deletion, which makes its implementation simple
//! and allocation fast. If you want deletion, you need a way to solve the ABA
//! problem. Consider using [the `generational-arena`
//! crate](https://github.com/fitzgen/generational-arena) instead.
//!
//! ## Homogeneous
//!
//! This crate's arenas can only contain objects of a single type `T`. If you
//! need an arena of objects with heterogeneous types, consider another crate.
//!
//! ## `#![no_std]` Support
//!
//! Requires the `alloc` nightly feature. Disable the on-by-default `"std"` feature:
//!
//! ```toml
//! [dependencies.id-arena]
//! version = "2"
//! default-features = false
//! ```
//!
//! ## `rayon` Support
//!
//! If the `rayon` feature of this crate is activated:
//!
//! ```toml
//! [dependencies]
//! id-arena = { version = "2", features = ["rayon"] }
//! ```
//!
//! then you can use [`rayon`](https://crates.io/crates/rayon)'s support for
//! parallel iteration. The `Arena` type will have a `par_iter` family of
//! methods where appropriate.
//!
//! ## Example
//!
//! ```rust
//! use id_arena::{Arena, Id};
//!
//! type AstNodeId = Id<AstNode>;
//!
//! #[derive(Debug, Eq, PartialEq)]
//! pub enum AstNode {
//!     Const(i64),
//!     Var(String),
//!     Add {
//!         lhs: AstNodeId,
//!         rhs: AstNodeId,
//!     },
//!     Sub {
//!         lhs: AstNodeId,
//!         rhs: AstNodeId,
//!     },
//!     Mul {
//!         lhs: AstNodeId,
//!         rhs: AstNodeId,
//!     },
//!     Div {
//!         lhs: AstNodeId,
//!         rhs: AstNodeId,
//!     },
//! }
//!
//! let mut ast_nodes = Arena::<AstNode>::new();
//!
//! // Create the AST for `a * (b + 3)`.
//! let three = ast_nodes.alloc(AstNode::Const(3));
//! let b = ast_nodes.alloc(AstNode::Var("b".into()));
//! let b_plus_three = ast_nodes.alloc(AstNode::Add {
//!     lhs: b,
//!     rhs: three,
//! });
//! let a = ast_nodes.alloc(AstNode::Var("a".into()));
//! let a_times_b_plus_three = ast_nodes.alloc(AstNode::Mul {
//!     lhs: a,
//!     rhs: b_plus_three,
//! });
//!
//! // Can use indexing to access allocated nodes.
//! assert_eq!(ast_nodes[three], AstNode::Const(3));
//! ```

#![forbid(unsafe_code)]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
// In no-std mode, use the alloc crate to get `Vec`.
#![no_std]
#![cfg_attr(not(feature = "std"), feature(alloc))]

use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter;
use core::marker::PhantomData;
use core::ops;
use core::slice;
use core::sync::atomic::{self, AtomicUsize, ATOMIC_USIZE_INIT};

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::vec::{self, Vec};

#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "std")]
use std::vec::{self, Vec};

#[cfg(feature = "rayon")]
mod rayon;
#[cfg(feature = "rayon")]
pub use rayon::*;

/// A trait representing the implementation behavior of an arena and how
/// identifiers are represented.
///
/// ## When should I implement `ArenaBehavior` myself?
///
/// Usually, you should just use `DefaultArenaBehavior`, which is simple and
/// correct. However, there are some scenarios where you might want to implement
/// `ArenaBehavior` yourself:
///
/// * **Space optimizations:** The default identifier is two words in size,
/// which is larger than is usually necessary. For example, if you know that an
/// arena *cannot* contain more than 256 items, you could make your own
/// identifier type that stores the index as a `u8` and then you can save some
/// space.
///
/// * **Trait Coherence:** If you need to implement an upstream crate's traits
/// for identifiers, then defining your own identifier type allows you to work
/// with trait coherence rules.
///
/// * **Share identifiers across arenas:** You can coordinate and share
/// identifiers across different arenas to enable a "struct of arrays" style
/// data representation.
pub trait ArenaBehavior {
    /// The identifier type.
    type Id: Copy;

    /// Construct a new object identifier from the given index and arena
    /// identifier.
    ///
    /// ## Panics
    ///
    /// Implementations are allowed to panic if the given index is larger than
    /// the underlying storage (e.g. the implementation uses a `u8` for storing
    /// indices and the given index value is larger than 255).
    fn new_id(arena_id: u32, index: usize) -> Self::Id;

    /// Get the given identifier's index.
    fn index(Self::Id) -> usize;

    /// Get the given identifier's arena id.
    fn arena_id(Self::Id) -> u32;

    /// Construct a new arena identifier.
    ///
    /// This is used to disambiguate `Id`s across different arenas. To make
    /// identifiers with the same index from different arenas compare false for
    /// equality, return a unique `u32` on every invocation. This is the
    /// default, provided implementation's behavior.
    ///
    /// To make identifiers with the same index from different arenas compare
    /// true for equality, return the same `u32` on every invocation.
    fn new_arena_id() -> u32 {
        static ARENA_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
        ARENA_COUNTER.fetch_add(1, atomic::Ordering::SeqCst) as u32
    }
}

/// An identifier for an object allocated within an arena.
pub struct Id<T> {
    idx: usize,
    arena_id: u32,
    _ty: PhantomData<fn() -> T>,
}

impl<T> fmt::Debug for Id<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Id").field("idx", &self.idx).finish()
    }
}

impl<T> Copy for Id<T> {}

impl<T> Clone for Id<T> {
    #[inline]
    fn clone(&self) -> Id<T> {
        *self
    }
}

impl<T> PartialEq for Id<T> {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        self.arena_id == rhs.arena_id && self.idx == rhs.idx
    }
}

impl<T> Eq for Id<T> {}

impl<T> Hash for Id<T> {
    #[inline]
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.arena_id.hash(h);
        self.idx.hash(h);
    }
}

impl<T> PartialOrd for Id<T> {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<T> Ord for Id<T> {
    fn cmp(&self, rhs: &Self) -> Ordering {
        self.arena_id
            .cmp(&rhs.arena_id)
            .then(self.idx.cmp(&rhs.idx))
    }
}

impl<T> Id<T> {
    /// Get the index within the arena that this id refers to.
    #[inline]
    pub fn index(&self) -> usize {
        self.idx
    }
}

/// The default `ArenaBehavior` implementation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DefaultArenaBehavior<T> {
    _phantom: PhantomData<fn() -> T>,
}

impl<T> ArenaBehavior for DefaultArenaBehavior<T> {
    type Id = Id<T>;

    #[inline]
    fn new_id(arena_id: u32, idx: usize) -> Self::Id {
        Id {
            idx,
            arena_id,
            _ty: PhantomData,
        }
    }

    #[inline]
    fn index(id: Self::Id) -> usize {
        id.idx
    }

    #[inline]
    fn arena_id(id: Self::Id) -> u32 {
        id.arena_id
    }
}

/// An arena of objects of type `T`.
///
/// ```
/// use id_arena::Arena;
///
/// let mut arena = Arena::<&str>::new();
///
/// let a = arena.alloc("Albert");
/// assert_eq!(arena[a], "Albert");
///
/// arena[a] = "Alice";
/// assert_eq!(arena[a], "Alice");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Arena<T, A = DefaultArenaBehavior<T>> {
    arena_id: u32,
    items: Vec<T>,
    _phantom: PhantomData<fn() -> A>,
}

impl<T, A> Default for Arena<T, A>
where
    A: ArenaBehavior,
{
    #[inline]
    fn default() -> Arena<T, A> {
        Arena {
            arena_id: A::new_arena_id(),
            items: Vec::new(),
            _phantom: PhantomData,
        }
    }
}

impl<T, A> Arena<T, A>
where
    A: ArenaBehavior,
{
    /// Construct a new, empty `Arena`.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<usize>::new();
    /// arena.alloc(42);
    /// ```
    #[inline]
    pub fn new() -> Arena<T, A> {
        Default::default()
    }

    /// Construct a new, empty `Arena` with capacity for the given number of
    /// elements.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<usize>::with_capacity(100);
    /// for x in 0..100 {
    ///     arena.alloc(x * x);
    /// }
    /// ```
    #[inline]
    pub fn with_capacity(capacity: usize) -> Arena<T, A> {
        Arena {
            arena_id: A::new_arena_id(),
            items: Vec::with_capacity(capacity),
            _phantom: PhantomData,
        }
    }

    /// Allocate `item` within this arena and return its id.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<usize>::new();
    /// let _id = arena.alloc(42);
    /// ```
    ///
    /// ## Panics
    ///
    /// Panics if the number of elements in the arena overflows a `usize` or
    /// `Id`'s index storage representation.
    #[inline]
    pub fn alloc(&mut self, item: T) -> A::Id {
        let id = self.next_id();
        self.items.push(item);
        id
    }

    /// Allocate an item with the id that it will be assigned.
    ///
    /// This is useful for structures that want to store their id as their own
    /// member.
    ///
    /// ```
    /// use id_arena::{Arena, Id};
    ///
    /// struct Cat {
    ///     id: Id<Cat>,
    /// }
    ///
    /// let mut arena = Arena::<Cat>::new();
    ///
    /// let kitty = arena.alloc_with_id(|id| Cat { id });
    /// assert_eq!(arena[kitty].id, kitty);
    /// ```
    #[inline]
    pub fn alloc_with_id(&mut self, f: impl FnOnce(A::Id) -> T) -> A::Id {
        let id = self.next_id();
        let val = f(id);
        self.alloc(val)
    }

    /// Get the id that will be used for the next item allocated into this
    /// arena.
    ///
    /// If you are allocating a `struct` that wants to have its id as a member
    /// of itself, prefer the less error-prone `Arena::alloc_with_id` method.
    #[inline]
    pub fn next_id(&self) -> A::Id {
        let arena_id = self.arena_id;
        let idx = self.items.len();
        A::new_id(arena_id, idx)
    }

    /// Get a shared reference to the object associated with the given `id` if
    /// it exists.
    ///
    /// If there is no object associated with `id` (for example, it might
    /// reference an object allocated within a different arena) then return
    /// `None`.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<usize>::new();
    /// let id = arena.alloc(42);
    /// assert!(arena.get(id).is_some());
    ///
    /// let other_arena = Arena::<usize>::new();
    /// assert!(other_arena.get(id).is_none());
    /// ```
    #[inline]
    pub fn get(&self, id: A::Id) -> Option<&T> {
        if A::arena_id(id) != self.arena_id {
            None
        } else {
            self.items.get(A::index(id))
        }
    }

    /// Get an exclusive reference to the object associated with the given `id`
    /// if it exists.
    ///
    /// If there is no object associated with `id` (for example, it might
    /// reference an object allocated within a different arena) then return
    /// `None`.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<usize>::new();
    /// let id = arena.alloc(42);
    /// assert!(arena.get_mut(id).is_some());
    ///
    /// let mut other_arena = Arena::<usize>::new();
    /// assert!(other_arena.get_mut(id).is_none());
    /// ```
    #[inline]
    pub fn get_mut(&mut self, id: A::Id) -> Option<&mut T> {
        if A::arena_id(id) != self.arena_id {
            None
        } else {
            self.items.get_mut(A::index(id))
        }
    }

    /// Iterate over this arena's items and their ids.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<&str>::new();
    ///
    /// arena.alloc("hello");
    /// arena.alloc("hi");
    /// arena.alloc("yo");
    ///
    /// for (id, s) in arena.iter() {
    ///     assert_eq!(arena.get(id).unwrap(), s);
    ///     println!("{:?} -> {}", id, s);
    /// }
    /// ```
    #[inline]
    pub fn iter(&self) -> Iter<T, A> {
        IntoIterator::into_iter(self)
    }

    /// Iterate over this arena's items and their ids, allowing mutation of each
    /// item.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<T, A> {
        IntoIterator::into_iter(self)
    }

    /// Get the number of objects allocated in this arena.
    ///
    /// ```
    /// use id_arena::Arena;
    ///
    /// let mut arena = Arena::<&str>::new();
    ///
    /// arena.alloc("hello");
    /// arena.alloc("hi");
    ///
    /// assert_eq!(arena.len(), 2);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.items.len()
    }
}

impl<T, A> ops::Index<A::Id> for Arena<T, A>
where
    A: ArenaBehavior,
{
    type Output = T;

    #[inline]
    fn index(&self, id: A::Id) -> &T {
        assert_eq!(self.arena_id, A::arena_id(id));
        &self.items[A::index(id)]
    }
}

impl<T, A> ops::IndexMut<A::Id> for Arena<T, A>
where
    A: ArenaBehavior,
{
    #[inline]
    fn index_mut(&mut self, id: A::Id) -> &mut T {
        assert_eq!(self.arena_id, A::arena_id(id));
        &mut self.items[A::index(id)]
    }
}

fn add_id<A, T>(item: Option<(usize, T)>, arena_id: u32) -> Option<(A::Id, T)>
where
    A: ArenaBehavior,
{
    item.map(|(idx, item)| (A::new_id(arena_id, idx), item))
}

/// An iterator over `(Id, &T)` pairs in an arena.
///
/// See [the `Arena::iter()` method](./struct.Arena.html#method.iter) for details.
#[derive(Debug)]
pub struct Iter<'a, T: 'a, A: 'a> {
    arena_id: u32,
    iter: iter::Enumerate<slice::Iter<'a, T>>,
    _phantom: PhantomData<fn() -> A>,
}

impl<'a, T: 'a, A: 'a> Iterator for Iter<'a, T, A>
where
    A: ArenaBehavior,
{
    type Item = (A::Id, &'a T);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        add_id::<A, _>(self.iter.next(), self.arena_id)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T: 'a, A: 'a> DoubleEndedIterator for Iter<'a, T, A>
where
    A: ArenaBehavior,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        add_id::<A, _>(self.iter.next_back(), self.arena_id)
    }
}

impl<'a, T: 'a, A: 'a> ExactSizeIterator for Iter<'a, T, A>
where
    A: ArenaBehavior,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a, T, A> IntoIterator for &'a Arena<T, A>
where
    A: ArenaBehavior,
{
    type Item = (A::Id, &'a T);
    type IntoIter = Iter<'a, T, A>;

    #[inline]
    fn into_iter(self) -> Iter<'a, T, A> {
        Iter {
            arena_id: self.arena_id,
            iter: self.items.iter().enumerate(),
            _phantom: PhantomData,
        }
    }
}

/// An iterator over `(Id, &mut T)` pairs in an arena.
///
/// See [the `Arena::iter_mut()` method](./struct.Arena.html#method.iter_mut)
/// for details.
#[derive(Debug)]
pub struct IterMut<'a, T: 'a, A: 'a> {
    arena_id: u32,
    iter: iter::Enumerate<slice::IterMut<'a, T>>,
    _phantom: PhantomData<fn() -> A>,
}

impl<'a, T: 'a, A: 'a> Iterator for IterMut<'a, T, A>
where
    A: ArenaBehavior,
{
    type Item = (A::Id, &'a mut T);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        add_id::<A, _>(self.iter.next(), self.arena_id)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a, T: 'a, A: 'a> DoubleEndedIterator for IterMut<'a, T, A>
where
    A: ArenaBehavior,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        add_id::<A, _>(self.iter.next_back(), self.arena_id)
    }
}

impl<'a, T: 'a, A: 'a> ExactSizeIterator for IterMut<'a, T, A>
where
    A: ArenaBehavior,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a, T, A> IntoIterator for &'a mut Arena<T, A>
where
    A: ArenaBehavior,
{
    type Item = (A::Id, &'a mut T);
    type IntoIter = IterMut<'a, T, A>;

    #[inline]
    fn into_iter(self) -> IterMut<'a, T, A> {
        IterMut {
            arena_id: self.arena_id,
            iter: self.items.iter_mut().enumerate(),
            _phantom: PhantomData,
        }
    }
}

/// An iterator over `(Id, T)` pairs in an arena.
#[derive(Debug)]
pub struct IntoIter<T, A> {
    arena_id: u32,
    iter: iter::Enumerate<vec::IntoIter<T>>,
    _phantom: PhantomData<fn() -> A>,
}

impl<T, A> Iterator for IntoIter<T, A>
where
    A: ArenaBehavior,
{
    type Item = (A::Id, T);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        add_id::<A, _>(self.iter.next(), self.arena_id)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<T, A> DoubleEndedIterator for IntoIter<T, A>
where
    A: ArenaBehavior,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        add_id::<A, _>(self.iter.next_back(), self.arena_id)
    }
}

impl<T, A> ExactSizeIterator for IntoIter<T, A>
where
    A: ArenaBehavior,
{
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<T, A> IntoIterator for Arena<T, A>
where
    A: ArenaBehavior,
{
    type Item = (A::Id, T);
    type IntoIter = IntoIter<T, A>;

    #[inline]
    fn into_iter(self) -> IntoIter<T, A> {
        IntoIter {
            arena_id: self.arena_id,
            iter: self.items.into_iter().enumerate(),
            _phantom: PhantomData,
        }
    }
}

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

    #[test]
    fn ids_are_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        struct Foo;
        assert_send_sync::<Id<Foo>>();
    }
}