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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use serde::ser::{Serialize, Serializer};
use std::io::Write;

#[cfg(feature = "bridge")]
mod bridge;
mod error;
mod str;
mod top;
mod value;

#[cfg(feature = "bridge")]
pub use self::bridge::Family;

pub use self::error::Error;

/// Serializes `value` into a [`String`].
///
/// See [`serializer`] for information about the data format.
///
/// #### Examples
///
/// Basic usage:
///
/// ```rust
/// # use serde::Serialize;
/// # use serde_prometheus_labels::to_string;
/// #
/// #[derive(Serialize)]
/// struct Labels {
///     method: Method,
///     path: String,
/// }
///
/// #[derive(Serialize)]
/// enum Method {
///     #[serde(rename = "GET")]
///     Get,
/// }
///
/// let labels = Labels {
///     method: Method::Get,
///     path: "/metrics".to_string(),
/// };
///
/// let serialized = to_string(&labels).unwrap();
///
/// assert_eq!(serialized, r#"method="GET",path="/metrics""#);
/// ```
///
/// Optional values:
///
/// ```rust
/// # use serde::Serialize;
/// # use serde_prometheus_labels::to_string;
/// #
/// #[derive(Serialize)]
/// struct Error {
///     severity: Option<&'static str>,
///     reason: Option<&'static str>,
/// }
///
/// let error = Error {
///     severity: Some("fatal"),
///     reason: None,
/// };
///
/// let serialized = to_string(&error).unwrap();
///
/// assert_eq!(serialized, r#"severity="fatal",reason="""#);
/// ```
pub fn to_string(value: &impl Serialize) -> Result<String, Error> {
    let mut string = "".to_owned();

    value.serialize(top::TopSerializer::new(str::Writer::from_mut_string(
        &mut string,
    )))?;

    Ok(string)
}

/// Serializes `value` into a [`Vec<u8>`].
///
/// See [`serializer`] for information about the data format.
///
/// #### Examples
///
/// Basic usage:
///
/// ```rust
/// # use serde::Serialize;
/// # use serde_prometheus_labels::to_vec;
/// #
/// #[derive(Serialize)]
/// struct Labels {
///     method: Method,
///     path: String,
/// }
///
/// #[derive(Serialize)]
/// enum Method {
///     #[serde(rename = "GET")]
///     Get,
/// }
///
/// let labels = Labels {
///     method: Method::Get,
///     path: "/metrics".to_string(),
/// };
///
/// let serialized = to_vec(&labels).unwrap();
///
/// assert_eq!(serialized, br#"method="GET",path="/metrics""#);
/// ```
pub fn to_vec(value: &impl Serialize) -> Result<Vec<u8>, Error> {
    let mut buf = vec![];
    to_writer(&mut buf, value)?;
    Ok(buf)
}

/// Serializes `value` into [`writer`][Write].
///
/// See [`serializer`] for information about the data format.
pub fn to_writer(writer: &mut (impl ?Sized + Write), value: &impl Serialize) -> Result<(), Error> {
    value.serialize(serializer(writer))
}

/// A serializer for Prometheus labels.
///
/// This serializer only supports structs.
///
/// For struct fields, the supported values are scalars, strings, and bytes
/// that can be converted to strings. Nones and units are ignored, and unit
/// variants are serialized as their name. Anything else results in an error.
///
/// Prometheus labels are a sequence of comma-separated key-value pairs
/// as specified by the [Prometheus documentation][doc].
///
/// [doc]: https://github.com/prometheus/docs/blob/main/content/docs/instrumenting/exposition_formats.md#text-format-details
pub fn serializer(
    writer: &mut (impl ?Sized + Write),
) -> impl '_ + Serializer<Ok = (), Error = Error> {
    top::TopSerializer::new(str::Writer::new(writer))
}