impl_more/display.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
/// Implements [`Display`] for structs by forwarding to one of its field.
///
/// Emitted code is not compatible with `#[no_std]`.
///
/// Newtype structs can omit the field identifier.
///
/// # Examples
///
/// For newtype struct:
///
/// ```
/// # use impl_more::forward_display;
/// struct Foo(String);
///
/// impl_more::forward_display!(Foo);
///
/// assert_eq!(Foo("hello world".to_owned()).to_string(), "hello world");
/// ```
///
/// For struct with named field:
///
/// ```
/// # use impl_more::forward_display;
/// struct Bar {
/// inner: u64,
/// }
///
/// impl_more::forward_display!(Bar => inner);
///
/// assert_eq!(Bar { inner: 42 }.to_string(), "42");
/// ```
///
/// For generic newtype struct (note that `Display` bounds are applied to all type parameters):
///
/// ```
/// # use impl_more::forward_display;
/// struct Baz<T>(T);
///
/// impl_more::forward_display!(<T> in Baz<T>);
///
/// assert_eq!(Baz(42u64).to_string(), "42");
/// ```
///
/// [`Display`]: std::fmt::Display
#[macro_export]
macro_rules! forward_display {
(<$($generic:ident),+> in $this:ty => $field:ident) => {
impl <$($generic: ::core::fmt::Display),+> ::core::fmt::Display for $this {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Display::fmt(&self.$field, fmt)
}
}
};
(<$($generic:ident),+> in $this:ty) => {
impl <$($generic: ::core::fmt::Display),+> ::core::fmt::Display for $this {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Display::fmt(&self.0, fmt)
}
}
};
($ty:ty) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Display::fmt(&self.0, fmt)
}
}
};
($ty:ty => $field:ident) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Display::fmt(&self.$field, fmt)
}
}
};
}
/// Implements [`Display`] for structs using a `format!`-like string constructor.
///
/// # Examples
///
/// Display implementation can be just a string literal.
///
/// ```
/// # use impl_more::forward_display;
/// struct Hello;
/// impl_more::impl_display!(Foo; "hello world");
/// assert_eq!(Hello.to_string(), "hello world");
/// ```
///
/// Explicit and inline format args are supported.
///
/// ```
/// # use impl_more::forward_display;
/// struct Hello2;
/// impl_more::impl_display!(Foo; "hello world {}", 2);
/// assert_eq!(Hello2.to_string(), "hello world 2");
///
/// const HI: &str = "hello"
///
/// struct Hello3;
/// impl_more::impl_display!(Foo; "{HI} world");
/// assert_eq!(Foo.to_string(), "hello world");
/// ```
///
/// [`Display`]: std::fmt::Display
#[macro_export]
macro_rules! impl_display {
// no format args
($ty:ty; $format:literal) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::write!(fmt, $format)
}
}
};
// with explicit format args
($ty:ty; $format:literal, $($args:expr),+) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::write!(fmt, $format, $($args),+)
}
}
};
// strip trailing comma and forward to format args branch
($ty:ty; $format:literal, $($args:expr),+ ,) => {
$crate::impl_display!($ty; $format, $($args),+);
};
}
/// Implements [`Display`] for enums using a static string or format args for each variant.
///
/// # Examples
///
/// ```
/// # extern crate alloc;
/// use impl_more::impl_display_enum;
///
/// enum Foo {
/// Bar,
/// Qux,
/// }
///
/// impl_display_enum!(Foo, Bar => "bar", Qux => "qux");
///
/// assert_eq!(Foo::Bar.to_string(), "bar");
/// assert_eq!(Foo::Qux.to_string(), "qux");
///
/// enum CoordOrMsg {
/// Coord(i64, i64),
/// Msg(&'static str),
/// }
///
/// impl_display_enum!(CoordOrMsg, Coord(x, y) => "{x}, {y}", Msg(msg) => "message: {msg}");
///
/// assert_eq!(CoordOrMsg::Coord(4, 2).to_string(), "4, 2");
/// assert_eq!(CoordOrMsg::Msg("hi").to_string(), "message: hi");
/// ```
///
/// [`Display`]: std::fmt::Display
#[macro_export]
macro_rules! impl_display_enum {
($ty:ty, $($variant:ident => $stringified:literal),+) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.write_str(match self {
$(
Self::$variant => $stringified,
)*
})
}
}
};
($ty:ty, $($variant:ident => $stringified:literal),+ ,) => {
$crate::impl_display_enum!($ty, $($variant => $stringified),+);
};
($ty:ty, $($variant:ident ($($inner:ident),+) => $format:literal),+) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
use ::core::fmt::Write as _;
// a more efficient method (format_args) is blocked by:
// https://github.com/rust-lang/rust/issues/15023
let mut buf = ::std::string::String::new();
match self {
$(
Self::$variant($($inner),+) =>
::core::write!(&mut buf, $format, $($inner = $inner),+)?,
)*
};
fmt.write_str(&buf)
}
}
};
($ty:ty, $($variant:ident ($($inner:ident),+) => $format:literal),+ ,) => {
$crate::impl_display_enum!($ty, $($variant ($($inner),+) => $format),+);
};
($ty:ty, $($variant:ident { $($inner:ident),+ } => $format:literal),+) => {
impl ::core::fmt::Display for $ty {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
use ::core::fmt::Write as _;
// a more efficient method (format_args) is blocked by:
// https://github.com/rust-lang/rust/issues/15023
let mut buf = ::std::string::String::new();
match self {
$(
Self::$variant { $($inner),+ } =>
::core::write!(&mut buf, $format, $($inner = $inner),+)?,
)*
};
fmt.write_str(&buf)
}
}
};
($ty:ty, $($variant:ident { $($inner:ident),+ } => $format:literal),+ ,) => {
$crate::impl_display_enum!($ty, $($variant ($($inner),+) => $format),+);
};
// TODO: mixed named and positional variant support
}
#[cfg(test)]
mod tests {
use alloc::{
borrow::ToOwned as _,
string::{String, ToString as _},
};
#[test]
fn impl_forward_for_newtype_struct() {
struct Foo(String);
forward_display!(Foo);
assert_eq!(Foo("hello world".to_owned()).to_string(), "hello world");
}
#[test]
fn impl_forward_newtype_named_struct() {
struct Foo {
inner: u64,
}
forward_display!(Foo => inner);
assert_eq!(Foo { inner: 42 }.to_string(), "42");
}
#[test]
fn impl_forward_generic_newtype_struct() {
struct Foo<T>(T);
forward_display!(<T> in Foo<T>);
assert_eq!(Foo(42).to_string(), "42");
}
#[test]
fn impl_forward_generic_named_struct() {
struct Foo<T> {
inner: T,
}
forward_display!(<T> in Foo<T> => inner);
assert_eq!(Foo { inner: 42 }.to_string(), "42");
}
#[test]
fn impl_basic_for_unit_struct() {
struct Foo;
impl_display!(Foo; "foo");
assert_eq!(Foo.to_string(), "foo");
}
#[test]
fn impl_basic_with_args() {
struct Foo;
impl_display!(Foo; "foo {} {}", 2, 3);
assert_eq!(Foo.to_string(), "foo 2 3");
}
#[rustversion::stable(1.58)]
#[test]
fn impl_basic_with_inline_args() {
const HI: &str = "hello";
struct Hello3;
impl_display!(Hello3; "{HI} world");
assert_eq!(Hello3.to_string(), "hello world");
}
}