use std::fmt::{
self,
Debug,
Display,
Formatter,
Write as _,
};
use crate::{
BoundedRedactedDisplay,
LogOutputLimit,
Redact,
RedactionPolicy,
text::internal::LogEscapeWriter,
};
#[must_use = "format or serialize the redacted view"]
pub struct Redacted<'a, T: ?Sized> {
value: &'a T,
policy: RedactionPolicy,
}
impl<'a, T: ?Sized> Redacted<'a, T> {
#[inline(always)]
pub(crate) const fn new(value: &'a T, policy: RedactionPolicy) -> Self {
Self { value, policy }
}
#[inline(always)]
pub const fn with_output_limit(
self,
limit: LogOutputLimit,
) -> BoundedRedactedDisplay<Self> {
BoundedRedactedDisplay::new(self, limit)
}
#[must_use = "format the bounded redacted display adapter"]
#[inline]
pub fn with_policy_output_limit(self) -> BoundedRedactedDisplay<Self> {
let limit = LogOutputLimit::from(self.policy.diagnostic_budget());
BoundedRedactedDisplay::new(self, limit)
}
#[cfg(feature = "serde")]
#[inline(always)]
pub(crate) const fn value(&self) -> &'a T {
self.value
}
#[cfg(feature = "serde")]
#[inline(always)]
pub(crate) const fn policy(&self) -> &RedactionPolicy {
&self.policy
}
}
#[cfg(feature = "serde")]
impl<T: crate::domain::RedactSerialize + ?Sized> serde::Serialize
for Redacted<'_, T>
{
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.value().serialize_redacted(self.policy(), serializer)
}
}
impl<T: Redact + ?Sized> Debug for Redacted<'_, T> {
#[inline(always)]
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
self.value.fmt_redacted(&self.policy, formatter)
}
}
impl<T: Redact + ?Sized> Display for Redacted<'_, T> {
#[inline]
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
let mut writer = LogEscapeWriter::new(formatter);
write!(&mut writer, "{self:?}")
}
}