use crate::rust::fmt;
use crate::rust::prelude::*;
pub trait ContextualDisplay<Context> {
type Error;
fn contextual_format(
&self,
f: &mut fmt::Formatter,
context: &Context,
) -> Result<(), Self::Error>;
fn format<TContext: Into<Context>>(
&self,
f: &mut fmt::Formatter,
context: TContext,
) -> Result<(), Self::Error> {
self.contextual_format(f, &context.into())
}
fn display<'a, TContext: Into<Context>>(
&'a self,
context: TContext,
) -> ContextDisplayable<'a, Self, Context> {
ContextDisplayable {
value: self,
context: context.into(),
}
}
fn debug_as_display<'a, TContext: Into<Context>>(
&'a self,
context: TContext,
) -> ContextDebuggableAsDisplay<'a, Self, Context> {
ContextDebuggableAsDisplay {
value: self,
context: context.into(),
}
}
fn to_string<TContext: Into<Context>>(&self, context: TContext) -> String {
self.display(context).to_string()
}
}
pub struct ContextDisplayable<'a, TValue, TContext>
where
TValue: ContextualDisplay<TContext> + ?Sized,
{
value: &'a TValue,
context: TContext,
}
impl<'a, TValue, TContext> fmt::Display for ContextDisplayable<'a, TValue, TContext>
where
TValue: ContextualDisplay<TContext> + ?Sized,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.value
.contextual_format(f, &self.context)
.map_err(|_| fmt::Error) }
}
pub struct ContextDebuggableAsDisplay<'a, TValue, TContext>
where
TValue: ContextualDisplay<TContext> + ?Sized,
{
value: &'a TValue,
context: TContext,
}
impl<'a, TValue, TContext> fmt::Debug for ContextDebuggableAsDisplay<'a, TValue, TContext>
where
TValue: ContextualDisplay<TContext> + ?Sized,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.value
.contextual_format(f, &self.context)
.map_err(|_| fmt::Error) }
}