]> git.lizzy.rs Git - rust.git/blob - src/range_map.rs
Auto merge of #799 - rust-lang:rustup, r=RalfJung
[rust.git] / src / range_map.rs
1 //! Implements a map from integer indices to data.
2 //! Rather than storing data for every index, internally, this maps entire ranges to the data.
3 //! To this end, the APIs all work on ranges, not on individual integers. Ranges are split as
4 //! necessary (e.g., when [0,5) is first associated with X, and then [1,2) is mutated).
5 //! Users must not depend on whether a range is coalesced or not, even though this is observable
6 //! via the iteration APIs.
7
8 use std::ops;
9
10 use rustc::ty::layout::Size;
11
12 #[derive(Clone, Debug)]
13 struct Elem<T> {
14     /// The range covered by this element; never empty.
15     range: ops::Range<u64>,
16     /// The data stored for this element.
17     data: T,
18 }
19 #[derive(Clone, Debug)]
20 pub struct RangeMap<T> {
21     v: Vec<Elem<T>>,
22 }
23
24 impl<T> RangeMap<T> {
25     /// Creates a new `RangeMap` for the given size, and with the given initial value used for
26     /// the entire range.
27     #[inline(always)]
28     pub fn new(size: Size, init: T) -> RangeMap<T> {
29         let size = size.bytes();
30         let mut map = RangeMap { v: Vec::new() };
31         if size > 0 {
32             map.v.push(Elem {
33                 range: 0..size,
34                 data: init
35             });
36         }
37         map
38     }
39
40     /// Finds the index containing the given offset.
41     fn find_offset(&self, offset: u64) -> usize {
42         // We do a binary search.
43         let mut left = 0usize; // inclusive
44         let mut right = self.v.len(); // exclusive
45         loop {
46             debug_assert!(left < right, "find_offset: offset {} is out-of-bounds", offset);
47             let candidate = left.checked_add(right).unwrap() / 2;
48             let elem = &self.v[candidate];
49             if offset < elem.range.start {
50                 // We are too far right (offset is further left).
51                 debug_assert!(candidate < right); // we are making progress
52                 right = candidate;
53             } else if offset >= elem.range.end {
54                 // We are too far left (offset is further right).
55                 debug_assert!(candidate >= left); // we are making progress
56                 left = candidate+1;
57             } else {
58                 // This is it!
59                 return candidate;
60             }
61         }
62     }
63
64     /// Provides read-only iteration over everything in the given range. This does
65     /// *not* split items if they overlap with the edges. Do not use this to mutate
66     /// through interior mutability.
67     pub fn iter<'a>(&'a self, offset: Size, len: Size) -> impl Iterator<Item = &'a T> + 'a {
68         let offset = offset.bytes();
69         let len = len.bytes();
70         // Compute a slice starting with the elements we care about.
71         let slice: &[Elem<T>] = if len == 0 {
72                 // We just need any empty iterator. We don't even want to
73                 // yield the element that surrounds this position.
74                 &[]
75             } else {
76                 let first_idx = self.find_offset(offset);
77                 &self.v[first_idx..]
78             };
79         // The first offset that is not included any more.
80         let end = offset + len;
81         slice.iter()
82             .take_while(move |elem| elem.range.start < end)
83             .map(|elem| &elem.data)
84     }
85
86     pub fn iter_mut_all<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T> + 'a {
87         self.v.iter_mut().map(|elem| &mut elem.data)
88     }
89
90     // Splits the element situated at the given `index`, such that the 2nd one starts at offset
91     // `split_offset`. Do nothing if the element already starts there.
92     // Returns whether a split was necessary.
93     fn split_index(&mut self, index: usize, split_offset: u64) -> bool
94     where
95         T: Clone,
96     {
97         let elem = &mut self.v[index];
98         if split_offset == elem.range.start || split_offset == elem.range.end {
99             // Nothing to do.
100             return false;
101         }
102         debug_assert!(elem.range.contains(&split_offset),
103             "the `split_offset` is not in the element to be split");
104
105         // Now we really have to split. Reduce length of first element.
106         let second_range = split_offset..elem.range.end;
107         elem.range.end = split_offset;
108         // Copy the data, and insert second element.
109         let second = Elem {
110             range: second_range,
111             data: elem.data.clone(),
112         };
113         self.v.insert(index+1, second);
114         return true;
115     }
116
117     /// Provides mutable iteration over everything in the given range. As a side-effect,
118     /// this will split entries in the map that are only partially hit by the given range,
119     /// to make sure that when they are mutated, the effect is constrained to the given range.
120     /// Moreover, this will opportunistically merge neighbouring equal blocks.
121     pub fn iter_mut<'a>(
122         &'a mut self,
123         offset: Size,
124         len: Size,
125     ) -> impl Iterator<Item = &'a mut T> + 'a
126     where
127         T: Clone + PartialEq,
128     {
129         let offset = offset.bytes();
130         let len = len.bytes();
131         // Compute a slice containing exactly the elements we care about
132         let slice: &mut [Elem<T>] = if len == 0 {
133                 // We just need any empty iterator. We don't even want to
134                 // yield the element that surrounds this position, nor do
135                 // any splitting.
136                 &mut []
137             } else {
138                 // Make sure we got a clear beginning
139                 let mut first_idx = self.find_offset(offset);
140                 if self.split_index(first_idx, offset) {
141                     // The newly created 2nd element is ours
142                     first_idx += 1;
143                 }
144                 let first_idx = first_idx; // no more mutation
145                 // Find our end. Linear scan, but that's ok because the iteration
146                 // is doing the same linear scan anyway -- no increase in complexity.
147                 // We combine this scan with a scan for duplicates that we can merge, to reduce
148                 // the number of elements.
149                 // We stop searching after the first "block" of size 1, to avoid spending excessive
150                 // amounts of time on the merging.
151                 let mut equal_since_idx = first_idx;
152                 // Once we see too many non-mergeable blocks, we stop.
153                 // The initial value is chosen via... magic. Benchmarking and magic.
154                 let mut successful_merge_count = 3usize;
155                 let mut end_idx = first_idx; // when the loop is done, this is the first excluded element.
156                 loop {
157                     // Compute if `end` is the last element we need to look at.
158                     let done = self.v[end_idx].range.end >= offset+len;
159                     // We definitely need to include `end`, so move the index.
160                     end_idx += 1;
161                     debug_assert!(done || end_idx < self.v.len(), "iter_mut: end-offset {} is out-of-bounds", offset+len);
162                     // see if we want to merge everything in `equal_since..end` (exclusive at the end!)
163                     if successful_merge_count > 0 {
164                         if done || self.v[end_idx].data != self.v[equal_since_idx].data {
165                             // Everything in `equal_since..end` was equal. Make them just one element covering
166                             // the entire range.
167                             let removed_elems = end_idx - equal_since_idx - 1; // number of elements that we would remove
168                             if removed_elems > 0 {
169                                 // Adjust the range of the first element to cover all of them.
170                                 let equal_until = self.v[end_idx - 1].range.end; // end of range of last of the equal elements
171                                 self.v[equal_since_idx].range.end = equal_until;
172                                 // Delete the rest of them.
173                                 self.v.splice(equal_since_idx+1..end_idx, std::iter::empty());
174                                 // Adjust `end_idx` because we made the list shorter.
175                                 end_idx -= removed_elems;
176                                 // Adjust the count for the cutoff.
177                                 successful_merge_count += removed_elems;
178                             } else {
179                                 // Adjust the count for the cutoff.
180                                 successful_merge_count -= 1;
181                             }
182                             // Go on scanning for the next block starting here.
183                             equal_since_idx = end_idx;
184                         }
185                     }
186                     // Leave loop if this is the last element.
187                     if done {
188                         break;
189                     }
190                 }
191                 // Move to last included instead of first excluded index.
192                 let end_idx = end_idx-1;
193                 // We need to split the end as well. Even if this performs a
194                 // split, we don't have to adjust our index as we only care about
195                 // the first part of the split.
196                 self.split_index(end_idx, offset+len);
197                 // Now we yield the slice. `end` is inclusive.
198                 &mut self.v[first_idx..=end_idx]
199             };
200         slice.iter_mut().map(|elem| &mut elem.data)
201     }
202 }
203
204 #[cfg(test)]
205 mod tests {
206     use super::*;
207
208     /// Query the map at every offset in the range and collect the results.
209     fn to_vec<T: Copy>(map: &RangeMap<T>, offset: u64, len: u64) -> Vec<T> {
210         (offset..offset + len)
211             .into_iter()
212             .map(|i| map
213                 .iter(Size::from_bytes(i), Size::from_bytes(1))
214                 .next()
215                 .map(|&t| t)
216                 .unwrap()
217             )
218             .collect()
219     }
220
221     #[test]
222     fn basic_insert() {
223         let mut map = RangeMap::<i32>::new(Size::from_bytes(20), -1);
224         // Insert.
225         for x in map.iter_mut(Size::from_bytes(10), Size::from_bytes(1)) {
226             *x = 42;
227         }
228         // Check.
229         assert_eq!(to_vec(&map, 10, 1), vec![42]);
230         assert_eq!(map.v.len(), 3);
231
232         // Insert with size 0.
233         for x in map.iter_mut(Size::from_bytes(10), Size::from_bytes(0)) {
234             *x = 19;
235         }
236         for x in map.iter_mut(Size::from_bytes(11), Size::from_bytes(0)) {
237             *x = 19;
238         }
239         assert_eq!(to_vec(&map, 10, 2), vec![42, -1]);
240         assert_eq!(map.v.len(), 3);
241     }
242
243     #[test]
244     fn gaps() {
245         let mut map = RangeMap::<i32>::new(Size::from_bytes(20), -1);
246         for x in map.iter_mut(Size::from_bytes(11), Size::from_bytes(1)) {
247             *x = 42;
248         }
249         for x in map.iter_mut(Size::from_bytes(15), Size::from_bytes(1)) {
250             *x = 43;
251         }
252         assert_eq!(map.v.len(), 5);
253         assert_eq!(
254             to_vec(&map, 10, 10),
255             vec![-1, 42, -1, -1, -1, 43, -1, -1, -1, -1]
256         );
257
258         for x in map.iter_mut(Size::from_bytes(10), Size::from_bytes(10)) {
259             if *x < 42 {
260                 *x = 23;
261             }
262         }
263         assert_eq!(map.v.len(), 6);
264         assert_eq!(
265             to_vec(&map, 10, 10),
266             vec![23, 42, 23, 23, 23, 43, 23, 23, 23, 23]
267         );
268         assert_eq!(to_vec(&map, 13, 5), vec![23, 23, 43, 23, 23]);
269
270
271         for x in map.iter_mut(Size::from_bytes(15), Size::from_bytes(5)) {
272             *x = 19;
273         }
274         assert_eq!(map.v.len(), 6);
275         assert_eq!(
276             to_vec(&map, 10, 10),
277             vec![23, 42, 23, 23, 23, 19, 19, 19, 19, 19]
278         );
279         // Should be seeing two blocks with 19.
280         assert_eq!(map.iter(Size::from_bytes(15), Size::from_bytes(2))
281             .map(|&t| t).collect::<Vec<_>>(), vec![19, 19]);
282
283         // A NOP `iter_mut` should trigger merging.
284         for _ in map.iter_mut(Size::from_bytes(15), Size::from_bytes(5)) { }
285         assert_eq!(map.v.len(), 5);
286         assert_eq!(
287             to_vec(&map, 10, 10),
288             vec![23, 42, 23, 23, 23, 19, 19, 19, 19, 19]
289         );
290     }
291 }