Macro to_string_with_fallback

Source
macro_rules! to_string_with_fallback {
    ( $how : ty, $fallback1 : ty, $src : expr ) => { ... };
    ( $how : ty, $fallback1 : ty, $fallback2 : ty, $src : expr ) => { ... };
}
Expand description

Macro to convert a value to a string using a specified formatting method with a fallback.

§Parameters

  • $how: The primary formatting type (e.g., WithDebug, WithDisplay).
  • $fallback1: The first fallback formatting type.
  • $fallback2: The second fallback formatting type (optional).
  • $src: The source value to format.

§Example

use core::fmt;
use format_tools::
{
  WithRef,
  WithDebug,
  WithDisplay,
  to_string_with_fallback,
};

// Define a struct that implements both Debug and Display traits.
struct Both;

impl fmt::Debug for Both
{
  fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
  {
    write!( f, "This is debug" )
  }
}

impl fmt::Display for Both
{
  fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
  {
    write!( f, "This is display" )
  }
}

// Define a struct that implements only the Debug trait.
struct OnlyDebug;

impl fmt::Debug for OnlyDebug
{
  fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
  {
    write!( f, "This is debug" )
  }
}

// Example usage: Using Both which implements both Debug and Display.
let src = Both;
let got = to_string_with_fallback!( WithDisplay, WithDebug, &src );
let exp = "This is display".to_string();
// The primary formatting method WithDisplay is used.
assert_eq!( got, exp );

// Example usage: Using OnlyDebug which implements only Debug.
let src = OnlyDebug;
let got = to_string_with_fallback!( WithDisplay, WithDebug, &src );
let exp = "This is debug".to_string();
// The primary formatting method WithDisplay is not available, so the fallback WithDebug is used.
assert_eq!( got, exp );

// Example usage: Using a struct that might need a second fallback.
struct OnlyDebugFallback;

impl fmt::Debug for OnlyDebugFallback
{
  fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
  {
    write!( f, "This is debug fallback" )
  }
}

// Example usage: Using OnlyDebugFallback which implements only Debug.
let src = OnlyDebugFallback;
let got = to_string_with_fallback!( WithRef, WithDisplay, WithDebug, &src );
let exp = "This is debug fallback".to_string();
// The primary formatting method WithDisplay is not available, so the second fallback WithDebugFallback is used.
assert_eq!( got, exp );