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
use rustc_index::vec::{Idx, IndexVec};
use std::mem;
use std::ptr;
pub trait IdFunctor {
type Inner;
fn map_id<F>(self, f: F) -> Self
where
F: FnMut(Self::Inner) -> Self::Inner;
}
impl<T> IdFunctor for Box<T> {
type Inner = T;
#[inline]
fn map_id<F>(self, mut f: F) -> Self
where
F: FnMut(Self::Inner) -> Self::Inner,
{
let raw = Box::into_raw(self);
unsafe {
let value = ptr::read(raw);
let mut raw: Box<mem::MaybeUninit<T>> = Box::from_raw(raw.cast());
ptr::write(raw.as_mut_ptr(), f(value));
raw.assume_init()
}
}
}
impl<T> IdFunctor for Vec<T> {
type Inner = T;
#[inline]
fn map_id<F>(mut self, mut f: F) -> Self
where
F: FnMut(Self::Inner) -> Self::Inner,
{
let len = self.len();
unsafe {
self.set_len(0);
let start = self.as_mut_ptr();
for i in 0..len {
let p = start.add(i);
ptr::write(p, f(ptr::read(p)));
}
self.set_len(len);
}
self
}
}
impl<T> IdFunctor for Box<[T]> {
type Inner = T;
#[inline]
fn map_id<F>(self, f: F) -> Self
where
F: FnMut(Self::Inner) -> Self::Inner,
{
Vec::from(self).map_id(f).into()
}
}
impl<I: Idx, T> IdFunctor for IndexVec<I, T> {
type Inner = T;
#[inline]
fn map_id<F>(self, f: F) -> Self
where
F: FnMut(Self::Inner) -> Self::Inner,
{
IndexVec::from_raw(self.raw.map_id(f))
}
}