From 4b06a3e2637812a13d501d14a80edafade8dff98 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 20 Oct 2022 10:28:23 -0700 Subject: [PATCH] Add test of Display impl nested inside display attribute --- tests/test_display.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/tests/test_display.rs b/tests/test_display.rs index 8917bb0..99ce2fd 100644 --- a/tests/test_display.rs +++ b/tests/test_display.rs @@ -1,4 +1,4 @@ -use std::fmt::Display; +use std::fmt::{self, Display}; use thiserror::Error; fn assert(expected: &str, value: T) { @@ -141,6 +141,35 @@ fn test_match() { ); } +#[test] +fn test_nested_display() { + // Same behavior as the one in `test_match`, but without String allocations. + #[derive(Error, Debug)] + #[error("{}", { + struct Msg<'a>(&'a String, &'a Option); + impl<'a> Display for Msg<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.1 { + Some(n) => write!(formatter, "error occurred with {}", n), + None => write!(formatter, "there was an empty error"), + }?; + write!(formatter, ": {}", self.0) + } + } + Msg(.0, .1) + })] + struct Error(String, Option); + + assert( + "error occurred with 1: ...", + Error("...".to_owned(), Some(1)), + ); + assert( + "there was an empty error: ...", + Error("...".to_owned(), None), + ); +} + #[test] fn test_void() { #[allow(clippy::empty_enum)]