use std::{borrow::Cow, collections::HashMap};
use crate::LogValue;
pub type LogFieldsIter<'a> = std::collections::hash_map::Iter<'a, Cow<'static, str>, LogValue>;
pub type LogFieldsIntoIter = std::collections::hash_map::IntoIter<Cow<'static, str>, LogValue>;
pub type LogField = (Cow<'static, str>, LogValue);
pub type LogFieldRef<'a> = (&'a Cow<'static, str>, &'a LogValue);
#[derive(Debug, Clone, Default)]
pub struct LogFields(pub(crate) HashMap<Cow<'static, str>, LogValue>);
impl LogFields {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, key: impl Into<Cow<'static, str>>, value: impl Into<LogValue>) -> Self {
self.insert(key, value);
self
}
pub fn insert(
&mut self,
key: impl Into<Cow<'static, str>>,
value: impl Into<LogValue>,
) -> &mut Self {
self.0.insert(key.into(), value.into());
self
}
pub fn merge_with(&mut self, other: impl IntoIterator<Item = LogField>) -> &mut Self {
self.0.extend(other);
self
}
#[must_use]
pub fn iter(&self) -> LogFieldsIter<'_> {
self.0.iter()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<'a> IntoIterator for &'a LogFields {
type Item = LogFieldRef<'a>;
type IntoIter = LogFieldsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl IntoIterator for LogFields {
type Item = LogField;
type IntoIter = LogFieldsIntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl Extend<LogField> for LogFields {
fn extend<I: IntoIterator<Item = LogField>>(&mut self, iter: I) {
self.0.extend(iter);
}
}
impl FromIterator<LogField> for LogFields {
fn from_iter<T: IntoIterator<Item = LogField>>(iter: T) -> Self {
Self(HashMap::from_iter(iter))
}
}
#[cfg(test)]
impl LogFields {
pub(crate) fn find(&self, key: impl AsRef<str>) -> Option<&LogValue> {
self.0.get(&Cow::Owned(key.as_ref().to_owned()))
}
}
#[cfg(test)]
impl std::ops::Index<&str> for LogFields {
type Output = LogValue;
fn index(&self, index: &str) -> &Self::Output {
self.0
.get(&Cow::Owned(index.to_owned()))
.expect("No value found for the given key")
}
}