Skip to content

Commit 08c3d48

Browse files
authored
Add attach method to Contextualized (#1277)
1 parent 16a866e commit 08c3d48

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

opentelemetry-contrib/src/trace/context.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::TracerSource;
22
use opentelemetry::{
33
trace::{SpanBuilder, TraceContextExt as _, Tracer as _},
4-
Context,
4+
Context, ContextGuard,
55
};
66
use std::{
77
fmt::{Debug, Formatter},
@@ -129,6 +129,12 @@ impl<T> Contextualized<T> {
129129
pub fn into_inner(self) -> (T, Option<Context>) {
130130
(self.0, self.1)
131131
}
132+
133+
/// Attach the contained context if it exists and return both the
134+
/// associated value and an optional guard for the attached context.
135+
pub fn attach(self) -> (T, Option<ContextGuard>) {
136+
(self.0, self.1.map(|cx| cx.attach()))
137+
}
132138
}
133139

134140
impl<T: Clone> Clone for Contextualized<T> {
@@ -159,3 +165,20 @@ impl<T> DerefMut for Contextualized<T> {
159165
&mut self.0
160166
}
161167
}
168+
169+
#[cfg(test)]
170+
mod tests {
171+
use super::*;
172+
173+
#[test]
174+
fn cover_contextualized() {
175+
let cx = Contextualized::new(17, None);
176+
let (i, cx) = cx.into_inner();
177+
assert_eq!(i, 17);
178+
assert!(cx.is_none());
179+
180+
let cx = Contextualized::pass_thru(17);
181+
let (i, _guard) = cx.attach();
182+
assert_eq!(i, 17);
183+
}
184+
}

0 commit comments

Comments
 (0)