60
60
//! // Types implementing `Writeable` are recommended to also implement `fmt::Display`.
61
61
//! // This can be simply done by redirecting to the `Writeable` implementation:
62
62
//! writeable::impl_display_with_writeable!(WelcomeMessage<'_>);
63
+ //! assert_eq!(message.to_string(), "Hello, Alice!");
63
64
//! ```
64
65
//!
65
66
//! [`ICU4X`]: ../icu/index.html
@@ -116,10 +117,11 @@ pub mod adapters {
116
117
}
117
118
}
118
119
119
- #[ doc( hidden) ] // for testing
120
+ #[ doc( hidden) ] // for testing and macros
120
121
pub mod _internal {
121
122
pub use super :: testing:: try_writeable_to_parts_for_test;
122
123
pub use super :: testing:: writeable_to_parts_for_test;
124
+ pub use alloc:: string:: String ;
123
125
}
124
126
125
127
/// A hint to help consumers of `Writeable` pre-allocate bytes before they call
@@ -314,9 +316,13 @@ pub trait Writeable {
314
316
/// It's recommended to do this for every [`Writeable`] type, as it will add
315
317
/// support for `core::fmt` features like [`fmt!`](std::fmt),
316
318
/// [`print!`](std::print), [`write!`](std::write), etc.
319
+ ///
320
+ /// This macro also adds a concrete `to_string` function. This function will shadow the
321
+ /// standard library `ToString`, using the more efficient writeable-based code path.
322
+ /// To add only `Display`, use the `@display` macro variant.
317
323
#[ macro_export]
318
324
macro_rules! impl_display_with_writeable {
319
- ( $type: ty) => {
325
+ ( @display , $type: ty) => {
320
326
/// This trait is implemented for compatibility with [`fmt!`](alloc::fmt).
321
327
/// To create a string, [`Writeable::write_to_string`] is usually more efficient.
322
328
impl core:: fmt:: Display for $type {
@@ -326,6 +332,19 @@ macro_rules! impl_display_with_writeable {
326
332
}
327
333
}
328
334
} ;
335
+ ( $type: ty) => {
336
+ $crate:: impl_display_with_writeable!( @display, $type) ;
337
+ impl $type {
338
+ /// Converts the given value to a `String`.
339
+ ///
340
+ /// Under the hood, this uses an efficient [`Writeable`] implementation.
341
+ /// However, in order to avoid allocating a string, it is more efficient
342
+ /// to use [`Writeable`] directly.
343
+ pub fn to_string( & self ) -> $crate:: _internal:: String {
344
+ $crate:: Writeable :: write_to_string( self ) . into_owned( )
345
+ }
346
+ }
347
+ } ;
329
348
}
330
349
331
350
/// Testing macros for types implementing [`Writeable`].
0 commit comments