use crate::cfg;
cfg::alloc! {
use alloc::{borrow::Cow, fmt, string::String};
}
#[cfg(feature = "debug")]
use core::any::type_name;
use core::ops::Deref;
use disqualified::ShortName;
#[cfg(not(feature = "debug"))]
const FEATURE_DISABLED: &str = "<Enable the debug feature to see the name>";
#[derive(Clone, PartialEq, Eq)]
pub struct DebugName {
#[cfg(feature = "debug")]
name: Cow<'static, str>,
}
cfg::alloc! {
impl fmt::Display for DebugName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", &**self)
}
}
impl fmt::Debug for DebugName {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?}", &**self)
}
}
}
impl DebugName {
#[cfg_attr(
not(feature = "debug"),
expect(
unused_variables,
reason = "The value will be ignored if the `debug` feature is not enabled"
)
)]
pub const fn borrowed(value: &'static str) -> Self {
DebugName {
#[cfg(feature = "debug")]
name: Cow::Borrowed(value),
}
}
cfg::alloc! {
#[cfg_attr(
not(feature = "debug"),
expect(
unused_variables,
reason = "The value will be ignored if the `debug` feature is not enabled"
)
)]
pub fn owned(value: String) -> Self {
DebugName {
#[cfg(feature = "debug")]
name: Cow::Owned(value),
}
}
}
pub fn type_name<T>() -> Self {
DebugName {
#[cfg(feature = "debug")]
name: Cow::Borrowed(type_name::<T>()),
}
}
pub fn shortname(&self) -> ShortName<'_> {
#[cfg(feature = "debug")]
return ShortName(self.name.as_ref());
#[cfg(not(feature = "debug"))]
return ShortName(FEATURE_DISABLED);
}
#[cfg(feature = "debug")]
pub fn as_string(&self) -> String {
self.name.clone().into_owned()
}
}
impl Deref for DebugName {
type Target = str;
fn deref(&self) -> &Self::Target {
#[cfg(feature = "debug")]
return &self.name;
#[cfg(not(feature = "debug"))]
return FEATURE_DISABLED;
}
}
cfg::alloc! {
impl From<Cow<'static, str>> for DebugName {
#[cfg_attr(
not(feature = "debug"),
expect(
unused_variables,
reason = "The value will be ignored if the `debug` feature is not enabled"
)
)]
fn from(value: Cow<'static, str>) -> Self {
Self {
#[cfg(feature = "debug")]
name: value,
}
}
}
impl From<String> for DebugName {
fn from(value: String) -> Self {
Self::owned(value)
}
}
impl From<DebugName> for Cow<'static, str> {
#[cfg_attr(
not(feature = "debug"),
expect(
unused_variables,
reason = "The value will be ignored if the `debug` feature is not enabled"
)
)]
fn from(value: DebugName) -> Self {
#[cfg(feature = "debug")]
{
value.name
}
#[cfg(not(feature = "debug"))]
{
Cow::Borrowed(FEATURE_DISABLED)
}
}
}
}
impl From<&'static str> for DebugName {
fn from(value: &'static str) -> Self {
Self::borrowed(value)
}
}