Skip to main content

prometheus_client/
encoding.rs

1//! Exposition format implementations.
2
3#![allow(deprecated)]
4
5pub use prometheus_client_derive_encode::*;
6
7use crate::metrics::exemplar::Exemplar;
8use crate::metrics::MetricType;
9use crate::registry::{Prefix, Unit};
10use std::borrow::Cow;
11use std::collections::HashMap;
12use std::fmt::Write;
13use std::ops::Deref;
14use std::rc::Rc;
15use std::sync::Arc;
16use std::time::{SystemTime, UNIX_EPOCH};
17
18#[cfg(feature = "openmetrics_protobuf")]
19#[cfg_attr(docsrs, doc(cfg(feature = "openmetrics_protobuf")))]
20#[cfg_attr(
21    not(test),
22    deprecated(
23        note = "OpenMetrics protobuf support is deprecated. Use prometheus_protobuf instead."
24    )
25)]
26pub mod openmetrics_protobuf;
27#[cfg(feature = "prometheus_protobuf")]
28#[cfg_attr(docsrs, doc(cfg(feature = "prometheus_protobuf")))]
29pub mod prometheus_protobuf;
30pub mod prometheus_text;
31pub mod text;
32
33#[cfg(feature = "openmetrics_protobuf")]
34#[deprecated(note = "Use openmetrics_protobuf instead.")]
35pub use openmetrics_protobuf as protobuf;
36
37/// Native histogram fields shared by encoders.
38#[derive(Clone, Copy, Debug)]
39pub struct NativeHistogram<'a> {
40    /// Native histogram schema.
41    pub schema: i32,
42    /// Breadth of the zero bucket.
43    pub zero_threshold: f64,
44    /// Count in the zero bucket.
45    pub zero_count: u64,
46    /// Negative sparse buckets.
47    pub negative: NativeHistogramBuckets<'a>,
48    /// Positive sparse buckets.
49    pub positive: NativeHistogramBuckets<'a>,
50    /// Native histogram creation timestamp.
51    pub created: Option<SystemTime>,
52}
53
54/// Sparse bucket span and delta encoding for one side of a native histogram.
55#[derive(Clone, Copy, Debug)]
56pub struct NativeHistogramBuckets<'a> {
57    /// Bucket spans.
58    pub spans: &'a [(i32, u32)],
59    /// Bucket count deltas.
60    pub deltas: &'a [i64],
61}
62
63macro_rules! for_both_mut {
64    ($self:expr, $inner:ident, [$($variant:ident),+], $pattern:pat, $fn:expr) => {
65        match &mut $self.0 {
66            $($inner::$variant($pattern) => $fn,)+
67            #[cfg(feature = "openmetrics_protobuf")]
68            $inner::Protobuf($pattern) => $fn,
69            #[cfg(feature = "prometheus_protobuf")]
70            $inner::PrometheusProtobuf($pattern) => $fn,
71        }
72    };
73    ($self:expr, $inner:ident, $pattern:pat, $fn:expr) => {
74        for_both_mut!($self, $inner, [Text, PrometheusText], $pattern, $fn)
75    };
76}
77
78macro_rules! for_both {
79    ($self:expr, $inner:ident, [$($variant:ident),+], $pattern:pat, $fn:expr) => {
80        match $self.0 {
81            $($inner::$variant($pattern) => $fn,)+
82            #[cfg(feature = "openmetrics_protobuf")]
83            $inner::Protobuf($pattern) => $fn,
84            #[cfg(feature = "prometheus_protobuf")]
85            $inner::PrometheusProtobuf($pattern) => $fn,
86        }
87    };
88}
89
90/// Trait implemented by each metric type, e.g.
91/// [`Counter`](crate::metrics::counter::Counter), to implement its encoding in
92/// the OpenMetric text format.
93pub trait EncodeMetric {
94    /// Encode the given instance in the OpenMetrics text encoding.
95    // TODO: Lifetimes on MetricEncoder needed?
96    fn encode(&self, encoder: MetricEncoder) -> Result<(), std::fmt::Error>;
97
98    /// The OpenMetrics metric type of the instance.
99    // One can not use [`TypedMetric`] directly, as associated constants are not
100    // object safe and thus can not be used with dynamic dispatching.
101    fn metric_type(&self) -> MetricType;
102
103    /// Check if the metric is empty.
104    ///
105    /// An empty metric is a metric that has no data to encode, and thus should not have any
106    /// descriptor in the final output.
107    ///
108    /// By default, this returns `false`, ensuring the metric and its description is always
109    /// encoded.
110    fn is_empty(&self) -> bool {
111        false
112    }
113}
114
115impl EncodeMetric for Box<dyn EncodeMetric> {
116    fn encode(&self, encoder: MetricEncoder) -> Result<(), std::fmt::Error> {
117        self.deref().encode(encoder)
118    }
119
120    fn metric_type(&self) -> MetricType {
121        self.deref().metric_type()
122    }
123}
124
125/// Encoder for a Metric Descriptor.
126#[derive(Debug)]
127pub struct DescriptorEncoder<'a>(DescriptorEncoderInner<'a>);
128
129#[derive(Debug)]
130enum DescriptorEncoderInner<'a> {
131    Text(text::DescriptorEncoder<'a>),
132
133    PrometheusText(prometheus_text::DescriptorEncoder<'a>),
134
135    #[cfg(feature = "openmetrics_protobuf")]
136    Protobuf(openmetrics_protobuf::DescriptorEncoder<'a>),
137
138    #[cfg(feature = "prometheus_protobuf")]
139    PrometheusProtobuf(prometheus_protobuf::DescriptorEncoder<'a>),
140}
141
142impl<'a> From<text::DescriptorEncoder<'a>> for DescriptorEncoder<'a> {
143    fn from(e: text::DescriptorEncoder<'a>) -> Self {
144        Self(DescriptorEncoderInner::Text(e))
145    }
146}
147
148impl<'a> From<prometheus_text::DescriptorEncoder<'a>> for DescriptorEncoder<'a> {
149    fn from(e: prometheus_text::DescriptorEncoder<'a>) -> Self {
150        Self(DescriptorEncoderInner::PrometheusText(e))
151    }
152}
153
154#[cfg(feature = "openmetrics_protobuf")]
155impl<'a> From<openmetrics_protobuf::DescriptorEncoder<'a>> for DescriptorEncoder<'a> {
156    fn from(e: openmetrics_protobuf::DescriptorEncoder<'a>) -> Self {
157        Self(DescriptorEncoderInner::Protobuf(e))
158    }
159}
160
161#[cfg(feature = "prometheus_protobuf")]
162impl<'a> From<prometheus_protobuf::DescriptorEncoder<'a>> for DescriptorEncoder<'a> {
163    fn from(e: prometheus_protobuf::DescriptorEncoder<'a>) -> Self {
164        Self(DescriptorEncoderInner::PrometheusProtobuf(e))
165    }
166}
167
168impl DescriptorEncoder<'_> {
169    pub(crate) fn with_prefix_and_labels<'s>(
170        &'s mut self,
171        prefix: Option<&'s Prefix>,
172        labels: &'s [(Cow<'static, str>, Cow<'static, str>)],
173        // TODO: result needed?
174    ) -> DescriptorEncoder<'s> {
175        for_both_mut!(
176            self,
177            DescriptorEncoderInner,
178            e,
179            e.with_prefix_and_labels(prefix, labels).into()
180        )
181    }
182
183    /// Encode a descriptor.
184    pub fn encode_descriptor<'s>(
185        &'s mut self,
186        name: &'s str,
187        help: &str,
188        unit: Option<&'s Unit>,
189        metric_type: MetricType,
190    ) -> Result<MetricEncoder<'s>, std::fmt::Error> {
191        for_both_mut!(
192            self,
193            DescriptorEncoderInner,
194            e,
195            Ok(e.encode_descriptor(name, help, unit, metric_type)?.into())
196        )
197    }
198}
199
200/// Encoder for a metric.
201#[derive(Debug)]
202pub struct MetricEncoder<'a>(MetricEncoderInner<'a>);
203
204#[derive(Debug)]
205enum MetricEncoderInner<'a> {
206    Text(text::MetricEncoder<'a>),
207
208    PrometheusText(prometheus_text::MetricEncoder<'a>),
209
210    #[cfg(feature = "openmetrics_protobuf")]
211    Protobuf(openmetrics_protobuf::MetricEncoder<'a>),
212
213    #[cfg(feature = "prometheus_protobuf")]
214    PrometheusProtobuf(prometheus_protobuf::MetricEncoder<'a>),
215}
216
217impl<'a> From<text::MetricEncoder<'a>> for MetricEncoder<'a> {
218    fn from(e: text::MetricEncoder<'a>) -> Self {
219        Self(MetricEncoderInner::Text(e))
220    }
221}
222
223impl<'a> From<prometheus_text::MetricEncoder<'a>> for MetricEncoder<'a> {
224    fn from(e: prometheus_text::MetricEncoder<'a>) -> Self {
225        Self(MetricEncoderInner::PrometheusText(e))
226    }
227}
228
229#[cfg(feature = "openmetrics_protobuf")]
230impl<'a> From<openmetrics_protobuf::MetricEncoder<'a>> for MetricEncoder<'a> {
231    fn from(e: openmetrics_protobuf::MetricEncoder<'a>) -> Self {
232        Self(MetricEncoderInner::Protobuf(e))
233    }
234}
235
236#[cfg(feature = "prometheus_protobuf")]
237impl<'a> From<prometheus_protobuf::MetricEncoder<'a>> for MetricEncoder<'a> {
238    fn from(e: prometheus_protobuf::MetricEncoder<'a>) -> Self {
239        Self(MetricEncoderInner::PrometheusProtobuf(e))
240    }
241}
242
243impl MetricEncoder<'_> {
244    /// Encode a counter.
245    pub fn encode_counter<
246        S: EncodeLabelSet,
247        CounterValue: EncodeCounterValue,
248        ExemplarValue: EncodeExemplarValue,
249    >(
250        &mut self,
251        v: &CounterValue,
252        exemplar: Option<&Exemplar<S, ExemplarValue>>,
253    ) -> Result<(), std::fmt::Error> {
254        for_both_mut!(self, MetricEncoderInner, e, e.encode_counter(v, exemplar))
255    }
256
257    /// Encode a gauge.
258    pub fn encode_gauge<GaugeValue: EncodeGaugeValue>(
259        &mut self,
260        v: &GaugeValue,
261    ) -> Result<(), std::fmt::Error> {
262        for_both_mut!(self, MetricEncoderInner, e, e.encode_gauge(v))
263    }
264
265    /// Encode an info.
266    pub fn encode_info(&mut self, label_set: &impl EncodeLabelSet) -> Result<(), std::fmt::Error> {
267        for_both_mut!(self, MetricEncoderInner, e, e.encode_info(label_set))
268    }
269
270    /// Encode a histogram.
271    pub fn encode_histogram<S: EncodeLabelSet>(
272        &mut self,
273        sum: f64,
274        count: u64,
275        buckets: &[(f64, u64)],
276        exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
277    ) -> Result<(), std::fmt::Error> {
278        for_both_mut!(
279            self,
280            MetricEncoderInner,
281            e,
282            e.encode_histogram(sum, count, buckets, exemplars)
283        )
284    }
285
286    /// Encode a histogram that may have native buckets.
287    ///
288    /// Encoders without native histogram support encode the classic buckets when
289    /// present and reject native-only histograms.
290    pub fn encode_histogram_with_native<S: EncodeLabelSet>(
291        &mut self,
292        sum: f64,
293        count: u64,
294        buckets: &[(f64, u64)],
295        exemplars: Option<&HashMap<usize, Exemplar<S, f64>>>,
296        native: NativeHistogram<'_>,
297    ) -> Result<(), std::fmt::Error> {
298        for_both_mut!(
299            self,
300            MetricEncoderInner,
301            e,
302            e.encode_histogram_with_native(sum, count, buckets, exemplars, native)
303        )
304    }
305
306    /// Encode a metric family.
307    pub fn encode_family<'s, S: EncodeLabelSet>(
308        &'s mut self,
309        label_set: &'s S,
310    ) -> Result<MetricEncoder<'s>, std::fmt::Error> {
311        for_both_mut!(
312            self,
313            MetricEncoderInner,
314            e,
315            e.encode_family(label_set).map(Into::into)
316        )
317    }
318}
319
320/// An encodable label set.
321pub trait EncodeLabelSet {
322    /// Encode oneself into the given encoder.
323    fn encode(&self, encoder: &mut LabelSetEncoder) -> Result<(), std::fmt::Error>;
324}
325
326/// Encoder for a label set.
327#[derive(Debug)]
328pub struct LabelSetEncoder<'a>(LabelSetEncoderInner<'a>);
329
330#[derive(Debug)]
331enum LabelSetEncoderInner<'a> {
332    Text(text::LabelSetEncoder<'a>),
333    #[cfg(feature = "openmetrics_protobuf")]
334    Protobuf(openmetrics_protobuf::LabelSetEncoder<'a>),
335    #[cfg(feature = "prometheus_protobuf")]
336    PrometheusProtobuf(prometheus_protobuf::LabelSetEncoder<'a>),
337}
338
339impl<'a> From<text::LabelSetEncoder<'a>> for LabelSetEncoder<'a> {
340    fn from(e: text::LabelSetEncoder<'a>) -> Self {
341        Self(LabelSetEncoderInner::Text(e))
342    }
343}
344
345#[cfg(feature = "openmetrics_protobuf")]
346impl<'a> From<openmetrics_protobuf::LabelSetEncoder<'a>> for LabelSetEncoder<'a> {
347    fn from(e: openmetrics_protobuf::LabelSetEncoder<'a>) -> Self {
348        Self(LabelSetEncoderInner::Protobuf(e))
349    }
350}
351
352#[cfg(feature = "prometheus_protobuf")]
353impl<'a> From<prometheus_protobuf::LabelSetEncoder<'a>> for LabelSetEncoder<'a> {
354    fn from(e: prometheus_protobuf::LabelSetEncoder<'a>) -> Self {
355        Self(LabelSetEncoderInner::PrometheusProtobuf(e))
356    }
357}
358
359impl LabelSetEncoder<'_> {
360    /// Encode the given label.
361    pub fn encode_label(&mut self) -> LabelEncoder<'_> {
362        for_both_mut!(
363            self,
364            LabelSetEncoderInner,
365            [Text],
366            e,
367            e.encode_label().into()
368        )
369    }
370}
371
372impl<T: EncodeLabel, const N: usize> EncodeLabelSet for [T; N] {
373    fn encode(&self, encoder: &mut LabelSetEncoder) -> Result<(), std::fmt::Error> {
374        self.as_ref().encode(encoder)
375    }
376}
377
378impl<T: EncodeLabel> EncodeLabelSet for &[T] {
379    fn encode(&self, encoder: &mut LabelSetEncoder) -> Result<(), std::fmt::Error> {
380        if self.is_empty() {
381            return Ok(());
382        }
383
384        for label in self.iter() {
385            let encoder = encoder.encode_label();
386            label.encode(encoder)?
387        }
388
389        Ok(())
390    }
391}
392
393impl<T: EncodeLabel> EncodeLabelSet for Vec<T> {
394    fn encode(&self, encoder: &mut LabelSetEncoder) -> Result<(), std::fmt::Error> {
395        self.as_slice().encode(encoder)
396    }
397}
398
399impl<A, B> EncodeLabelSet for (A, B)
400where
401    A: EncodeLabelSet,
402    B: EncodeLabelSet,
403{
404    fn encode(&self, encoder: &mut LabelSetEncoder) -> Result<(), std::fmt::Error> {
405        let (a, b) = self;
406
407        a.encode(encoder)?;
408        b.encode(encoder)?;
409
410        Ok(())
411    }
412}
413
414/// Uninhabited type to represent the lack of a label set for a metric
415#[derive(Debug)]
416pub enum NoLabelSet {}
417
418impl EncodeLabelSet for NoLabelSet {
419    fn encode(&self, _encoder: &mut LabelSetEncoder) -> Result<(), std::fmt::Error> {
420        Ok(())
421    }
422}
423
424/// An encodable label.
425pub trait EncodeLabel {
426    /// Encode oneself into the given encoder.
427    fn encode(&self, encoder: LabelEncoder) -> Result<(), std::fmt::Error>;
428}
429
430/// Encoder for a label.
431#[derive(Debug)]
432pub struct LabelEncoder<'a>(LabelEncoderInner<'a>);
433
434#[derive(Debug)]
435enum LabelEncoderInner<'a> {
436    Text(text::LabelEncoder<'a>),
437    #[cfg(feature = "openmetrics_protobuf")]
438    Protobuf(openmetrics_protobuf::LabelEncoder<'a>),
439    #[cfg(feature = "prometheus_protobuf")]
440    PrometheusProtobuf(prometheus_protobuf::LabelEncoder<'a>),
441}
442
443impl<'a> From<text::LabelEncoder<'a>> for LabelEncoder<'a> {
444    fn from(e: text::LabelEncoder<'a>) -> Self {
445        Self(LabelEncoderInner::Text(e))
446    }
447}
448
449#[cfg(feature = "openmetrics_protobuf")]
450impl<'a> From<openmetrics_protobuf::LabelEncoder<'a>> for LabelEncoder<'a> {
451    fn from(e: openmetrics_protobuf::LabelEncoder<'a>) -> Self {
452        Self(LabelEncoderInner::Protobuf(e))
453    }
454}
455
456#[cfg(feature = "prometheus_protobuf")]
457impl<'a> From<prometheus_protobuf::LabelEncoder<'a>> for LabelEncoder<'a> {
458    fn from(e: prometheus_protobuf::LabelEncoder<'a>) -> Self {
459        Self(LabelEncoderInner::PrometheusProtobuf(e))
460    }
461}
462
463impl LabelEncoder<'_> {
464    /// Encode a label.
465    pub fn encode_label_key(&mut self) -> Result<LabelKeyEncoder<'_>, std::fmt::Error> {
466        for_both_mut!(
467            self,
468            LabelEncoderInner,
469            [Text],
470            e,
471            e.encode_label_key().map(Into::into)
472        )
473    }
474}
475
476impl<K: EncodeLabelKey, V: EncodeLabelValue> EncodeLabel for (K, V) {
477    fn encode(&self, mut encoder: LabelEncoder) -> Result<(), std::fmt::Error> {
478        let (key, value) = self;
479
480        let mut label_key_encoder = encoder.encode_label_key()?;
481        key.encode(&mut label_key_encoder)?;
482
483        let mut label_value_encoder = label_key_encoder.encode_label_value()?;
484        value.encode(&mut label_value_encoder)?;
485        label_value_encoder.finish()?;
486
487        Ok(())
488    }
489}
490
491/// An encodable label key.
492pub trait EncodeLabelKey {
493    /// Encode oneself into the given encoder.
494    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error>;
495}
496
497/// Encoder for a label key.
498#[derive(Debug)]
499pub struct LabelKeyEncoder<'a>(LabelKeyEncoderInner<'a>);
500
501#[derive(Debug)]
502enum LabelKeyEncoderInner<'a> {
503    Text(text::LabelKeyEncoder<'a>),
504    #[cfg(feature = "openmetrics_protobuf")]
505    Protobuf(openmetrics_protobuf::LabelKeyEncoder<'a>),
506    #[cfg(feature = "prometheus_protobuf")]
507    PrometheusProtobuf(prometheus_protobuf::LabelKeyEncoder<'a>),
508}
509
510impl<'a> From<text::LabelKeyEncoder<'a>> for LabelKeyEncoder<'a> {
511    fn from(e: text::LabelKeyEncoder<'a>) -> Self {
512        Self(LabelKeyEncoderInner::Text(e))
513    }
514}
515
516#[cfg(feature = "openmetrics_protobuf")]
517impl<'a> From<openmetrics_protobuf::LabelKeyEncoder<'a>> for LabelKeyEncoder<'a> {
518    fn from(e: openmetrics_protobuf::LabelKeyEncoder<'a>) -> Self {
519        Self(LabelKeyEncoderInner::Protobuf(e))
520    }
521}
522
523#[cfg(feature = "prometheus_protobuf")]
524impl<'a> From<prometheus_protobuf::LabelKeyEncoder<'a>> for LabelKeyEncoder<'a> {
525    fn from(e: prometheus_protobuf::LabelKeyEncoder<'a>) -> Self {
526        Self(LabelKeyEncoderInner::PrometheusProtobuf(e))
527    }
528}
529
530impl std::fmt::Write for LabelKeyEncoder<'_> {
531    fn write_str(&mut self, s: &str) -> std::fmt::Result {
532        for_both_mut!(self, LabelKeyEncoderInner, [Text], e, e.write_str(s))
533    }
534}
535
536impl<'a> LabelKeyEncoder<'a> {
537    /// Encode a label value.
538    pub fn encode_label_value(self) -> Result<LabelValueEncoder<'a>, std::fmt::Error> {
539        for_both!(
540            self,
541            LabelKeyEncoderInner,
542            [Text],
543            e,
544            e.encode_label_value().map(LabelValueEncoder::from)
545        )
546    }
547}
548
549impl EncodeLabelKey for &str {
550    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error> {
551        encoder.write_str(self)?;
552        Ok(())
553    }
554}
555
556impl EncodeLabelKey for String {
557    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error> {
558        EncodeLabelKey::encode(&self.as_str(), encoder)
559    }
560}
561
562impl EncodeLabelKey for Cow<'_, str> {
563    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error> {
564        EncodeLabelKey::encode(&self.as_ref(), encoder)
565    }
566}
567
568impl<T> EncodeLabelKey for Box<T>
569where
570    T: ?Sized,
571    for<'a> &'a T: EncodeLabelKey,
572{
573    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error> {
574        EncodeLabelKey::encode(&self.as_ref(), encoder)
575    }
576}
577
578impl<T> EncodeLabelKey for Arc<T>
579where
580    T: ?Sized,
581    for<'a> &'a T: EncodeLabelKey,
582{
583    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error> {
584        EncodeLabelKey::encode(&self.as_ref(), encoder)
585    }
586}
587
588impl<T> EncodeLabelKey for Rc<T>
589where
590    T: ?Sized,
591    for<'a> &'a T: EncodeLabelKey,
592{
593    fn encode(&self, encoder: &mut LabelKeyEncoder) -> Result<(), std::fmt::Error> {
594        EncodeLabelKey::encode(&self.as_ref(), encoder)
595    }
596}
597
598/// An encodable label value.
599pub trait EncodeLabelValue {
600    /// Encode oneself into the given encoder.
601    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error>;
602}
603
604/// Encoder for a label value.
605#[derive(Debug)]
606pub struct LabelValueEncoder<'a>(LabelValueEncoderInner<'a>);
607
608#[derive(Debug)]
609enum LabelValueEncoderInner<'a> {
610    Text(text::LabelValueEncoder<'a>),
611    #[cfg(feature = "openmetrics_protobuf")]
612    Protobuf(openmetrics_protobuf::LabelValueEncoder<'a>),
613    #[cfg(feature = "prometheus_protobuf")]
614    PrometheusProtobuf(prometheus_protobuf::LabelValueEncoder<'a>),
615}
616
617impl<'a> From<text::LabelValueEncoder<'a>> for LabelValueEncoder<'a> {
618    fn from(e: text::LabelValueEncoder<'a>) -> Self {
619        LabelValueEncoder(LabelValueEncoderInner::Text(e))
620    }
621}
622
623#[cfg(feature = "openmetrics_protobuf")]
624impl<'a> From<openmetrics_protobuf::LabelValueEncoder<'a>> for LabelValueEncoder<'a> {
625    fn from(e: openmetrics_protobuf::LabelValueEncoder<'a>) -> Self {
626        LabelValueEncoder(LabelValueEncoderInner::Protobuf(e))
627    }
628}
629
630#[cfg(feature = "prometheus_protobuf")]
631impl<'a> From<prometheus_protobuf::LabelValueEncoder<'a>> for LabelValueEncoder<'a> {
632    fn from(e: prometheus_protobuf::LabelValueEncoder<'a>) -> Self {
633        LabelValueEncoder(LabelValueEncoderInner::PrometheusProtobuf(e))
634    }
635}
636
637impl std::fmt::Write for LabelValueEncoder<'_> {
638    fn write_str(&mut self, s: &str) -> std::fmt::Result {
639        for_both_mut!(self, LabelValueEncoderInner, [Text], e, e.write_str(s))
640    }
641}
642
643impl LabelValueEncoder<'_> {
644    pub(crate) fn write_str_unescaped(&mut self, s: &str) -> Result<(), std::fmt::Error> {
645        for_both_mut!(
646            self,
647            LabelValueEncoderInner,
648            [Text],
649            e,
650            e.write_str_unescaped(s)
651        )
652    }
653
654    /// Finish encoding the label value.
655    pub fn finish(self) -> Result<(), std::fmt::Error> {
656        for_both!(self, LabelValueEncoderInner, [Text], e, e.finish())
657    }
658}
659
660impl EncodeLabelValue for &str {
661    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
662        encoder.write_str(self)?;
663        Ok(())
664    }
665}
666
667impl EncodeLabelValue for String {
668    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
669        EncodeLabelValue::encode(&self.as_str(), encoder)
670    }
671}
672
673impl EncodeLabelValue for &String {
674    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
675        EncodeLabelValue::encode(&self.as_str(), encoder)
676    }
677}
678
679impl EncodeLabelValue for Cow<'_, str> {
680    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
681        EncodeLabelValue::encode(&self.as_ref(), encoder)
682    }
683}
684
685impl<T> EncodeLabelValue for Box<T>
686where
687    T: ?Sized,
688    for<'a> &'a T: EncodeLabelValue,
689{
690    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
691        EncodeLabelValue::encode(&self.as_ref(), encoder)
692    }
693}
694
695impl<T> EncodeLabelValue for Arc<T>
696where
697    T: ?Sized,
698    for<'a> &'a T: EncodeLabelValue,
699{
700    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
701        EncodeLabelValue::encode(&self.as_ref(), encoder)
702    }
703}
704
705impl<T> EncodeLabelValue for Rc<T>
706where
707    T: ?Sized,
708    for<'a> &'a T: EncodeLabelValue,
709{
710    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
711        EncodeLabelValue::encode(&self.as_ref(), encoder)
712    }
713}
714
715impl EncodeLabelValue for f64 {
716    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
717        encoder.write_str_unescaped(dtoa::Buffer::new().format(*self))
718    }
719}
720
721impl<T> EncodeLabelValue for Option<T>
722where
723    T: EncodeLabelValue,
724{
725    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
726        match self {
727            Some(v) => EncodeLabelValue::encode(v, encoder),
728            None => EncodeLabelValue::encode(&"", encoder),
729        }
730    }
731}
732
733impl EncodeLabelValue for bool {
734    fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
735        encoder.write_str_unescaped(if *self { "true" } else { "false" })
736    }
737}
738
739macro_rules! impl_encode_label_value_for_integer {
740    ($($t:ident),*) => {$(
741        impl EncodeLabelValue for $t {
742            fn encode(&self, encoder: &mut LabelValueEncoder) -> Result<(), std::fmt::Error> {
743                encoder.write_str_unescaped(itoa::Buffer::new().format(*self))
744            }
745        }
746    )*};
747}
748
749impl_encode_label_value_for_integer!(
750    u128, i128, u64, i64, u32, i32, u16, i16, u8, i8, usize, isize
751);
752
753/// An encodable gauge value.
754pub trait EncodeGaugeValue {
755    /// Encode the given instance in the OpenMetrics text encoding.
756    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error>;
757}
758
759impl EncodeGaugeValue for u32 {
760    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
761        encoder.encode_u32(*self)
762    }
763}
764
765impl EncodeGaugeValue for i64 {
766    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
767        encoder.encode_i64(*self)
768    }
769}
770
771impl EncodeGaugeValue for u64 {
772    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
773        encoder.encode_u64(*self)
774    }
775}
776
777impl EncodeGaugeValue for isize {
778    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
779        // Is infallible for 32-bit or 64-bit platforms
780        encoder.encode_i64(i64::try_from(*self).map_err(|_err| std::fmt::Error)?)
781    }
782}
783
784impl EncodeGaugeValue for usize {
785    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
786        // For 32-bit platforms this is infallible, for 64-bit platforms the argument is the same
787        // as the one for u64 values
788        encoder.encode_i64(i64::try_from(*self).map_err(|_err| std::fmt::Error)?)
789    }
790}
791
792impl EncodeGaugeValue for f64 {
793    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
794        encoder.encode_f64(*self)
795    }
796}
797
798impl EncodeGaugeValue for i32 {
799    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
800        encoder.encode_i64(i64::from(*self))
801    }
802}
803
804impl EncodeGaugeValue for f32 {
805    fn encode(&self, encoder: &mut GaugeValueEncoder) -> Result<(), std::fmt::Error> {
806        encoder.encode_f64(f64::from(*self))
807    }
808}
809
810/// Encoder for a gauge value.
811#[derive(Debug)]
812pub struct GaugeValueEncoder<'a>(GaugeValueEncoderInner<'a>);
813
814#[derive(Debug)]
815enum GaugeValueEncoderInner<'a> {
816    Text(text::GaugeValueEncoder<'a>),
817    PrometheusText(prometheus_text::GaugeValueEncoder<'a>),
818    #[cfg(feature = "openmetrics_protobuf")]
819    Protobuf(openmetrics_protobuf::GaugeValueEncoder<'a>),
820    #[cfg(feature = "prometheus_protobuf")]
821    PrometheusProtobuf(prometheus_protobuf::GaugeValueEncoder<'a>),
822}
823
824impl GaugeValueEncoder<'_> {
825    fn encode_u32(&mut self, v: u32) -> Result<(), std::fmt::Error> {
826        for_both_mut!(self, GaugeValueEncoderInner, e, e.encode_u32(v))
827    }
828
829    fn encode_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
830        for_both_mut!(self, GaugeValueEncoderInner, e, e.encode_u64(v))
831    }
832
833    fn encode_i64(&mut self, v: i64) -> Result<(), std::fmt::Error> {
834        for_both_mut!(self, GaugeValueEncoderInner, e, e.encode_i64(v))
835    }
836
837    fn encode_f64(&mut self, v: f64) -> Result<(), std::fmt::Error> {
838        for_both_mut!(self, GaugeValueEncoderInner, e, e.encode_f64(v))
839    }
840}
841
842impl<'a> From<text::GaugeValueEncoder<'a>> for GaugeValueEncoder<'a> {
843    fn from(e: text::GaugeValueEncoder<'a>) -> Self {
844        GaugeValueEncoder(GaugeValueEncoderInner::Text(e))
845    }
846}
847
848impl<'a> From<prometheus_text::GaugeValueEncoder<'a>> for GaugeValueEncoder<'a> {
849    fn from(e: prometheus_text::GaugeValueEncoder<'a>) -> Self {
850        GaugeValueEncoder(GaugeValueEncoderInner::PrometheusText(e))
851    }
852}
853
854#[cfg(feature = "openmetrics_protobuf")]
855impl<'a> From<openmetrics_protobuf::GaugeValueEncoder<'a>> for GaugeValueEncoder<'a> {
856    fn from(e: openmetrics_protobuf::GaugeValueEncoder<'a>) -> Self {
857        GaugeValueEncoder(GaugeValueEncoderInner::Protobuf(e))
858    }
859}
860
861#[cfg(feature = "prometheus_protobuf")]
862impl<'a> From<prometheus_protobuf::GaugeValueEncoder<'a>> for GaugeValueEncoder<'a> {
863    fn from(e: prometheus_protobuf::GaugeValueEncoder<'a>) -> Self {
864        GaugeValueEncoder(GaugeValueEncoderInner::PrometheusProtobuf(e))
865    }
866}
867
868/// An encodable counter value.
869pub trait EncodeCounterValue {
870    /// Encode the given instance in the OpenMetrics text encoding.
871    fn encode(&self, encoder: &mut CounterValueEncoder) -> Result<(), std::fmt::Error>;
872}
873
874impl EncodeCounterValue for u64 {
875    fn encode(&self, encoder: &mut CounterValueEncoder) -> Result<(), std::fmt::Error> {
876        encoder.encode_u64(*self)
877    }
878}
879
880impl EncodeCounterValue for usize {
881    fn encode(&self, encoder: &mut CounterValueEncoder) -> Result<(), std::fmt::Error> {
882        // Is infallible for 32-bit and 64-bit platforms
883        encoder.encode_u64(u64::try_from(*self).map_err(|_err| std::fmt::Error)?)
884    }
885}
886
887impl EncodeCounterValue for f64 {
888    fn encode(&self, encoder: &mut CounterValueEncoder) -> Result<(), std::fmt::Error> {
889        encoder.encode_f64(*self)
890    }
891}
892
893impl EncodeCounterValue for u32 {
894    fn encode(&self, encoder: &mut CounterValueEncoder) -> Result<(), std::fmt::Error> {
895        encoder.encode_u64(u64::from(*self))
896    }
897}
898
899impl EncodeCounterValue for f32 {
900    fn encode(&self, encoder: &mut CounterValueEncoder) -> Result<(), std::fmt::Error> {
901        encoder.encode_f64(f64::from(*self))
902    }
903}
904
905/// Encoder for a counter value.
906#[derive(Debug)]
907pub struct CounterValueEncoder<'a>(CounterValueEncoderInner<'a>);
908
909#[derive(Debug)]
910enum CounterValueEncoderInner<'a> {
911    Text(text::CounterValueEncoder<'a>),
912    PrometheusText(prometheus_text::CounterValueEncoder<'a>),
913    #[cfg(feature = "openmetrics_protobuf")]
914    Protobuf(openmetrics_protobuf::CounterValueEncoder<'a>),
915    #[cfg(feature = "prometheus_protobuf")]
916    PrometheusProtobuf(prometheus_protobuf::CounterValueEncoder<'a>),
917}
918
919impl<'a> From<text::CounterValueEncoder<'a>> for CounterValueEncoder<'a> {
920    fn from(e: text::CounterValueEncoder<'a>) -> Self {
921        CounterValueEncoder(CounterValueEncoderInner::Text(e))
922    }
923}
924
925impl<'a> From<prometheus_text::CounterValueEncoder<'a>> for CounterValueEncoder<'a> {
926    fn from(e: prometheus_text::CounterValueEncoder<'a>) -> Self {
927        CounterValueEncoder(CounterValueEncoderInner::PrometheusText(e))
928    }
929}
930
931#[cfg(feature = "openmetrics_protobuf")]
932impl<'a> From<openmetrics_protobuf::CounterValueEncoder<'a>> for CounterValueEncoder<'a> {
933    fn from(e: openmetrics_protobuf::CounterValueEncoder<'a>) -> Self {
934        CounterValueEncoder(CounterValueEncoderInner::Protobuf(e))
935    }
936}
937
938#[cfg(feature = "prometheus_protobuf")]
939impl<'a> From<prometheus_protobuf::CounterValueEncoder<'a>> for CounterValueEncoder<'a> {
940    fn from(e: prometheus_protobuf::CounterValueEncoder<'a>) -> Self {
941        CounterValueEncoder(CounterValueEncoderInner::PrometheusProtobuf(e))
942    }
943}
944
945impl CounterValueEncoder<'_> {
946    fn encode_f64(&mut self, v: f64) -> Result<(), std::fmt::Error> {
947        for_both_mut!(self, CounterValueEncoderInner, e, e.encode_f64(v))
948    }
949
950    fn encode_u64(&mut self, v: u64) -> Result<(), std::fmt::Error> {
951        for_both_mut!(self, CounterValueEncoderInner, e, e.encode_u64(v))
952    }
953}
954
955/// An encodable exemplar value.
956pub trait EncodeExemplarValue {
957    /// Encode the given instance in the OpenMetrics text encoding.
958    fn encode(&self, encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error>;
959}
960
961impl EncodeExemplarValue for f64 {
962    fn encode(&self, mut encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error> {
963        encoder.encode(*self)
964    }
965}
966
967impl EncodeExemplarValue for u64 {
968    fn encode(&self, mut encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error> {
969        encoder.encode(*self as f64)
970    }
971}
972
973impl EncodeExemplarValue for f32 {
974    fn encode(&self, mut encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error> {
975        encoder.encode(f64::from(*self))
976    }
977}
978
979impl EncodeExemplarValue for u32 {
980    fn encode(&self, mut encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error> {
981        encoder.encode(f64::from(*self))
982    }
983}
984
985/// An encodable exemplar time.
986pub trait EncodeExemplarTime {
987    /// Encode the time in the OpenMetrics text encoding.
988    fn encode(&self, encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error>;
989}
990
991impl EncodeExemplarTime for SystemTime {
992    fn encode(&self, mut encoder: ExemplarValueEncoder) -> Result<(), std::fmt::Error> {
993        encoder.encode(self.duration_since(UNIX_EPOCH).unwrap().as_secs_f64())
994    }
995}
996
997/// Encoder for an exemplar value.
998#[derive(Debug)]
999pub struct ExemplarValueEncoder<'a>(ExemplarValueEncoderInner<'a>);
1000
1001#[derive(Debug)]
1002enum ExemplarValueEncoderInner<'a> {
1003    Text(text::ExemplarValueEncoder<'a>),
1004    #[cfg(feature = "openmetrics_protobuf")]
1005    Protobuf(openmetrics_protobuf::ExemplarValueEncoder<'a>),
1006    #[cfg(feature = "prometheus_protobuf")]
1007    PrometheusProtobuf(prometheus_protobuf::ExemplarValueEncoder<'a>),
1008}
1009
1010impl<'a> From<text::ExemplarValueEncoder<'a>> for ExemplarValueEncoder<'a> {
1011    fn from(e: text::ExemplarValueEncoder<'a>) -> Self {
1012        ExemplarValueEncoder(ExemplarValueEncoderInner::Text(e))
1013    }
1014}
1015
1016#[cfg(feature = "openmetrics_protobuf")]
1017impl<'a> From<openmetrics_protobuf::ExemplarValueEncoder<'a>> for ExemplarValueEncoder<'a> {
1018    fn from(e: openmetrics_protobuf::ExemplarValueEncoder<'a>) -> Self {
1019        ExemplarValueEncoder(ExemplarValueEncoderInner::Protobuf(e))
1020    }
1021}
1022
1023#[cfg(feature = "prometheus_protobuf")]
1024impl<'a> From<prometheus_protobuf::ExemplarValueEncoder<'a>> for ExemplarValueEncoder<'a> {
1025    fn from(e: prometheus_protobuf::ExemplarValueEncoder<'a>) -> Self {
1026        ExemplarValueEncoder(ExemplarValueEncoderInner::PrometheusProtobuf(e))
1027    }
1028}
1029
1030impl ExemplarValueEncoder<'_> {
1031    fn encode(&mut self, v: f64) -> Result<(), std::fmt::Error> {
1032        for_both_mut!(self, ExemplarValueEncoderInner, [Text], e, e.encode(v))
1033    }
1034}