-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathfrozen.rs
More file actions
295 lines (248 loc) · 8.09 KB
/
Copy pathfrozen.rs
File metadata and controls
295 lines (248 loc) · 8.09 KB
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
use std::hash::Hash;
use ruff_index::Idx;
use rustc_hash::FxHashMap;
/// Compact immutable key-value entries stored in key order.
///
/// Analysis builds these tables with hash maps, but after construction they only need keyed
/// lookup. A sorted slice avoids retaining hash-table capacity for every indexed file.
#[derive(Debug, Eq, PartialEq, salsa::Update, get_size2::GetSize)]
pub struct FrozenMap<K, V>(Box<[(K, V)]>);
impl<K, V> FrozenMap<K, V> {
pub fn iter(&self) -> std::slice::Iter<'_, (K, V)> {
self.0.iter()
}
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, (K, V)> {
self.0.iter_mut()
}
pub fn keys(&self) -> impl DoubleEndedIterator<Item = &K> + ExactSizeIterator {
self.0.iter().map(|(key, _)| key)
}
pub fn values(&self) -> impl DoubleEndedIterator<Item = &V> + ExactSizeIterator {
self.0.iter().map(|(_, value)| value)
}
}
impl<K: Ord, V> FromIterator<(K, V)> for FrozenMap<K, V> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut entries = iter.into_iter().collect::<Vec<_>>();
entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
entries.dedup_by(|(left, _), (right, _)| left == right);
Self(entries.into_boxed_slice())
}
}
impl<K, V> From<std::collections::BTreeMap<K, V>> for FrozenMap<K, V> {
fn from(map: std::collections::BTreeMap<K, V>) -> Self {
Self(map.into_iter().collect())
}
}
impl<K: Ord, V, S> From<std::collections::HashMap<K, V, S>> for FrozenMap<K, V> {
fn from(map: std::collections::HashMap<K, V, S>) -> Self {
Self::from_entries(map.into_iter().collect())
}
}
impl<K: Ord, V> FrozenMap<K, V> {
pub(crate) fn from_entries(mut entries: Vec<(K, V)>) -> Self {
entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
Self(entries.into_boxed_slice())
}
pub fn get(&self, key: &K) -> Option<&V> {
self.0
.binary_search_by(|(candidate, _)| candidate.cmp(key))
.ok()
.map(|index| &self.0[index].1)
}
}
impl<K, V> Default for FrozenMap<K, V> {
fn default() -> Self {
Self(Box::default())
}
}
impl<K: Ord, V> std::ops::Index<&K> for FrozenMap<K, V> {
type Output = V;
#[track_caller]
fn index(&self, index: &K) -> &Self::Output {
self.get(index).expect("key not found")
}
}
impl<K, V> IntoIterator for FrozenMap<K, V> {
type Item = (K, V);
type IntoIter = std::vec::IntoIter<(K, V)>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_vec().into_iter()
}
}
impl<'a, K, V> IntoIterator for &'a FrozenMap<K, V> {
type Item = &'a (K, V);
type IntoIter = std::slice::Iter<'a, (K, V)>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<'a, K, V> IntoIterator for &'a mut FrozenMap<K, V> {
type Item = &'a mut (K, V);
type IntoIter = std::slice::IterMut<'a, (K, V)>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter_mut()
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, get_size2::GetSize, salsa::Update)]
struct FrozenValueIndex(u32);
impl Idx for FrozenValueIndex {
fn new(value: usize) -> Self {
assert!(u32::try_from(value).is_ok());
#[expect(clippy::cast_possible_truncation)]
Self(value as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}
/// Compact immutable key-value entries that deduplicate repeated values.
#[derive(Debug, Eq, PartialEq, salsa::Update, get_size2::GetSize)]
pub struct FrozenValueMap<K, V> {
entries: FrozenMap<K, FrozenValueIndex>,
values: Box<[V]>,
}
impl<K, V> FrozenValueMap<K, V> {
pub fn get(&self, key: &K) -> Option<&V>
where
K: Ord,
{
self.entries
.get(key)
.map(|index| &self.values[index.index()])
}
pub fn iter(&self) -> impl DoubleEndedIterator<Item = (K, V)> + ExactSizeIterator + '_
where
K: Copy,
V: Copy,
{
self.entries
.iter()
.map(|(key, index)| (*key, self.values[index.index()]))
}
pub fn map_values<F>(&mut self, mut map: F)
where
K: Copy + Ord,
V: Copy + Eq + Hash,
F: FnMut(K, V) -> V,
{
*self = self
.iter()
.map(|(key, value)| (key, map(key, value)))
.collect();
}
}
impl<K, V> FromIterator<(K, V)> for FrozenValueMap<K, V>
where
K: Ord,
V: Copy + Eq + Hash,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut source_entries = iter.into_iter().collect::<Vec<_>>();
source_entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
source_entries.dedup_by(|(left, _), (right, _)| left == right);
let mut values = Vec::new();
let mut value_indices = FxHashMap::default();
let entries = source_entries
.into_iter()
.map(|(key, value)| {
let index = *value_indices.entry(value).or_insert_with(|| {
let index = FrozenValueIndex::new(values.len());
values.push(value);
index
});
(key, index)
})
.collect::<Vec<_>>();
Self {
entries: FrozenMap(entries.into_boxed_slice()),
values: values.into_boxed_slice(),
}
}
}
impl<K, V, S> From<std::collections::HashMap<K, V, S>> for FrozenValueMap<K, V>
where
K: Ord,
V: Copy + Eq + Hash,
{
fn from(map: std::collections::HashMap<K, V, S>) -> Self {
map.into_iter().collect()
}
}
impl<K, V> Default for FrozenValueMap<K, V> {
fn default() -> Self {
Self {
entries: FrozenMap::default(),
values: Box::default(),
}
}
}
/// Compact immutable keys stored in ascending order.
///
/// Analysis builds these sets with hash sets, but after construction they only need membership
/// tests and iteration. A sorted slice avoids retaining hash-table capacity.
#[derive(Debug, Eq, PartialEq, salsa::Update, get_size2::GetSize)]
pub struct FrozenSet<K>(Box<[K]>);
impl<K: Ord, S> From<std::collections::HashSet<K, S>> for FrozenSet<K> {
fn from(set: std::collections::HashSet<K, S>) -> Self {
let mut entries = set.into_iter().collect::<Vec<_>>();
entries.sort_unstable();
Self(entries.into_boxed_slice())
}
}
impl<K: Ord> FrozenSet<K> {
pub fn contains(&self, key: &K) -> bool {
self.0.binary_search(key).is_ok()
}
}
impl<K> FrozenSet<K> {
pub fn iter(&self) -> std::slice::Iter<'_, K> {
self.0.iter()
}
}
impl<'a, K> IntoIterator for &'a FrozenSet<K> {
type Item = &'a K;
type IntoIter = std::slice::Iter<'a, K>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl<K> Default for FrozenSet<K> {
fn default() -> Self {
Self(Box::default())
}
}
#[cfg(test)]
mod tests {
use super::{FrozenMap, FrozenValueMap};
#[test]
fn frozen_value_map_deduplicates_values() {
let map = FrozenValueMap::from_iter([(3, [1; 4]), (1, [2; 4]), (2, [1; 4])]);
assert_eq!(map.values.len(), 2);
assert_eq!(map.get(&1), Some(&[2; 4]));
assert_eq!(map.get(&2), Some(&[1; 4]));
assert_eq!(
map.iter().collect::<Vec<_>>(),
vec![(1, [2; 4]), (2, [1; 4]), (3, [1; 4])]
);
}
#[test]
fn frozen_value_map_updates_and_rededuplicates_values() {
let mut map = FrozenValueMap::from_iter([(1, 10), (2, 20), (3, 30)]);
map.map_values(|_, _| 42);
assert_eq!(map.values.as_ref(), &[42]);
assert_eq!(
map.iter().collect::<Vec<_>>(),
vec![(1, 42), (2, 42), (3, 42)]
);
}
#[test]
fn frozen_value_map_uses_less_heap_for_repeated_large_values() {
let entries = [(1, [1; 8]), (2, [1; 8]), (3, [1; 8]), (4, [2; 8])];
let direct = FrozenMap::from_iter(entries);
let deduplicated = FrozenValueMap::from_iter(entries);
assert!(
ruff_memory_usage::heap_size(&deduplicated) < ruff_memory_usage::heap_size(&direct)
);
}
}