Created
May 27, 2025 21:51
-
-
Save momvart/2c5abb31bd89c59dd431339b36270be5 to your computer and use it in GitHub Desktop.
Propagates the tracing `Span` down to the iterators returned by functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tracing::Span; | |
/// Iterator adapter that enters a span on each iteration. | |
pub struct InstrumentedIter<I> { | |
iter: I, | |
span: Span, | |
} | |
impl<I> Iterator for InstrumentedIter<I> | |
where | |
I: Iterator, | |
{ | |
type Item = I::Item; | |
fn next(&mut self) -> Option<Self::Item> { | |
let _enter = self.span.enter(); | |
self.iter.next() | |
} | |
} | |
/// Extension trait for instrumenting iterators with a tracing span. | |
pub trait IteratorInstrumentExt: Iterator + Sized { | |
fn instrumented(self, span: Span) -> InstrumentedIter<Self> { | |
InstrumentedIter { iter: self, span } | |
} | |
} | |
impl<I: Iterator> IteratorInstrumentExt for I {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment