508 /// Yields (key, value) pairs for everything in the given section |
508 /// Yields (key, value) pairs for everything in the given section |
509 pub fn iter_section<'a>( |
509 pub fn iter_section<'a>( |
510 &'a self, |
510 &'a self, |
511 section: &'a [u8], |
511 section: &'a [u8], |
512 ) -> impl Iterator<Item = (&[u8], &[u8])> + 'a { |
512 ) -> impl Iterator<Item = (&[u8], &[u8])> + 'a { |
513 // TODO: Use `Iterator`’s `.peekable()` when its `peek_mut` is |
|
514 // available: |
|
515 // https://doc.rust-lang.org/nightly/std/iter/struct.Peekable.html#method.peek_mut |
|
516 struct Peekable<I: Iterator> { |
|
517 iter: I, |
|
518 /// Remember a peeked value, even if it was None. |
|
519 peeked: Option<Option<I::Item>>, |
|
520 } |
|
521 |
|
522 impl<I: Iterator> Peekable<I> { |
|
523 fn new(iter: I) -> Self { |
|
524 Self { iter, peeked: None } |
|
525 } |
|
526 |
|
527 fn next(&mut self) { |
|
528 self.peeked = None |
|
529 } |
|
530 |
|
531 fn peek_mut(&mut self) -> Option<&mut I::Item> { |
|
532 let iter = &mut self.iter; |
|
533 self.peeked.get_or_insert_with(|| iter.next()).as_mut() |
|
534 } |
|
535 } |
|
536 |
|
537 // Deduplicate keys redefined in multiple layers |
513 // Deduplicate keys redefined in multiple layers |
538 let mut keys_already_seen = HashSet::new(); |
514 let mut keys_already_seen = HashSet::new(); |
539 let mut key_is_new = |
515 let mut key_is_new = |
540 move |&(key, _value): &(&'a [u8], &'a [u8])| -> bool { |
516 move |&(key, _value): &(&'a [u8], &'a [u8])| -> bool { |
541 keys_already_seen.insert(key) |
517 keys_already_seen.insert(key) |
542 }; |
518 }; |
543 // This is similar to `flat_map` + `filter_map`, except with a single |
519 // This is similar to `flat_map` + `filter_map`, except with a single |
544 // closure that owns `key_is_new` (and therefore the |
520 // closure that owns `key_is_new` (and therefore the |
545 // `keys_already_seen` set): |
521 // `keys_already_seen` set): |
546 let mut layer_iters = Peekable::new( |
522 let mut layer_iters = self |
547 self.layers |
523 .layers |
548 .iter() |
524 .iter() |
549 .rev() |
525 .rev() |
550 .map(move |layer| layer.iter_section(section)), |
526 .map(move |layer| layer.iter_section(section)) |
551 ); |
527 .peekable(); |
552 std::iter::from_fn(move || loop { |
528 std::iter::from_fn(move || loop { |
553 if let Some(pair) = layer_iters.peek_mut()?.find(&mut key_is_new) { |
529 if let Some(pair) = layer_iters.peek_mut()?.find(&mut key_is_new) { |
554 return Some(pair); |
530 return Some(pair); |
555 } else { |
531 } else { |
556 layer_iters.next(); |
532 layer_iters.next(); |