ast2str_lib/
utils.rs

1//! This module contains a simple wrapper for formatting [`Display`] objects as [`Debug`] and an extension method that can be called on strings.
2//! Mainly useful for testing.
3//!
4//! # Example:
5//! ```rust
6//! # use ast2str_lib as ast2str;
7//! use ast2str::utils::{DisplayAsDebugWrapper, AstToStrExt};
8//!
9//! assert_eq!(format!("{:?}", "foo".with_display_as_debug_wrapper()), "foo");
10//! assert_eq!(format!("{:?}", "foo"), "\"foo\"");
11//! assert_eq!(format!("{:?}", DisplayAsDebugWrapper("foo")), "foo");
12//! ```
13//! [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
14//! [`Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
15//!
16
17/// Wraps a type that implements [`Display`] and provides a [`Debug`] implementation that calls [`Display::fmt`].
18///
19/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
20/// [`Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
21/// [`Display::fmt`]: https://doc.rust-lang.org/std/fmt/trait.Display.html#tymethod.fmt
22#[allow(clippy::derive_partial_eq_without_eq)]
23#[derive(Clone, PartialEq)]
24pub struct DisplayAsDebugWrapper<T>(pub T);
25
26/// This trait provides a convenience method for wrapping types that implement [`Display`] with [`DisplayAsDebugWrapper`].
27/// Implemented for [`String`], [`str`], and [`Cow`] by default.
28///
29/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
30/// [`Cow`]: https://doc.rust-lang.org/std/borrow/enum.Cow.html
31pub trait AstToStrExt {
32    /// Wraps the object with a [`DisplayAsDebugWrapper`].
33    fn with_display_as_debug_wrapper(&self) -> DisplayAsDebugWrapper<&'_ Self>
34    where
35        Self: std::fmt::Display,
36    {
37        DisplayAsDebugWrapper(self)
38    }
39}
40impl AstToStrExt for String {}
41impl AstToStrExt for str {}
42impl<'a> AstToStrExt for std::borrow::Cow<'a, str> {}
43
44impl<T: std::fmt::Display> crate::AstToStr for DisplayAsDebugWrapper<T> {
45    fn ast_to_str_impl(&self, _: &dyn crate::Symbols) -> String {
46        format!("{:?}", self)
47    }
48}
49
50impl<T> std::fmt::Debug for DisplayAsDebugWrapper<T>
51where
52    T: std::fmt::Display,
53{
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "{}", self.0)
56    }
57}
58
59impl<T> std::ops::Deref for DisplayAsDebugWrapper<T> {
60    type Target = T;
61
62    fn deref(&self) -> &Self::Target {
63        &self.0
64    }
65}