1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! # Text Propagator
//!
//! `TextMapPropagator` is a formatter to serialize and deserialize a value into a
//! text format.
use crate::{
    propagation::{Extractor, Injector},
    Context,
};
use std::fmt::Debug;
use std::slice;

/// Methods to inject and extract a value as text into injectors and extractors that travel
/// in-band across process boundaries.
pub trait TextMapPropagator: Debug {
    /// Properly encodes the values of the current [`Context`] and injects them into
    /// the [`Injector`].
    ///
    /// [`Context`]: crate::Context
    /// [`Injector`]: crate::propagation::Injector
    fn inject(&self, injector: &mut dyn Injector) {
        self.inject_context(&Context::current(), injector)
    }

    /// Properly encodes the values of the [`Context`] and injects them into the
    /// [`Injector`].
    ///
    /// [`Context`]: crate::Context
    /// [`Injector`]: crate::propagation::Injector
    fn inject_context(&self, cx: &Context, injector: &mut dyn Injector);

    /// Retrieves encoded data using the provided [`Extractor`]. If no data for this
    /// format was retrieved OR if the retrieved data is invalid, then the current
    /// [`Context`] is returned.
    ///
    /// [`Context`]: crate::Context
    /// [`Injector`]: crate::propagation::Extractor
    fn extract(&self, extractor: &dyn Extractor) -> Context {
        self.extract_with_context(&Context::current(), extractor)
    }

    /// Retrieves encoded data using the provided [`Extractor`]. If no data for this
    /// format was retrieved OR if the retrieved data is invalid, then the given
    /// [`Context`] is returned.
    ///
    /// [`Context`]: crate::Context
    /// [`Injector`]: crate::propagation::Extractor
    fn extract_with_context(&self, cx: &Context, extractor: &dyn Extractor) -> Context;

    /// Returns iter of fields used by [`TextMapPropagator`]
    ///
    fn fields(&self) -> FieldIter<'_>;
}

/// An iterator over fields of a [`TextMapPropagator`]
///
#[derive(Debug)]
pub struct FieldIter<'a>(slice::Iter<'a, String>);

impl<'a> FieldIter<'a> {
    /// Create a new `FieldIter` from a slice of propagator fields
    pub fn new(fields: &'a [String]) -> Self {
        FieldIter(fields.iter())
    }
}

impl<'a> Iterator for FieldIter<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|field| field.as_str())
    }
}