opentelemetry_prometheus_xx/
lib.rs

1//! An OpenTelemetry exporter for [Prometheus] metrics.
2//!
3//! <div class="warning">
4//! <strong>Warning: This crate is no longer recommended for use.</strong><br><br>
5//! Development of the Prometheus exporter has been discontinued. See the related
6//! [issue](https://github.com/open-telemetry/opentelemetry-rust/issues/2451).
7//! This crate depends on the unmaintained `protobuf` crate and has unresolved
8//! security vulnerabilities. Version 0.29 will be the final release.
9//!
10//! For Prometheus integration, we strongly recommend using the [OTLP] exporter instead.
11//! Prometheus [natively supports OTLP](https://prometheus.io/docs/guides/opentelemetry/#enable-the-otlp-receiver),
12//! providing a more stable and actively maintained solution.
13//! </div>
14//!
15//! [Prometheus]: https://prometheus.io
16//! [OTLP]: https://docs.rs/opentelemetry-otlp/latest/opentelemetry_otlp/
17//!
18//! ```
19//! use opentelemetry::{metrics::MeterProvider, KeyValue};
20//! use opentelemetry_sdk::metrics::SdkMeterProvider;
21//! use prometheus::{Encoder, TextEncoder};
22//!
23//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
24//!
25//! // create a new prometheus registry
26//! let registry = prometheus::Registry::new();
27//!
28//! // configure OpenTelemetry to use this registry
29//! let exporter = opentelemetry_prometheus_xx::exporter()
30//!     .with_registry(registry.clone())
31//!     .build()?;
32//!
33//! // set up a meter to create instruments
34//! let provider = SdkMeterProvider::builder().with_reader(exporter).build();
35//! let meter = provider.meter("my-app");
36//!
37//! // Use two instruments
38//! let counter = meter
39//!     .u64_counter("a.counter")
40//!     .with_description("Counts things")
41//!     .build();
42//! let histogram = meter
43//!     .u64_histogram("a.histogram")
44//!     .with_description("Records values")
45//!     .build();
46//!
47//! counter.add(100, &[KeyValue::new("key", "value")]);
48//! histogram.record(100, &[KeyValue::new("key", "value")]);
49//!
50//! // Encode data as text or protobuf
51//! let encoder = TextEncoder::new();
52//! let metric_families = registry.gather();
53//! let mut result = Vec::new();
54//! encoder.encode(&metric_families, &mut result)?;
55//!
56//! // result now contains encoded metrics:
57//! //
58//! // # HELP a_counter_total Counts things
59//! // # TYPE a_counter_total counter
60//! // a_counter_total{key="value",otel_scope_name="my-app"} 100
61//! // # HELP a_histogram Records values
62//! // # TYPE a_histogram histogram
63//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="0"} 0
64//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="5"} 0
65//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="10"} 0
66//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="25"} 0
67//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="50"} 0
68//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="75"} 0
69//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="100"} 1
70//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="250"} 1
71//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="500"} 1
72//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="750"} 1
73//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="1000"} 1
74//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="2500"} 1
75//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="5000"} 1
76//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="7500"} 1
77//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="10000"} 1
78//! // a_histogram_bucket{key="value",otel_scope_name="my-app",le="+Inf"} 1
79//! // a_histogram_sum{key="value",otel_scope_name="my-app"} 100
80//! // a_histogram_count{key="value",otel_scope_name="my-app"} 1
81//! // # HELP otel_scope_info Instrumentation Scope metadata
82//! // # TYPE otel_scope_info gauge
83//! // otel_scope_info{otel_scope_name="my-app"} 1
84//! // # HELP target_info Target metadata
85//! // # TYPE target_info gauge
86//! // target_info{service_name="unknown_service"} 1
87//! # Ok(())
88//! # }
89//! ```
90#![warn(
91    future_incompatible,
92    missing_debug_implementations,
93    missing_docs,
94    nonstandard_style,
95    rust_2018_idioms,
96    unreachable_pub,
97    unused
98)]
99#![cfg_attr(
100    docsrs,
101    feature(doc_cfg, doc_auto_cfg),
102    deny(rustdoc::broken_intra_doc_links)
103)]
104#![doc(
105    html_logo_url = "https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo.svg"
106)]
107#![cfg_attr(test, deny(warnings))]
108
109use once_cell::sync::OnceCell;
110use opentelemetry::{otel_error, otel_warn, InstrumentationScope, Key, Value};
111use opentelemetry_sdk::{
112    error::OTelSdkResult,
113    metrics::{
114        data::{self, ResourceMetrics},
115        reader::MetricReader,
116        InstrumentKind, ManualReader, Pipeline, Temporality,
117    },
118    Resource,
119};
120use prometheus::{
121    core::Desc,
122    proto::{LabelPair, MetricFamily, MetricType},
123};
124use std::{
125    borrow::Cow,
126    collections::{BTreeMap, HashMap},
127    sync::{Arc, Mutex},
128    time::Duration,
129};
130use std::{fmt, sync::Weak};
131
132const TARGET_INFO_NAME: &str = "target_info";
133const TARGET_INFO_DESCRIPTION: &str = "Target metadata";
134
135const SCOPE_INFO_METRIC_NAME: &str = "otel_scope_info";
136const SCOPE_INFO_DESCRIPTION: &str = "Instrumentation Scope metadata";
137
138const SCOPE_INFO_KEYS: [&str; 2] = ["otel_scope_name", "otel_scope_version"];
139
140// prometheus counters MUST have a _total suffix by default:
141// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/compatibility/prometheus_and_openmetrics.md
142const COUNTER_SUFFIX: &str = "_total";
143
144mod config;
145mod resource_selector;
146mod utils;
147
148pub use config::ExporterBuilder;
149pub use resource_selector::ResourceSelector;
150
151/// Creates a builder to configure a [PrometheusExporter]
152pub fn exporter() -> ExporterBuilder {
153    ExporterBuilder::default()
154}
155
156/// Prometheus metrics exporter
157#[derive(Debug)]
158pub struct PrometheusExporter {
159    reader: Arc<ManualReader>,
160}
161
162impl MetricReader for PrometheusExporter {
163    fn register_pipeline(&self, pipeline: Weak<Pipeline>) {
164        self.reader.register_pipeline(pipeline)
165    }
166
167    fn collect(&self, rm: &mut ResourceMetrics) -> OTelSdkResult {
168        self.reader.collect(rm)
169    }
170
171    fn force_flush(&self) -> OTelSdkResult {
172        self.reader.force_flush()
173    }
174
175    fn shutdown_with_timeout(&self, timeout: Duration) -> OTelSdkResult {
176        self.reader.shutdown_with_timeout(timeout)
177    }
178
179    /// Note: Prometheus only supports cumulative temporality, so this will always be
180    /// [Temporality::Cumulative].
181    fn temporality(&self, _kind: InstrumentKind) -> Temporality {
182        Temporality::Cumulative
183    }
184}
185
186struct Collector {
187    reader: Arc<ManualReader>,
188    disable_target_info: bool,
189    without_units: bool,
190    without_counter_suffixes: bool,
191    disable_scope_info: bool,
192    create_target_info_once: OnceCell<MetricFamily>,
193    resource_labels_once: OnceCell<Vec<LabelPair>>,
194    namespace: Option<String>,
195    inner: Mutex<CollectorInner>,
196    resource_selector: ResourceSelector,
197}
198
199#[derive(Default)]
200struct CollectorInner {
201    scope_infos: HashMap<InstrumentationScope, MetricFamily>,
202    metric_families: HashMap<String, MetricFamily>,
203}
204
205impl Collector {
206    fn metric_type_and_name(&self, m: &data::Metric) -> Option<(MetricType, Cow<'static, str>)> {
207        let mut name = self.get_name(m);
208
209        macro_rules! extract_metric_data_type_and_name {
210            ($data:expr, $counter:tt) => {
211                match $data {
212                    data::MetricData::Gauge(_) => Some((MetricType::GAUGE, name)),
213                    data::MetricData::Sum(sum) => {
214                        let is_monotonic = sum.is_monotonic();
215                        if is_monotonic {
216                            if !self.without_counter_suffixes {
217                                name = format!("{name}{COUNTER_SUFFIX}").into();
218                            }
219                            Some((MetricType::COUNTER, name))
220                        } else {
221                            Some((MetricType::GAUGE, name))
222                        }
223                    }
224                    data::MetricData::Histogram(_) => Some((MetricType::HISTOGRAM, name)),
225                    data::MetricData::ExponentialHistogram(_) => {
226                        Some((MetricType::HISTOGRAM, name))
227                    }
228                }
229            };
230        }
231
232        match m.data() {
233            data::AggregatedMetrics::F64(data) => extract_metric_data_type_and_name!(data, self),
234            data::AggregatedMetrics::U64(data) => extract_metric_data_type_and_name!(data, self),
235            data::AggregatedMetrics::I64(data) => extract_metric_data_type_and_name!(data, self),
236        }
237    }
238
239    fn get_name(&self, m: &data::Metric) -> Cow<'static, str> {
240        let name = utils::sanitize_name(&m.name().to_string().into());
241        let unit_suffixes = if self.without_units {
242            None
243        } else {
244            utils::get_unit_suffixes(m.unit())
245        };
246        match (&self.namespace, unit_suffixes) {
247            (Some(namespace), Some(suffix)) => Cow::Owned(format!("{namespace}{name}_{suffix}")),
248            (Some(namespace), None) => Cow::Owned(format!("{namespace}{name}")),
249            (None, Some(suffix)) => Cow::Owned(format!("{name}_{suffix}")),
250            (None, None) => name,
251        }
252    }
253}
254
255impl prometheus::core::Collector for Collector {
256    fn desc(&self) -> Vec<&Desc> {
257        Vec::new()
258    }
259
260    fn collect(&self) -> Vec<MetricFamily> {
261        let mut inner = match self.inner.lock() {
262            Ok(guard) => guard,
263            Err(err) => {
264                otel_error!(
265                    name: "MetricScrapeFailed",
266                    message = err.to_string(),
267                );
268                return Vec::new();
269            }
270        };
271
272        let mut metrics = ResourceMetrics::default();
273        if let Err(err) = self.reader.collect(&mut metrics) {
274            otel_error!(
275                name: "MetricScrapeFailed",
276                message = err.to_string(),
277            );
278            return vec![];
279        }
280        let mut res = Vec::with_capacity(metrics.scope_metrics().collect::<Vec<_>>().len() + 1);
281
282        let target_info = self.create_target_info_once.get_or_init(|| {
283            // Resource should be immutable, we don't need to compute again
284            create_info_metric(
285                TARGET_INFO_NAME,
286                TARGET_INFO_DESCRIPTION,
287                metrics.resource(),
288            )
289        });
290
291        if !self.disable_target_info && !metrics.resource().is_empty() {
292            res.push(target_info.clone())
293        }
294
295        let resource_labels = self
296            .resource_labels_once
297            .get_or_init(|| self.resource_selector.select(metrics.resource()));
298
299        for scope_metrics in metrics.scope_metrics() {
300            let scope_labels = if !self.disable_scope_info {
301                if scope_metrics.scope().attributes().count() > 0 {
302                    let scope_info = inner
303                        .scope_infos
304                        .entry(scope_metrics.scope().clone())
305                        .or_insert_with_key(create_scope_info_metric);
306                    res.push(scope_info.clone());
307                }
308
309                let mut labels =
310                    Vec::with_capacity(1 + scope_metrics.scope().version().is_some() as usize);
311                let mut name = LabelPair::new();
312                name.set_name(SCOPE_INFO_KEYS[0].into());
313                name.set_value(scope_metrics.scope().name().to_string());
314                labels.push(name);
315                if let Some(version) = &scope_metrics.scope().version() {
316                    let mut l_version = LabelPair::new();
317                    l_version.set_name(SCOPE_INFO_KEYS[1].into());
318                    l_version.set_value(version.to_string());
319                    labels.push(l_version);
320                }
321
322                if !resource_labels.is_empty() {
323                    labels.extend(resource_labels.iter().cloned());
324                }
325                labels
326            } else {
327                Vec::new()
328            };
329
330            for metrics in scope_metrics.metrics() {
331                let (metric_type, name) = match self.metric_type_and_name(metrics) {
332                    Some((metric_type, name)) => (metric_type, name),
333                    _ => continue,
334                };
335
336                let mfs = &mut inner.metric_families;
337                let (drop, help) = validate_metrics(&name, metrics.description(), metric_type, mfs);
338                if drop {
339                    continue;
340                }
341
342                let description = help.unwrap_or_else(|| metrics.description().into());
343
344                macro_rules! add_metric {
345                    ($data:expr) => {
346                        match $data {
347                            data::MetricData::Gauge(gauge) => {
348                                add_gauge_metric(&mut res, gauge, description, &scope_labels, name);
349                            }
350                            data::MetricData::Sum(sum) => {
351                                add_sum_metric(&mut res, sum, description, &scope_labels, name);
352                            }
353                            data::MetricData::Histogram(hist) => {
354                                add_histogram_metric(
355                                    &mut res,
356                                    hist,
357                                    description,
358                                    &scope_labels,
359                                    name,
360                                );
361                            }
362                            data::MetricData::ExponentialHistogram(_) => {
363                                // FIXME(MrCroxx):
364                                // add_exponential_histogram_metric(
365                                //     &mut res,
366                                //     hist,
367                                //     description,
368                                //     &scope_labels,
369                                //     name,
370                                // );
371                            }
372                        }
373                    };
374                }
375
376                match metrics.data() {
377                    data::AggregatedMetrics::F64(data) => add_metric!(data),
378                    data::AggregatedMetrics::U64(data) => add_metric!(data),
379                    data::AggregatedMetrics::I64(data) => add_metric!(data),
380                }
381            }
382        }
383
384        res
385    }
386}
387
388/// Maps attributes into Prometheus-style label pairs.
389///
390/// It sanitizes invalid characters and handles duplicate keys (due to
391/// sanitization) by sorting and concatenating the values following the spec.
392fn get_attrs(kvs: &mut dyn Iterator<Item = (&Key, &Value)>, extra: &[LabelPair]) -> Vec<LabelPair> {
393    let mut keys_map = BTreeMap::<String, Vec<String>>::new();
394    for (key, value) in kvs {
395        let key = utils::sanitize_prom_kv(key.as_str());
396        keys_map
397            .entry(key)
398            .and_modify(|v| v.push(value.to_string()))
399            .or_insert_with(|| vec![value.to_string()]);
400    }
401
402    let mut res = Vec::with_capacity(keys_map.len() + extra.len());
403
404    for (key, mut values) in keys_map.into_iter() {
405        values.sort_unstable();
406
407        let mut lp = LabelPair::new();
408        lp.set_name(key);
409        lp.set_value(values.join(";"));
410        res.push(lp);
411    }
412
413    if !extra.is_empty() {
414        res.extend(&mut extra.iter().cloned());
415    }
416
417    res
418}
419
420fn validate_metrics(
421    name: &str,
422    description: &str,
423    metric_type: MetricType,
424    mfs: &mut HashMap<String, MetricFamily>,
425) -> (bool, Option<String>) {
426    if let Some(existing) = mfs.get(name) {
427        if existing.get_field_type() != metric_type {
428            otel_warn!(
429                name: "MetricValidationFailed",
430                message = "Instrument type conflict, using existing type definition",
431                metric_type = format!("Instrument {name}, Existing: {:?}, dropped: {:?}", existing.get_field_type(), metric_type).as_str(),
432            );
433            return (true, None);
434        }
435        if existing.help() != description {
436            otel_warn!(
437                name: "MetricValidationFailed",
438                message = "Instrument description conflict, using existing",
439                metric_description = format!("Instrument {name}, Existing: {:?}, dropped: {:?}", existing.help().to_string(), description.to_string()).as_str(),
440            );
441            return (false, Some(existing.help().to_string()));
442        }
443        (false, None)
444    } else {
445        let mut mf = MetricFamily::default();
446        mf.set_name(name.into());
447        mf.set_help(description.to_string());
448        mf.set_field_type(metric_type);
449        mfs.insert(name.to_string(), mf);
450
451        (false, None)
452    }
453}
454
455fn add_histogram_metric<T: Numeric>(
456    res: &mut Vec<MetricFamily>,
457    histogram: &data::Histogram<T>,
458    description: String,
459    extra: &[LabelPair],
460    name: Cow<'static, str>,
461) {
462    // Consider supporting exemplars when `prometheus` crate has the feature
463    // See: https://github.com/tikv/rust-prometheus/issues/393
464
465    for dp in histogram.data_points() {
466        let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
467        let bounds_len = dp.bounds().collect::<Vec<_>>().len();
468        let bucket_counts = dp.bucket_counts().collect::<Vec<_>>();
469        let (bucket, _) = dp.bounds().enumerate().fold(
470            (Vec::with_capacity(bounds_len), 0),
471            |(mut acc, mut count), (i, bound)| {
472                count += bucket_counts[i];
473
474                let mut b = prometheus::proto::Bucket::default();
475                b.set_upper_bound(bound);
476                b.set_cumulative_count(count);
477                acc.push(b);
478                (acc, count)
479            },
480        );
481
482        let mut h = prometheus::proto::Histogram::default();
483        h.set_sample_sum(dp.sum().as_f64());
484        h.set_sample_count(dp.count());
485        h.set_bucket(bucket);
486        let mut pm = prometheus::proto::Metric::default();
487        pm.set_label(kvs);
488        pm.set_histogram(h);
489
490        let mut mf = prometheus::proto::MetricFamily::default();
491        mf.set_name(name.to_string());
492        mf.set_help(description.clone());
493        mf.set_field_type(prometheus::proto::MetricType::HISTOGRAM);
494        mf.set_metric(vec![pm]);
495        res.push(mf);
496    }
497}
498
499// FIXME(MrCroxx):
500// fn add_exponential_histogram_metric<T: Numeric>(
501//     res: &mut Vec<MetricFamily>,
502//     histogram: &data::ExponentialHistogram<T>,
503//     description: String,
504//     extra: &[LabelPair],
505//     name: Cow<'static, str>,
506// ) {
507//     // Consider supporting exemplars when `prometheus` crate has the feature
508//     // See: https://github.com/tikv/rust-prometheus/issues/393
509
510//     for dp in histogram.data_points() {
511//         let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
512
513//         let bounds_len = dp.bounds.len();
514//         let (bucket, _) = dp.bounds.iter().enumerate().fold(
515//             (Vec::with_capacity(bounds_len), 0),
516//             |(mut acc, mut count), (i, bound)| {
517//                 count += dp.bucket_counts[i];
518
519//                 let mut b = prometheus::proto::Bucket::default();
520//                 b.set_upper_bound(*bound);
521//                 b.set_cumulative_count(count);
522//                 acc.push(b);
523//                 (acc, count)
524//             },
525//         );
526
527//         let mut h = prometheus::proto::Histogram::default();
528//         h.set_sample_sum(dp.sum().as_f64());
529//         h.set_sample_count(dp.count() as _);
530//         h.set_bucket(bucket);
531//         let mut pm = prometheus::proto::Metric::default();
532//         pm.set_label(kvs);
533//         pm.set_histogram(h);
534
535//         let mut mf = prometheus::proto::MetricFamily::default();
536//         mf.set_name(name.to_string());
537//         mf.set_help(description.clone());
538//         mf.set_field_type(prometheus::proto::MetricType::HISTOGRAM);
539//         mf.set_metric(vec![pm]);
540//         res.push(mf);
541//     }
542// }
543
544fn add_sum_metric<T: Numeric>(
545    res: &mut Vec<MetricFamily>,
546    sum: &data::Sum<T>,
547    description: String,
548    extra: &[LabelPair],
549    name: Cow<'static, str>,
550) {
551    let metric_type = if sum.is_monotonic() {
552        MetricType::COUNTER
553    } else {
554        MetricType::GAUGE
555    };
556
557    for dp in sum.data_points() {
558        let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
559
560        let mut pm = prometheus::proto::Metric::default();
561        pm.set_label(kvs);
562
563        if sum.is_monotonic() {
564            let mut c = prometheus::proto::Counter::default();
565            c.set_value(dp.value().as_f64());
566            pm.set_counter(c);
567        } else {
568            let mut g = prometheus::proto::Gauge::default();
569            g.set_value(dp.value().as_f64());
570            pm.set_gauge(g);
571        }
572
573        let mut mf = prometheus::proto::MetricFamily::default();
574        mf.set_name(name.to_string());
575        mf.set_help(description.clone());
576        mf.set_field_type(metric_type);
577        mf.set_metric(vec![pm]);
578        res.push(mf);
579    }
580}
581
582fn add_gauge_metric<T: Numeric>(
583    res: &mut Vec<MetricFamily>,
584    gauge: &data::Gauge<T>,
585    description: String,
586    extra: &[LabelPair],
587    name: Cow<'static, str>,
588) {
589    for dp in gauge.data_points() {
590        let kvs = get_attrs(&mut dp.attributes().map(|kv| (&kv.key, &kv.value)), extra);
591
592        let mut g = prometheus::proto::Gauge::default();
593        g.set_value(dp.value().as_f64());
594        let mut pm = prometheus::proto::Metric::default();
595        pm.set_label(kvs);
596        pm.set_gauge(g);
597
598        let mut mf = prometheus::proto::MetricFamily::default();
599        mf.set_name(name.to_string());
600        mf.set_help(description.to_string());
601        mf.set_field_type(MetricType::GAUGE);
602        mf.set_metric(vec![pm]);
603        res.push(mf);
604    }
605}
606
607fn create_info_metric(
608    target_info_name: &str,
609    target_info_description: &str,
610    resource: &Resource,
611) -> MetricFamily {
612    let mut g = prometheus::proto::Gauge::default();
613    g.set_value(1.0);
614
615    let mut m = prometheus::proto::Metric::default();
616    m.set_label(get_attrs(&mut resource.iter(), &[]));
617    m.set_gauge(g);
618
619    let mut mf = MetricFamily::default();
620    mf.set_name(target_info_name.into());
621    mf.set_help(target_info_description.into());
622    mf.set_field_type(MetricType::GAUGE);
623    mf.set_metric(vec![m]);
624    mf
625}
626
627fn create_scope_info_metric(scope: &InstrumentationScope) -> MetricFamily {
628    let mut g = prometheus::proto::Gauge::default();
629    g.set_value(1.0);
630
631    let mut labels = Vec::with_capacity(1 + scope.version().is_some() as usize);
632    let mut name = LabelPair::new();
633    name.set_name(SCOPE_INFO_KEYS[0].into());
634    name.set_value(scope.name().to_string());
635    labels.push(name);
636    if let Some(version) = &scope.version() {
637        let mut v_label = LabelPair::new();
638        v_label.set_name(SCOPE_INFO_KEYS[1].into());
639        v_label.set_value(version.to_string());
640        labels.push(v_label);
641    }
642
643    let mut m = prometheus::proto::Metric::default();
644    m.set_label(labels);
645    m.set_gauge(g);
646
647    let mut mf = MetricFamily::default();
648    mf.set_name(SCOPE_INFO_METRIC_NAME.into());
649    mf.set_help(SCOPE_INFO_DESCRIPTION.into());
650    mf.set_field_type(MetricType::GAUGE);
651    mf.set_metric(vec![m]);
652    mf
653}
654
655trait Numeric: fmt::Debug + Copy {
656    // lossy at large values for u64 and i64 but prometheus only handles floats
657    fn as_f64(&self) -> f64;
658}
659
660impl Numeric for u64 {
661    fn as_f64(&self) -> f64 {
662        *self as f64
663    }
664}
665
666impl Numeric for i64 {
667    fn as_f64(&self) -> f64 {
668        *self as f64
669    }
670}
671
672impl Numeric for f64 {
673    fn as_f64(&self) -> f64 {
674        *self
675    }
676}