#[cfg(not(feature = "std"))]
use alloc::{borrow::Cow, string::String, vec::Vec};
#[cfg(feature = "std")]
use std::borrow::Cow;
#[derive(Debug, Clone)]
pub struct ContextLayer {
pub(crate) key: Option<Cow<'static, str>>,
pub(crate) value: ContextValue,
}
impl ContextLayer {
pub fn with_key<K, V>(key: K, value: V) -> Self
where
K: Into<Cow<'static, str>>,
V: IntoContextValue,
{
Self {
key: Some(key.into()),
value: value.into_context_value(),
}
}
pub fn text<T: Into<Cow<'static, str>>>(text: T) -> Self {
Self {
key: None,
value: ContextValue::Text(text.into()),
}
}
pub fn key(&self) -> Option<&str> {
self.key.as_deref()
}
pub fn value(&self) -> &ContextValue {
&self.value
}
}
#[derive(Debug, Clone)]
pub enum ContextValue {
Text(Cow<'static, str>),
Debugged(String),
}
impl ContextValue {
pub fn as_str(&self) -> &str {
match self {
ContextValue::Text(s) => s.as_ref(),
ContextValue::Debugged(s) => s.as_str(),
}
}
}
pub trait IntoContextValue {
fn into_context_value(self) -> ContextValue;
}
impl IntoContextValue for String {
fn into_context_value(self) -> ContextValue {
ContextValue::Text(Cow::Owned(self))
}
}
impl IntoContextValue for &'static str {
fn into_context_value(self) -> ContextValue {
ContextValue::Text(Cow::Borrowed(self))
}
}
impl IntoContextValue for Cow<'static, str> {
fn into_context_value(self) -> ContextValue {
ContextValue::Text(self)
}
}
macro_rules! impl_into_context_value_debug {
($($t:ty),*) => {
$(
impl IntoContextValue for $t {
fn into_context_value(self) -> ContextValue {
#[cfg(feature = "std")]
{
ContextValue::Debugged(format!("{:?}", self))
}
#[cfg(not(feature = "std"))]
{
use alloc::format;
ContextValue::Debugged(format!("{:?}", self))
}
}
}
)*
};
}
impl_into_context_value_debug!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, bool, char
);
#[derive(Debug, Clone, Default)]
pub(crate) struct ContextChain {
layers: Vec<ContextLayer>,
}
impl ContextChain {
pub fn new() -> Self {
Self { layers: Vec::new() }
}
pub fn push(&mut self, layer: ContextLayer) {
self.layers.push(layer);
}
pub fn iter(&self) -> impl Iterator<Item = &ContextLayer> {
self.layers.iter()
}
pub fn is_empty(&self) -> bool {
self.layers.is_empty()
}
#[allow(dead_code)]
pub fn len(&self) -> usize {
self.layers.len()
}
}