Drain up to `max` items into the provided vector. Returns the count drained. More efficient than calling `try_pop` in a loop because it batches the atomic tail load.
(&mut self, buf: &mut Vec<T>, max: usize)
| 269 | /// More efficient than calling `try_pop` in a loop because it batches the |
| 270 | /// atomic tail load. |
| 271 | pub fn drain_into(&mut self, buf: &mut Vec<T>, max: usize) -> usize { |
| 272 | let head = self.shared.head.value.load(Ordering::Relaxed); |
| 273 | self.cached_tail = self.shared.tail.value.load(Ordering::Acquire); |
| 274 | |
| 275 | let available = self.cached_tail.wrapping_sub(head) as usize; |
| 276 | let count = available.min(max); |
| 277 | |
| 278 | for i in 0..count { |
| 279 | let idx = ((head.wrapping_add(i as u64)) as usize) & self.shared.mask; |
| 280 | // SAFETY: same as try_pop — we've verified these slots are occupied. |
| 281 | let value = unsafe { (*self.shared.slots[idx].get()).take() }; |
| 282 | buf.push(value.expect("BUG: slot was None during drain")); |
| 283 | } |
| 284 | |
| 285 | if count > 0 { |
| 286 | self.shared |
| 287 | .head |
| 288 | .value |
| 289 | .store(head.wrapping_add(count as u64), Ordering::Release); |
| 290 | self.shared.metrics.record_pops(count as u64); |
| 291 | } |
| 292 | |
| 293 | count |
| 294 | } |
| 295 | |
| 296 | /// Returns the number of items currently in the queue. |
| 297 | pub fn len(&self) -> usize { |