Skip to content

Commit f58d49c

Browse files
committed
Add example using std::io::Write
1 parent 377ca2d commit f58d49c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

examples/io_write.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use prometheus_client::{encoding::text::encode, metrics::counter::Counter, registry::Registry};
2+
use std::io::Write;
3+
4+
/// Example showing how one could write to a file or socket instead of a string.
5+
/// For large metrics registries this will be more memory efficient
6+
fn main() {
7+
let mut registry = <Registry>::with_prefix("stream");
8+
let request_counter: Counter<u64> = Default::default();
9+
10+
registry.register(
11+
"requests",
12+
"How many requests the application has received",
13+
request_counter.clone(),
14+
);
15+
16+
let mut buf = String::new();
17+
encode(&mut buf, &registry).unwrap();
18+
19+
let mut file = Vec::new();
20+
let mut writer = IoWriterWrapper(&mut file);
21+
encode(&mut writer, &registry).unwrap();
22+
23+
assert!(buf.as_bytes() == file);
24+
}
25+
26+
pub struct IoWriterWrapper<W>(W)
27+
where
28+
W: Write;
29+
30+
impl<W> std::fmt::Write for IoWriterWrapper<W>
31+
where
32+
W: Write,
33+
{
34+
fn write_str(&mut self, input: &str) -> std::fmt::Result {
35+
self.0
36+
.write_all(input.as_bytes())
37+
.map(|_| ())
38+
.map_err(|_| std::fmt::Error)
39+
}
40+
}

0 commit comments

Comments
 (0)