Skip to content

Commit

Permalink
Add attach method to Contextualized (#1277)
Browse files Browse the repository at this point in the history
  • Loading branch information
shaun-cox authored Sep 25, 2023
1 parent 16a866e commit 08c3d48
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion opentelemetry-contrib/src/trace/context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::TracerSource;
use opentelemetry::{
trace::{SpanBuilder, TraceContextExt as _, Tracer as _},
Context,
Context, ContextGuard,
};
use std::{
fmt::{Debug, Formatter},
Expand Down Expand Up @@ -129,6 +129,12 @@ impl<T> Contextualized<T> {
pub fn into_inner(self) -> (T, Option<Context>) {
(self.0, self.1)
}

/// Attach the contained context if it exists and return both the
/// associated value and an optional guard for the attached context.
pub fn attach(self) -> (T, Option<ContextGuard>) {
(self.0, self.1.map(|cx| cx.attach()))
}
}

impl<T: Clone> Clone for Contextualized<T> {
Expand Down Expand Up @@ -159,3 +165,20 @@ impl<T> DerefMut for Contextualized<T> {
&mut self.0
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn cover_contextualized() {
let cx = Contextualized::new(17, None);
let (i, cx) = cx.into_inner();
assert_eq!(i, 17);
assert!(cx.is_none());

let cx = Contextualized::pass_thru(17);
let (i, _guard) = cx.attach();
assert_eq!(i, 17);
}
}

0 comments on commit 08c3d48

Please sign in to comment.