| 1 | //! The merge algorithm. This one can merge unequal slices, allocating an n/2 |
| 2 | //! sized temporary slice of the same type. Naturally, it can only merge slices |
| 3 | //! that are themselves already sorted. |
| 4 | |
| 5 | #[cfg(test)] |
| 6 | mod tests; |
| 7 | |
| 8 | use crate::gallop::{self, gallop_left, gallop_right}; |
| 9 | use crate::Comparator; |
| 10 | use alloc::vec::Vec; |
| 11 | use core::mem::ManuallyDrop; |
| 12 | use core::ptr; |
| 13 | |
| 14 | /// Merge implementation switch. |
| 15 | pub(crate) fn merge<T, C: Comparator<T>>( |
| 16 | list: &mut [T], |
| 17 | mut first_len: usize, |
| 18 | cmp: &C, |
| 19 | ) -> Result<(), C::Error> { |
| 20 | if first_len == 0 { |
| 21 | return Ok(()); |
| 22 | } |
| 23 | let (first, second) = list.split_at_mut(first_len); |
| 24 | let second_len = gallop_left(first.last().unwrap(), second, gallop::Mode::Reverse, cmp)?; |
| 25 | let first_of_second = match second.get(0) { |
| 26 | Some(x) => x, |
| 27 | None => return Ok(()), |
| 28 | }; |
| 29 | let first_off = gallop_right(first_of_second, first, gallop::Mode::Forward, cmp)?; |
| 30 | first_len -= first_off; |
| 31 | if first_len == 0 { |
| 32 | return Ok(()); |
| 33 | } |
| 34 | |
| 35 | let nlist = &mut list[first_off..][..first_len + second_len]; |
| 36 | if first_len > second_len { |
| 37 | merge_hi(nlist, first_len, second_len, cmp) |
| 38 | } else { |
| 39 | merge_lo(nlist, first_len, cmp) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /// The number of times any one run can win before we try galloping. |
| 44 | /// Change this during testing. |
| 45 | const MIN_GALLOP: usize = 7; |
| 46 | |
| 47 | /// Merge implementation used when the first run is smaller than the second. |
| 48 | pub(crate) fn merge_lo<T, C: Comparator<T>>( |
| 49 | list: &mut [T], |
| 50 | first_len: usize, |
| 51 | cmp: &C, |
| 52 | ) -> Result<(), C::Error> { |
| 53 | MergeLo::new(list, first_len, cmp).merge() |
| 54 | } |
| 55 | |
| 56 | #[inline(always)] |
| 57 | fn md_as_inner<T>(x: &[ManuallyDrop<T>]) -> &[T] { |
| 58 | // SAFETY: ManuallyDrop<T> is repr(transparent) over T |
| 59 | unsafe { &*(x as *const [_] as *const [T]) } |
| 60 | } |
| 61 | |
| 62 | /// Implementation of `merge_lo`. We need to have an object in order to |
| 63 | /// implement panic safety. |
| 64 | struct MergeLo<'a, T, C: Comparator<T>> { |
| 65 | list_len: usize, |
| 66 | first_pos: usize, |
| 67 | first_len: usize, |
| 68 | second_pos: usize, |
| 69 | dest_pos: usize, |
| 70 | list: &'a mut [T], |
| 71 | tmp: Vec<ManuallyDrop<T>>, |
| 72 | cmp: &'a C, |
| 73 | } |
| 74 | impl<'a, T, C: Comparator<T>> MergeLo<'a, T, C> { |
| 75 | /// Constructor for a lower merge. |
| 76 | fn new(list: &'a mut [T], first_len: usize, cmp: &'a C) -> Self { |
| 77 | let mut ret_val = MergeLo { |
| 78 | list_len: list.len(), |
| 79 | first_pos: 0, |
| 80 | first_len, |
| 81 | second_pos: first_len, |
| 82 | dest_pos: 0, |
| 83 | list, |
| 84 | tmp: Vec::with_capacity(first_len), |
| 85 | cmp, |
| 86 | }; |
| 87 | // First, move the smallest run into temporary storage, leaving the |
| 88 | // original contents uninitialized. |
| 89 | unsafe { |
| 90 | ret_val.tmp.set_len(first_len); |
| 91 | ptr::copy_nonoverlapping( |
| 92 | ret_val.list.as_ptr() as *const ManuallyDrop<T>, |
| 93 | ret_val.tmp.as_mut_ptr(), |
| 94 | first_len, |
| 95 | ); |
| 96 | } |
| 97 | ret_val |
| 98 | } |
| 99 | /// Perform the one-by-one comparison and insertion. |
| 100 | fn merge(mut self) -> Result<(), C::Error> { |
| 101 | let cmp = self.cmp; |
| 102 | let mut first_count = 0; |
| 103 | let mut second_count = 0; |
| 104 | while self.second_pos > self.dest_pos && self.second_pos < self.list_len { |
| 105 | debug_assert!(self.first_pos + (self.second_pos - self.first_len) == self.dest_pos); |
| 106 | if (second_count | first_count) < MIN_GALLOP { |
| 107 | // One-at-a-time mode. |
| 108 | unsafe { |
| 109 | if cmp.is_gt( |
| 110 | self.tmp.get_unchecked(self.first_pos), |
| 111 | self.list.get_unchecked(self.second_pos), |
| 112 | )? { |
| 113 | ptr::copy_nonoverlapping( |
| 114 | self.list.get_unchecked(self.second_pos), |
| 115 | self.list.get_unchecked_mut(self.dest_pos), |
| 116 | 1, |
| 117 | ); |
| 118 | self.second_pos += 1; |
| 119 | second_count += 1; |
| 120 | first_count = 0; |
| 121 | } else { |
| 122 | ptr::copy_nonoverlapping( |
| 123 | &**self.tmp.get_unchecked(self.first_pos), |
| 124 | self.list.get_unchecked_mut(self.dest_pos), |
| 125 | 1, |
| 126 | ); |
| 127 | self.first_pos += 1; |
| 128 | first_count += 1; |
| 129 | second_count = 0; |
| 130 | } |
| 131 | } |
| 132 | self.dest_pos += 1; |
| 133 | } else { |
| 134 | // Galloping mode. |
| 135 | second_count = gallop_left( |
| 136 | unsafe { md_as_inner(&self.tmp).get_unchecked(self.first_pos) }, |
| 137 | &self.list[self.second_pos..], |
| 138 | gallop::Mode::Forward, |
| 139 | cmp, |
| 140 | )?; |
| 141 | unsafe { |
| 142 | ptr::copy( |
| 143 | self.list.get_unchecked(self.second_pos), |
| 144 | self.list.get_unchecked_mut(self.dest_pos), |
| 145 | second_count, |
| 146 | ) |
| 147 | } |
| 148 | self.dest_pos += second_count; |
| 149 | self.second_pos += second_count; |
| 150 | debug_assert!(self.first_pos + (self.second_pos - self.first_len) == self.dest_pos); |
| 151 | if self.second_pos > self.dest_pos && self.second_pos < self.list_len { |
| 152 | first_count = gallop_right( |
| 153 | unsafe { self.list.get_unchecked(self.second_pos) }, |
| 154 | md_as_inner(&self.tmp[self.first_pos..]), |
| 155 | gallop::Mode::Forward, |
| 156 | cmp, |
| 157 | )?; |
| 158 | unsafe { |
| 159 | ptr::copy_nonoverlapping( |
| 160 | md_as_inner(&self.tmp).get_unchecked(self.first_pos), |
| 161 | self.list.get_unchecked_mut(self.dest_pos), |
| 162 | first_count, |
| 163 | ) |
| 164 | }; |
| 165 | self.dest_pos += first_count; |
| 166 | self.first_pos += first_count; |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | Ok(()) |
| 171 | } |
| 172 | } |
| 173 | impl<'a, T, C: Comparator<T>> Drop for MergeLo<'a, T, C> { |
| 174 | /// Copy all remaining items in the temporary storage into the list. |
| 175 | /// If the comparator panics, the result will not be sorted, but will still |
| 176 | /// contain no duplicates or uninitialized spots. |
| 177 | fn drop(&mut self) { |
| 178 | unsafe { |
| 179 | // Make sure that the entire tmp storage is consumed. Since there are no uninitialized |
| 180 | // spaces before dest_pos, and no uninitialized space after first_pos, this will ensure |
| 181 | // that there are no uninitialized spaces inside the slice after we drop. Thus, the |
| 182 | // function is safe. |
| 183 | if self.first_pos < self.first_len { |
| 184 | ptr::copy_nonoverlapping( |
| 185 | self.tmp.get_unchecked(self.first_pos) as *const _ as *const T, |
| 186 | self.list.get_unchecked_mut(self.dest_pos), |
| 187 | self.first_len - self.first_pos, |
| 188 | ); |
| 189 | } |
| 190 | // The temporary storage is now full of nothing but uninitialized. |
| 191 | // We want to deallocate the space, but not call the destructors. |
| 192 | self.tmp.set_len(0); |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /// Merge implementation used when the first run is larger than the second. |
| 198 | pub(crate) fn merge_hi<T, C: Comparator<T>>( |
| 199 | list: &mut [T], |
| 200 | first_len: usize, |
| 201 | second_len: usize, |
| 202 | cmp: &C, |
| 203 | ) -> Result<(), C::Error> { |
| 204 | MergeHi::new(list, first_len, second_len, cmp).merge() |
| 205 | } |
| 206 | |
| 207 | /// Implementation of `merge_hi`. We need to have an object in order to |
| 208 | /// implement panic safety. |
| 209 | struct MergeHi<'a, T, C: Comparator<T>> { |
| 210 | first_pos: isize, |
| 211 | second_pos: isize, |
| 212 | dest_pos: isize, |
| 213 | list: &'a mut [T], |
| 214 | tmp: Vec<ManuallyDrop<T>>, |
| 215 | cmp: &'a C, |
| 216 | } |
| 217 | |
| 218 | impl<'a, T, C: Comparator<T>> MergeHi<'a, T, C> { |
| 219 | /// Constructor for a higher merge. |
| 220 | fn new(list: &'a mut [T], first_len: usize, second_len: usize, cmp: &'a C) -> Self { |
| 221 | let mut ret_val = MergeHi { |
| 222 | first_pos: first_len as isize - 1, |
| 223 | second_pos: second_len as isize - 1, |
| 224 | dest_pos: list.len() as isize - 1, |
| 225 | list, |
| 226 | tmp: Vec::with_capacity(second_len), |
| 227 | cmp, |
| 228 | }; |
| 229 | // First, move the smallest run into temporary storage, leaving the |
| 230 | // original contents uninitialized. |
| 231 | unsafe { |
| 232 | ret_val.tmp.set_len(second_len); |
| 233 | ptr::copy_nonoverlapping( |
| 234 | ret_val.list.as_ptr().add(first_len), |
| 235 | ret_val.tmp.as_mut_ptr() as *mut T, |
| 236 | second_len, |
| 237 | ); |
| 238 | } |
| 239 | ret_val |
| 240 | } |
| 241 | /// Perform the one-by-one comparison and insertion. |
| 242 | fn merge(mut self) -> Result<(), C::Error> { |
| 243 | let cmp = self.cmp; |
| 244 | let mut first_count: usize = 0; |
| 245 | let mut second_count: usize = 0; |
| 246 | while self.first_pos < self.dest_pos && self.first_pos >= 0 { |
| 247 | debug_assert!(self.first_pos + self.second_pos + 1 == self.dest_pos); |
| 248 | if (second_count | first_count) < MIN_GALLOP { |
| 249 | // One-at-a-time mode. |
| 250 | unsafe { |
| 251 | if cmp.is_gt( |
| 252 | self.list.get_unchecked(self.first_pos as usize), |
| 253 | self.tmp.get_unchecked(self.second_pos as usize), |
| 254 | )? { |
| 255 | ptr::copy_nonoverlapping( |
| 256 | self.list.get_unchecked(self.first_pos as usize), |
| 257 | self.list.get_unchecked_mut(self.dest_pos as usize), |
| 258 | 1, |
| 259 | ); |
| 260 | self.first_pos -= 1; |
| 261 | } else { |
| 262 | ptr::copy_nonoverlapping( |
| 263 | md_as_inner(&self.tmp).get_unchecked(self.second_pos as usize), |
| 264 | self.list.get_unchecked_mut(self.dest_pos as usize), |
| 265 | 1, |
| 266 | ); |
| 267 | self.second_pos -= 1; |
| 268 | } |
| 269 | } |
| 270 | self.dest_pos -= 1; |
| 271 | } else { |
| 272 | // Galloping mode. |
| 273 | first_count = self.first_pos as usize + 1 |
| 274 | - gallop_right( |
| 275 | unsafe { md_as_inner(&self.tmp).get_unchecked(self.second_pos as usize) }, |
| 276 | &self.list[..=self.first_pos as usize], |
| 277 | gallop::Mode::Reverse, |
| 278 | cmp, |
| 279 | )?; |
| 280 | unsafe { |
| 281 | copy_backwards( |
| 282 | self.list.get_unchecked(self.first_pos as usize), |
| 283 | self.list.get_unchecked_mut(self.dest_pos as usize), |
| 284 | first_count, |
| 285 | ) |
| 286 | } |
| 287 | self.dest_pos -= first_count as isize; |
| 288 | self.first_pos -= first_count as isize; |
| 289 | debug_assert!(self.first_pos + self.second_pos + 1 == self.dest_pos); |
| 290 | if self.first_pos < self.dest_pos && self.first_pos >= 0 { |
| 291 | second_count = self.second_pos as usize + 1 |
| 292 | - gallop_left( |
| 293 | unsafe { self.list.get_unchecked(self.first_pos as usize) }, |
| 294 | md_as_inner(&self.tmp[..=self.second_pos as usize]), |
| 295 | gallop::Mode::Reverse, |
| 296 | cmp, |
| 297 | )?; |
| 298 | unsafe { |
| 299 | copy_nonoverlapping_backwards( |
| 300 | md_as_inner(&self.tmp).get_unchecked(self.second_pos as usize), |
| 301 | self.list.get_unchecked_mut(self.dest_pos as usize), |
| 302 | second_count, |
| 303 | ) |
| 304 | } |
| 305 | self.dest_pos -= second_count as isize; |
| 306 | self.second_pos -= second_count as isize; |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | Ok(()) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// Perform a backwards `ptr::copy_nonoverlapping`. Behave identically when size = 1, but behave |
| 315 | /// differently all other times |
| 316 | unsafe fn copy_backwards<T>(src: *const T, dest: *mut T, size: usize) { |
| 317 | ptr::copy( |
| 318 | src.sub(size.wrapping_sub(1)), |
| 319 | dest.sub(size.wrapping_sub(1)), |
| 320 | size, |
| 321 | ) |
| 322 | } |
| 323 | |
| 324 | /// Perform a backwards `ptr::copy_nonoverlapping`. Behave identically when size = 1, but behave |
| 325 | /// differently all other times |
| 326 | unsafe fn copy_nonoverlapping_backwards<T>(src: *const T, dest: *mut T, size: usize) { |
| 327 | ptr::copy_nonoverlapping( |
| 328 | src.sub(size.wrapping_sub(1)), |
| 329 | dest.sub(size.wrapping_sub(1)), |
| 330 | size, |
| 331 | ) |
| 332 | } |
| 333 | |
| 334 | impl<'a, T, C: Comparator<T>> Drop for MergeHi<'a, T, C> { |
| 335 | /// Copy all remaining items in the temporary storage into the list. |
| 336 | /// If the comparator panics, the result will not be sorted, but will still |
| 337 | /// contain no duplicates or uninitialized spots. |
| 338 | fn drop(&mut self) { |
| 339 | unsafe { |
| 340 | // Make sure that the entire tmp storage is consumed. Since there are no uninitialized |
| 341 | // spaces before dest_pos, and no uninitialized space after first_pos, this will ensure |
| 342 | // that there are no uninitialized spaces inside the slice after we drop. Thus, the |
| 343 | // function is safe. |
| 344 | if self.second_pos >= 0 { |
| 345 | copy_nonoverlapping_backwards( |
| 346 | md_as_inner(&self.tmp).get_unchecked(self.second_pos as usize), |
| 347 | self.list.get_unchecked_mut(self.dest_pos as usize), |
| 348 | self.second_pos as usize + 1, |
| 349 | ); |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | } |