use std::time::Duration;
use std::time::Instant;
use opentelemetry::KeyValue;
pub(crate) struct Timer<F>
where
F: FnOnce(Duration),
{
start: Instant,
f: Option<F>,
}
impl<F> Timer<F>
where
F: FnOnce(Duration),
{
pub(crate) fn new(f: F) -> Self {
Self {
start: Instant::now(),
f: f.into(),
}
}
}
impl<F> Drop for Timer<F>
where
F: FnOnce(Duration),
{
fn drop(&mut self) {
self.f.take().expect("f must exist")(self.start.elapsed())
}
}
pub(crate) fn upsert_attribute(attributes: &mut Vec<KeyValue>, kv: KeyValue) {
if let Some(existing) = attributes.iter_mut().find(|a| a.key == kv.key) {
*existing = kv;
} else {
attributes.push(kv);
}
}
pub(crate) fn extend_attributes(
attrs: &mut Vec<KeyValue>,
new_attrs: impl IntoIterator<Item = KeyValue>,
) {
for kv in new_attrs {
upsert_attribute(attrs, kv);
}
}