Skip to main content

piece_tree/
cranelift_entity_vendor.rs

1#![allow(clippy::pedantic, clippy::all)]
2
3// Portions of this file are copied from the `cranelift_entity` crate.
4// Original code Copyright (c) The Cranelift Project Developers.
5// Licensed under the Apache License, Version 2.0 with LLVM Exception.
6// See: https://llvm.org/LICENSE.txt
7
8extern crate alloc;
9
10use alloc::vec::Vec;
11use core::fmt;
12use core::marker::PhantomData;
13use core::ops::{Index, IndexMut};
14use core::slice;
15use alloc::vec;
16use core::iter::Enumerate;
17
18/// A type wrapping a small integer index should implement `EntityRef` so it can be used as the key
19/// of an `SecondaryMap` or `SparseMap`.
20pub trait EntityRef: Copy + Eq {
21    /// Create a new entity reference from a small integer.
22    /// This should crash if the requested index is not representable.
23    fn new(_: usize) -> Self;
24
25    /// Get the index that was used to create this entity reference.
26    fn index(self) -> usize;
27}
28
29/// Macro which provides the common implementation of a 32-bit entity reference.
30#[macro_export]
31macro_rules! entity_impl {
32    // Basic traits.
33    ($entity:ident) => {
34        impl $crate::EntityRef for $entity {
35            #[inline]
36            fn new(index: usize) -> Self {
37                debug_assert!(index < (u32::MAX as usize));
38                $entity(index as u32)
39            }
40
41            #[inline]
42            fn index(self) -> usize {
43                self.0 as usize
44            }
45        }
46
47        impl $entity {
48            /// Create a new instance from a `u32`.
49            #[allow(dead_code, reason = "macro-generated code")]
50            #[inline]
51            pub fn from_u32(x: u32) -> Self {
52                debug_assert!(x < u32::MAX);
53                $entity(x)
54            }
55
56            /// Return the underlying index value as a `u32`.
57            #[allow(dead_code, reason = "macro-generated code")]
58            #[inline]
59            pub fn as_u32(self) -> u32 {
60                self.0
61            }
62
63            /// Return the raw bit encoding for this instance.
64            ///
65            /// __Warning__: the raw bit encoding is opaque and has no
66            /// guaranteed correspondence to the entity's index. It encodes the
67            /// entire state of this index value: either a valid index or an
68            /// invalid-index sentinel. The value returned by this method should
69            /// only be passed to `from_bits`.
70            #[allow(dead_code, reason = "macro-generated code")]
71            #[inline]
72            pub fn as_bits(self) -> u32 {
73                self.0
74            }
75
76            /// Create a new instance from the raw bit encoding.
77            ///
78            /// __Warning__: the raw bit encoding is opaque and has no
79            /// guaranteed correspondence to the entity's index. It encodes the
80            /// entire state of this index value: either a valid index or an
81            /// invalid-index sentinel. The value returned by this method should
82            /// only be given bits from `as_bits`.
83            #[allow(dead_code, reason = "macro-generated code")]
84            #[inline]
85            pub fn from_bits(x: u32) -> Self {
86                $entity(x)
87            }
88        }
89    };
90
91    // Include basic `Display` impl using the given display prefix.
92    // Display a `Block` reference as "block12".
93    ($entity:ident, $display_prefix:expr) => {
94        $crate::entity_impl!($entity);
95
96        impl core::fmt::Display for $entity {
97            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
98                write!(f, concat!($display_prefix, "{}"), self.0)
99            }
100        }
101
102        impl core::fmt::Debug for $entity {
103            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
104                (self as &dyn core::fmt::Display).fmt(f)
105            }
106        }
107    };
108
109    // Alternate form for tuples we can't directly construct; providing "to" and "from" expressions
110    // to turn an index *into* an entity, or get an index *from* an entity.
111    ($entity:ident, $display_prefix:expr, $arg:ident, $to_expr:expr, $from_expr:expr) => {
112        impl $crate::EntityRef for $entity {
113            #[inline]
114            fn new(index: usize) -> Self {
115                debug_assert!(index < (u32::MAX as usize));
116                let $arg = index as u32;
117                $to_expr
118            }
119
120            #[inline]
121            fn index(self) -> usize {
122                let $arg = self;
123                $from_expr as usize
124            }
125        }
126
127        impl $crate::packed_option::ReservedValue for $entity {
128            #[inline]
129            fn reserved_value() -> $entity {
130                $entity::from_u32(u32::MAX)
131            }
132
133            #[inline]
134            fn is_reserved_value(&self) -> bool {
135                self.as_u32() == u32::MAX
136            }
137        }
138
139        impl $entity {
140            /// Create a new instance from a `u32`.
141            #[allow(dead_code, reason = "macro-generated code")]
142            #[inline]
143            pub fn from_u32(x: u32) -> Self {
144                debug_assert!(x < u32::MAX);
145                let $arg = x;
146                $to_expr
147            }
148
149            /// Return the underlying index value as a `u32`.
150            #[allow(dead_code, reason = "macro-generated code")]
151            #[inline]
152            pub fn as_u32(self) -> u32 {
153                let $arg = self;
154                $from_expr
155            }
156        }
157
158        impl core::fmt::Display for $entity {
159            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
160                write!(f, concat!($display_prefix, "{}"), self.as_u32())
161            }
162        }
163
164        impl core::fmt::Debug for $entity {
165            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
166                (self as &dyn core::fmt::Display).fmt(f)
167            }
168        }
169    };
170}
171
172/// Densely numbered entity references as mapping keys.
173/// A primary mapping `K -> V` allocating dense entity references.
174///
175/// The `PrimaryMap` data structure uses the dense index space to implement a map with a vector.
176///
177/// A primary map contains the main definition of an entity, and it can be used to allocate new
178/// entity references with the `push` method.
179///
180/// There should only be a single `PrimaryMap` instance for a given `EntityRef` type, otherwise
181/// conflicting references will be created. Using unknown keys for indexing will cause a panic.
182///
183/// Note that `PrimaryMap` doesn't implement `Deref` or `DerefMut`, which would allow
184/// `&PrimaryMap<K, V>` to convert to `&[V]`. One of the main advantages of `PrimaryMap` is
185/// that it only allows indexing with the distinct `EntityRef` key type, so converting to a
186/// plain slice would make it easier to use incorrectly.
187#[derive(Clone, Hash, PartialEq, Eq)]
188pub struct PrimaryMap<K, V>
189where
190    K: EntityRef,
191{
192    elems: Vec<V>,
193    unused: PhantomData<K>,
194}
195
196impl<K, V> PrimaryMap<K, V>
197where
198    K: EntityRef,
199{
200    /// Create a new empty map.
201    pub fn new() -> Self {
202        Self {
203            elems: Vec::new(),
204            unused: PhantomData,
205        }
206    }
207
208    /// Create a new empty map with the given capacity.
209    pub fn with_capacity(capacity: usize) -> Self {
210        Self {
211            elems: Vec::with_capacity(capacity),
212            unused: PhantomData,
213        }
214    }
215
216    /// Check if `k` is a valid key in the map.
217    pub fn is_valid(&self, k: K) -> bool {
218        k.index() < self.elems.len()
219    }
220
221    /// Get the element at `k` if it exists.
222    pub fn get(&self, k: K) -> Option<&V> {
223        self.elems.get(k.index())
224    }
225
226    /// Get the slice of values associated with the given range of keys, if any.
227    pub fn get_range(&self, range: core::ops::Range<K>) -> Option<&[V]> {
228        self.elems.get(range.start.index()..range.end.index())
229    }
230
231    /// Get the element at `k` if it exists, mutable version.
232    pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
233        self.elems.get_mut(k.index())
234    }
235
236    /// Is this map completely empty?
237    pub fn is_empty(&self) -> bool {
238        self.elems.is_empty()
239    }
240
241    /// Get the total number of entity references created.
242    pub fn len(&self) -> usize {
243        self.elems.len()
244    }
245
246    /// Iterate over all the keys in this map.
247    pub fn keys(&self) -> Keys<K> {
248        Keys::with_len(self.elems.len())
249    }
250
251    /// Iterate over all the values in this map.
252    pub fn values(&self) -> slice::Iter<'_, V> {
253        self.elems.iter()
254    }
255
256    /// Iterate over all the values in this map, mutable edition.
257    pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {
258        self.elems.iter_mut()
259    }
260
261    /// Get this map's underlying values as a slice.
262    pub fn as_values_slice(&self) -> &[V] {
263        &self.elems
264    }
265
266    /// Iterate over all the keys and values in this map.
267    pub fn iter(&self) -> Iter<'_, K, V> {
268        Iter::new(self.elems.iter())
269    }
270
271    /// Iterate over all the keys and values in this map, mutable edition.
272    pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
273        IterMut::new(self.elems.iter_mut())
274    }
275
276    /// Remove all entries from this map.
277    pub fn clear(&mut self) {
278        self.elems.clear()
279    }
280
281    /// Get the key that will be assigned to the next pushed value.
282    pub fn next_key(&self) -> K {
283        K::new(self.elems.len())
284    }
285
286    /// Append `v` to the mapping, assigning a new key which is returned.
287    pub fn push(&mut self, v: V) -> K {
288        let k = self.next_key();
289        self.elems.push(v);
290        k
291    }
292
293    /// Returns the last element that was inserted in the map.
294    pub fn last(&self) -> Option<(K, &V)> {
295        let len = self.elems.len();
296        let last = self.elems.last()?;
297        Some((K::new(len - 1), last))
298    }
299
300    /// Returns the last element that was inserted in the map.
301    pub fn last_mut(&mut self) -> Option<(K, &mut V)> {
302        let len = self.elems.len();
303        let last = self.elems.last_mut()?;
304        Some((K::new(len - 1), last))
305    }
306
307    /// Reserves capacity for at least `additional` more elements to be inserted.
308    pub fn reserve(&mut self, additional: usize) {
309        self.elems.reserve(additional)
310    }
311
312    /// Reserves the minimum capacity for exactly `additional` more elements to be inserted.
313    pub fn reserve_exact(&mut self, additional: usize) {
314        self.elems.reserve_exact(additional)
315    }
316
317    /// Shrinks the capacity of the `PrimaryMap` as much as possible.
318    pub fn shrink_to_fit(&mut self) {
319        self.elems.shrink_to_fit()
320    }
321
322    /// Returns mutable references to many elements at once.
323    ///
324    /// Returns an error if an element does not exist, or if the same key was passed more than
325    /// once.
326    pub fn get_disjoint_mut<const N: usize>(
327        &mut self,
328        indices: [K; N],
329    ) -> Result<[&mut V; N], slice::GetDisjointMutError> {
330        self.elems.get_disjoint_mut(indices.map(|k| k.index()))
331    }
332
333    /// Performs a binary search on the values with a key extraction function.
334    ///
335    /// Assumes that the values are sorted by the key extracted by the function.
336    ///
337    /// If the value is found then `Ok(K)` is returned, containing the entity key
338    /// of the matching value.
339    ///
340    /// If there are multiple matches, then any one of the matches could be returned.
341    ///
342    /// If the value is not found then Err(K) is returned, containing the entity key
343    /// where a matching element could be inserted while maintaining sorted order.
344    pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K>
345    where
346        F: FnMut(&'a V) -> B,
347        B: Ord,
348    {
349        self.elems
350            .binary_search_by_key(b, f)
351            .map(|i| K::new(i))
352            .map_err(|i| K::new(i))
353    }
354
355    /// Analog of `get_raw` except that a raw pointer is returned rather than a
356    /// mutable reference.
357    ///
358    /// The default accessors of items in [`PrimaryMap`] will invalidate all
359    /// previous borrows obtained from the map according to miri. This function
360    /// can be used to acquire a pointer and then subsequently acquire a second
361    /// pointer later on without invalidating the first one. In other words
362    /// this is only here to help borrow two elements simultaneously with miri.
363    pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> {
364        if k.index() < self.elems.len() {
365            // SAFETY: the `add` function requires that the index is in-bounds
366            // with respect to the allocation which is satisfied here due to
367            // the bounds-check above.
368            unsafe { Some(self.elems.as_mut_ptr().add(k.index())) }
369        } else {
370            None
371        }
372    }
373}
374
375impl<K, V> Default for PrimaryMap<K, V>
376where
377    K: EntityRef,
378{
379    fn default() -> PrimaryMap<K, V> {
380        PrimaryMap::new()
381    }
382}
383
384/// Immutable indexing into an `PrimaryMap`.
385/// The indexed value must be in the map.
386impl<K, V> Index<K> for PrimaryMap<K, V>
387where
388    K: EntityRef,
389{
390    type Output = V;
391
392    fn index(&self, k: K) -> &V {
393        &self.elems[k.index()]
394    }
395}
396
397/// Mutable indexing into an `PrimaryMap`.
398impl<K, V> IndexMut<K> for PrimaryMap<K, V>
399where
400    K: EntityRef,
401{
402    fn index_mut(&mut self, k: K) -> &mut V {
403        &mut self.elems[k.index()]
404    }
405}
406
407impl<K, V> IntoIterator for PrimaryMap<K, V>
408where
409    K: EntityRef,
410{
411    type Item = (K, V);
412    type IntoIter = IntoIter<K, V>;
413
414    fn into_iter(self) -> Self::IntoIter {
415        IntoIter::new(self.elems.into_iter())
416    }
417}
418
419impl<'a, K, V> IntoIterator for &'a PrimaryMap<K, V>
420where
421    K: EntityRef,
422{
423    type Item = (K, &'a V);
424    type IntoIter = Iter<'a, K, V>;
425
426    fn into_iter(self) -> Self::IntoIter {
427        Iter::new(self.elems.iter())
428    }
429}
430
431impl<'a, K, V> IntoIterator for &'a mut PrimaryMap<K, V>
432where
433    K: EntityRef,
434{
435    type Item = (K, &'a mut V);
436    type IntoIter = IterMut<'a, K, V>;
437
438    fn into_iter(self) -> Self::IntoIter {
439        IterMut::new(self.elems.iter_mut())
440    }
441}
442
443impl<K, V> FromIterator<V> for PrimaryMap<K, V>
444where
445    K: EntityRef,
446{
447    fn from_iter<T>(iter: T) -> Self
448    where
449        T: IntoIterator<Item = V>,
450    {
451        Self {
452            elems: Vec::from_iter(iter),
453            unused: PhantomData,
454        }
455    }
456}
457
458impl<K, V> Extend<V> for PrimaryMap<K, V>
459where
460    K: EntityRef,
461{
462    fn extend<T>(&mut self, iter: T)
463    where
464        T: IntoIterator<Item = V>,
465    {
466        self.elems.extend(iter);
467    }
468}
469
470impl<K, V> From<Vec<V>> for PrimaryMap<K, V>
471where
472    K: EntityRef,
473{
474    fn from(elems: Vec<V>) -> Self {
475        Self {
476            elems,
477            unused: PhantomData,
478        }
479    }
480}
481
482impl<K, V> From<PrimaryMap<K, V>> for Vec<V>
483where
484    K: EntityRef,
485{
486    fn from(map: PrimaryMap<K, V>) -> Self {
487        map.elems
488    }
489}
490
491impl<K: EntityRef + fmt::Debug, V: fmt::Debug> fmt::Debug for PrimaryMap<K, V> {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        let mut struct_ = f.debug_struct("PrimaryMap");
494        for (k, v) in self {
495            struct_.field(&alloc::format!("{k:?}"), v);
496        }
497        struct_.finish()
498    }
499}
500
501/// A double-ended iterator over entity references.
502///
503/// When `core::iter::Step` is stabilized, `Keys` could be implemented as a wrapper around
504/// `core::ops::Range`, but for now, we implement it manually.
505/// Iterate over all keys in order.
506pub struct Keys<K: EntityRef> {
507    pos: usize,
508    rev_pos: usize,
509    unused: PhantomData<K>,
510}
511
512impl<K: EntityRef> Keys<K> {
513    /// Create a `Keys` iterator that visits `len` entities starting from 0.
514    pub fn with_len(len: usize) -> Self {
515        Self {
516            pos: 0,
517            rev_pos: len,
518            unused: PhantomData,
519        }
520    }
521}
522
523impl<K: EntityRef> Iterator for Keys<K> {
524    type Item = K;
525
526    fn next(&mut self) -> Option<Self::Item> {
527        if self.pos < self.rev_pos {
528            let k = K::new(self.pos);
529            self.pos += 1;
530            Some(k)
531        } else {
532            None
533        }
534    }
535
536    fn size_hint(&self) -> (usize, Option<usize>) {
537        let size = self.rev_pos - self.pos;
538        (size, Some(size))
539    }
540}
541
542impl<K: EntityRef> DoubleEndedIterator for Keys<K> {
543    fn next_back(&mut self) -> Option<Self::Item> {
544        if self.rev_pos > self.pos {
545            let k = K::new(self.rev_pos - 1);
546            self.rev_pos -= 1;
547            Some(k)
548        } else {
549            None
550        }
551    }
552}
553
554impl<K: EntityRef> ExactSizeIterator for Keys<K> {}
555
556/// Iterate over all keys in order.
557pub struct Iter<'a, K: EntityRef, V>
558where
559    V: 'a,
560{
561    enumerate: Enumerate<slice::Iter<'a, V>>,
562    unused: PhantomData<K>,
563}
564
565impl<'a, K: EntityRef, V> Iter<'a, K, V> {
566    /// Create an `Iter` iterator that visits the `PrimaryMap` keys and values
567    /// of `iter`.
568    pub fn new(iter: slice::Iter<'a, V>) -> Self {
569        Self {
570            enumerate: iter.enumerate(),
571            unused: PhantomData,
572        }
573    }
574}
575
576impl<'a, K: EntityRef, V> Iterator for Iter<'a, K, V> {
577    type Item = (K, &'a V);
578
579    fn next(&mut self) -> Option<Self::Item> {
580        self.enumerate.next().map(|(i, v)| (K::new(i), v))
581    }
582
583    fn size_hint(&self) -> (usize, Option<usize>) {
584        self.enumerate.size_hint()
585    }
586}
587
588impl<'a, K: EntityRef, V> DoubleEndedIterator for Iter<'a, K, V> {
589    fn next_back(&mut self) -> Option<Self::Item> {
590        self.enumerate.next_back().map(|(i, v)| (K::new(i), v))
591    }
592}
593
594impl<'a, K: EntityRef, V> ExactSizeIterator for Iter<'a, K, V> {}
595
596/// Iterate over all keys in order.
597pub struct IterMut<'a, K: EntityRef, V>
598where
599    V: 'a,
600{
601    enumerate: Enumerate<slice::IterMut<'a, V>>,
602    unused: PhantomData<K>,
603}
604
605impl<'a, K: EntityRef, V> IterMut<'a, K, V> {
606    /// Create an `IterMut` iterator that visits the `PrimaryMap` keys and values
607    /// of `iter`.
608    pub fn new(iter: slice::IterMut<'a, V>) -> Self {
609        Self {
610            enumerate: iter.enumerate(),
611            unused: PhantomData,
612        }
613    }
614}
615
616impl<'a, K: EntityRef, V> Iterator for IterMut<'a, K, V> {
617    type Item = (K, &'a mut V);
618
619    fn next(&mut self) -> Option<Self::Item> {
620        self.enumerate.next().map(|(i, v)| (K::new(i), v))
621    }
622
623    fn size_hint(&self) -> (usize, Option<usize>) {
624        self.enumerate.size_hint()
625    }
626}
627
628impl<'a, K: EntityRef, V> DoubleEndedIterator for IterMut<'a, K, V> {
629    fn next_back(&mut self) -> Option<Self::Item> {
630        self.enumerate.next_back().map(|(i, v)| (K::new(i), v))
631    }
632}
633
634impl<'a, K: EntityRef, V> ExactSizeIterator for IterMut<'a, K, V> {}
635
636/// Iterate over all keys in order.
637pub struct IntoIter<K: EntityRef, V> {
638    enumerate: Enumerate<vec::IntoIter<V>>,
639    unused: PhantomData<K>,
640}
641
642impl<K: EntityRef, V> IntoIter<K, V> {
643    /// Create an `IntoIter` iterator that visits the `PrimaryMap` keys and values
644    /// of `iter`.
645    pub fn new(iter: vec::IntoIter<V>) -> Self {
646        Self {
647            enumerate: iter.enumerate(),
648            unused: PhantomData,
649        }
650    }
651}
652
653impl<K: EntityRef, V> Iterator for IntoIter<K, V> {
654    type Item = (K, V);
655
656    fn next(&mut self) -> Option<Self::Item> {
657        self.enumerate.next().map(|(i, v)| (K::new(i), v))
658    }
659
660    fn size_hint(&self) -> (usize, Option<usize>) {
661        self.enumerate.size_hint()
662    }
663}
664
665impl<K: EntityRef, V> DoubleEndedIterator for IntoIter<K, V> {
666    fn next_back(&mut self) -> Option<Self::Item> {
667        self.enumerate.next_back().map(|(i, v)| (K::new(i), v))
668    }
669}
670
671impl<K: EntityRef, V> ExactSizeIterator for IntoIter<K, V> {}