1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
45// https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations
6#![cfg_attr(not(any(test, doc)), no_std)]
7#![cfg_attr(
8 not(test),
9 deny(
10 clippy::indexing_slicing,
11 clippy::unwrap_used,
12 clippy::expect_used,
13 clippy::panic,
14 )
15)]
16#![warn(missing_docs)]
1718//! This crate defines [`Writeable`], a trait representing an object that can be written to a
19//! sink implementing `std::fmt::Write`. It is an alternative to `std::fmt::Display` with the
20//! addition of a function indicating the number of bytes to be written.
21//!
22//! `Writeable` improves upon `std::fmt::Display` in two ways:
23//!
24//! 1. More efficient, since the sink can pre-allocate bytes.
25//! 2. Smaller code, since the format machinery can be short-circuited.
26//!
27//! This crate also exports [`TryWriteable`], a writeable that supports a custom error.
28//!
29//! # Benchmarks
30//!
31//! The benchmarks to generate the following data can be found in the `benches` directory.
32//!
33//! | Case | `Writeable` | `Display` |
34//! |---|---|---|
35//! | Create string from single-string message (139 chars) | 15.642 ns | 19.251 ns |
36//! | Create string from complex message | 35.830 ns | 89.478 ns |
37//! | Write complex message to buffer | 57.336 ns | 64.408 ns |
38//!
39//! # Examples
40//!
41//! ```
42//! use std::fmt;
43//! use writeable::assert_writeable_eq;
44//! use writeable::LengthHint;
45//! use writeable::Writeable;
46//!
47//! struct WelcomeMessage<'s> {
48//! pub name: &'s str,
49//! }
50//!
51//! impl<'s> Writeable for WelcomeMessage<'s> {
52//! fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
53//! sink.write_str("Hello, ")?;
54//! sink.write_str(self.name)?;
55//! sink.write_char('!')?;
56//! Ok(())
57//! }
58//!
59//! fn writeable_length_hint(&self) -> LengthHint {
60//! // "Hello, " + '!' + length of name
61//! LengthHint::exact(8 + self.name.len())
62//! }
63//! }
64//!
65//! let message = WelcomeMessage { name: "Alice" };
66//! assert_writeable_eq!(&message, "Hello, Alice!");
67//!
68//! // Types implementing `Writeable` are recommended to also implement `fmt::Display`.
69//! // This can be simply done by redirecting to the `Writeable` implementation:
70//! writeable::impl_display_with_writeable!(WelcomeMessage<'_>);
71//! assert_eq!(message.to_string(), "Hello, Alice!");
72//! ```
73//!
74//! [`ICU4X`]: ../icu/index.html
7576#[cfg(feature = "alloc")]
77extern crate alloc;
7879mod cmp;
80mod concat;
81#[cfg(feature = "either")]
82mod either;
83mod impls;
84mod ops;
85mod parts_write_adapter;
86mod replace;
87#[cfg(feature = "alloc")]
88mod testing;
89#[cfg(feature = "alloc")]
90mod to_string_or_borrow;
91mod try_writeable;
9293#[cfg(feature = "alloc")]
94use alloc::borrow::Cow;
9596#[cfg(feature = "alloc")]
97use alloc::string::String;
98use core::fmt;
99100pub use cmp::{cmp_str, cmp_utf8};
101pub use concat::concat_writeable;
102#[cfg(feature = "alloc")]
103pub use to_string_or_borrow::to_string_or_borrow;
104pub use try_writeable::TryWriteable;
105106/// Helper types for trait impls.
107pub mod adapters {
108use super::*;
109110pub use concat::Concat;
111pub use parts_write_adapter::CoreWriteAsPartsWrite;
112pub use parts_write_adapter::WithPart;
113pub use replace::Replace;
114pub use try_writeable::TryWriteableInfallibleAsWriteable;
115pub use try_writeable::WriteableAsTryWriteableInfallible;
116117/// A lossy wrapper for a [`TryWriteable`] that implements [`Writeable`]
118 /// and ignores any errors.
119#[derive(#[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for LossyWrap<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "LossyWrap",
&&self.0)
}
}Debug, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::clone::Clone> ::core::clone::Clone for LossyWrap<T> {
#[inline]
fn clone(&self) -> LossyWrap<T> {
LossyWrap(::core::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::marker::Copy> ::core::marker::Copy for LossyWrap<T> { }Copy, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for LossyWrap<T> {
#[inline]
fn eq(&self, other: &LossyWrap<T>) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for LossyWrap<T> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) { let _: ::core::cmp::AssertParamIsEq<T>; }
}Eq, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for LossyWrap<T> {
#[inline]
fn partial_cmp(&self, other: &LossyWrap<T>)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
}
}PartialOrd, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::Ord> ::core::cmp::Ord for LossyWrap<T> {
#[inline]
fn cmp(&self, other: &LossyWrap<T>) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}Ord, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::hash::Hash> ::core::hash::Hash for LossyWrap<T> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
120 #[repr(transparent)]
121 #[allow(clippy::exhaustive_structs)] // newtype
122pub struct LossyWrap<T>(pub T);
123124impl<T: TryWriteable> Writeablefor LossyWrap<T> {
125#[inline]
126fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
127let _ = self.0.try_write_to(sink)?;
128Ok(())
129 }
130131#[inline]
132fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
133let _ = self.0.try_write_to_parts(sink)?;
134Ok(())
135 }
136137#[inline]
138fn writeable_length_hint(&self) -> LengthHint {
139self.0.writeable_length_hint()
140 }
141142#[inline]
143fn writeable_borrow(&self) -> Option<&str> {
144match self.0.try_writeable_borrow()? {
145Ok(s) => Some(s),
146Err((_err, s)) => Some(s),
147 }
148 }
149150#[inline]
151 #[cfg(feature = "alloc")]
152fn write_to_string(&self) -> Cow<'_, str> {
153match self.0.try_write_to_string() {
154Ok(s) => s,
155Err((_err, s)) => s,
156 }
157 }
158 }
159160/// This trait is implemented for compatibility with [`fmt!`](core::fmt).
/// To create a string, [`Writeable::write_to_string`] is usually more efficient.
impl<T: TryWriteable> core::fmt::Display for LossyWrap<T> {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
crate::Writeable::write_to(&self, f)
}
}impl_display_with_writeable!(LossyWrap<T>, #[cfg(feature = "alloc")], where T: TryWriteable);
161}
162163#[doc(hidden)] // for testing and macros
164pub mod _internal {
165#[cfg(feature = "alloc")]
166pub use super::testing::try_writeable_to_parts_for_test;
167#[cfg(feature = "alloc")]
168pub use super::testing::writeable_to_parts_for_test;
169#[cfg(feature = "alloc")]
170pub use alloc::borrow::Cow;
171#[cfg(feature = "alloc")]
172pub use alloc::string::String;
173}
174175/// A hint to help consumers of `Writeable` pre-allocate bytes before they call
176/// [`write_to`](Writeable::write_to).
177///
178/// This behaves like `Iterator::size_hint`: it is a tuple where the first element is the
179/// lower bound, and the second element is the upper bound. If the upper bound is `None`
180/// either there is no known upper bound, or the upper bound is larger than `usize`.
181///
182/// `LengthHint` implements std`::ops::{Add, Mul}` and similar traits for easy composition.
183/// During computation, the lower bound will saturate at `usize::MAX`, while the upper
184/// bound will become `None` if `usize::MAX` is exceeded.
185#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LengthHint {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field2_finish(f, "LengthHint",
&self.0, &&self.1)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for LengthHint {
#[inline]
fn eq(&self, other: &LengthHint) -> bool {
self.0 == other.0 && self.1 == other.1
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LengthHint {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<Option<usize>>;
}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for LengthHint { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LengthHint {
#[inline]
fn clone(&self) -> LengthHint {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<Option<usize>>;
*self
}
}Clone)]
186#[non_exhaustive]
187pub struct LengthHint(pub usize, pub Option<usize>);
188189impl LengthHint {
190/// Unknown
191pub fn undefined() -> Self {
192Self(0, None)
193 }
194195/// `write_to` will use exactly n bytes.
196pub fn exact(n: usize) -> Self {
197Self(n, Some(n))
198 }
199200/// `write_to` will use at least n bytes.
201pub fn at_least(n: usize) -> Self {
202Self(n, None)
203 }
204205/// `write_to` will use at most n bytes.
206pub fn at_most(n: usize) -> Self {
207Self(0, Some(n))
208 }
209210/// `write_to` will use between `n` and `m` bytes.
211pub fn between(n: usize, m: usize) -> Self {
212Self(Ord::min(n, m), Some(Ord::max(n, m)))
213 }
214215/// Returns a recommendation for the number of bytes to pre-allocate.
216 /// If an upper bound exists, this is used, otherwise the lower bound
217 /// (which might be 0).
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// use writeable::Writeable;
223 ///
224 /// fn pre_allocate_string(w: &impl Writeable) -> String {
225 /// String::with_capacity(w.writeable_length_hint().capacity())
226 /// }
227 /// ```
228pub fn capacity(&self) -> usize {
229self.1.unwrap_or(self.0)
230 }
231232/// Returns whether the `LengthHint` indicates that the string is exactly 0 bytes long.
233pub fn is_zero(&self) -> bool {
234self.1 == Some(0)
235 }
236}
237238/// [`Part`]s are used as annotations for formatted strings.
239///
240/// For example, a string like `Alice, Bob` could assign a `NAME` part to the
241/// substrings `Alice` and `Bob`, and a `PUNCTUATION` part to `, `. This allows
242/// for example to apply styling only to names.
243///
244/// `Part` contains two fields, whose usage is left up to the producer of the [`Writeable`].
245/// Conventionally, the `category` field will identify the formatting logic that produces
246/// the string/parts, whereas the `value` field will have semantic meaning. `NAME` and
247/// `PUNCTUATION` could thus be defined as
248/// ```
249/// # use writeable::Part;
250/// const NAME: Part = Part {
251/// category: "userlist",
252/// value: "name",
253/// };
254/// const PUNCTUATION: Part = Part {
255/// category: "userlist",
256/// value: "punctuation",
257/// };
258/// ```
259///
260/// That said, consumers should not usually have to inspect `Part` internals. Instead,
261/// formatters should expose the `Part`s they produces as constants.
262#[derive(#[automatically_derived]
#[allow(clippy::exhaustive_structs)]
#[allow(missing_docs)]
impl ::core::clone::Clone for Part {
#[inline]
fn clone(&self) -> Part {
let _: ::core::clone::AssertParamIsClone<&'static str>;
let _: ::core::clone::AssertParamIsClone<&'static str>;
*self
}
}Clone, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
#[allow(missing_docs)]
impl ::core::marker::Copy for Part { }Copy, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
#[allow(missing_docs)]
impl ::core::fmt::Debug for Part {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Part",
"category", &self.category, "value", &&self.value)
}
}Debug, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
#[allow(missing_docs)]
impl ::core::cmp::PartialEq for Part {
#[inline]
fn eq(&self, other: &Part) -> bool {
self.category == other.category && self.value == other.value
}
}PartialEq)]
263#[allow(clippy::exhaustive_structs)] // stable
264#[allow(missing_docs)] // behavior not defined, explained in type docs
265pub struct Part {
266pub category: &'static str,
267pub value: &'static str,
268}
269270impl Part {
271/// A part that should annotate error segments in [`TryWriteable`] output.
272 ///
273 /// For an example, see [`TryWriteable`].
274pub const ERROR: Part = Part {
275 category: "writeable",
276 value: "error",
277 };
278}
279280/// A sink that supports annotating parts of the string with [`Part`]s.
281pub trait PartsWrite: fmt::Write {
282/// The recursive sink
283type SubPartsWrite: PartsWrite + ?Sized;
284285/// Annotates all strings written by the closure with the given [`Part`].
286fn with_part(
287&mut self,
288 part: Part,
289 f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result,
290 ) -> fmt::Result;
291}
292293/// `Writeable` is an alternative to `std::fmt::Display` with the addition of a length function.
294pub trait Writeable {
295/// Writes a string to the given sink. Errors from the sink are bubbled up.
296 /// The default implementation delegates to `write_to_parts`, and discards any
297 /// `Part` annotations.
298fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
299self.write_to_parts(&mut parts_write_adapter::CoreWriteAsPartsWrite(sink))
300 }
301302/// Write bytes and `Part` annotations to the given sink. Errors from the
303 /// sink are bubbled up. The default implementation delegates to `write_to`,
304 /// and doesn't produce any `Part` annotations.
305fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
306self.write_to(sink)
307 }
308309/// Returns a hint for the number of UTF-8 bytes that will be written to the sink.
310 ///
311 /// Override this method if it can be computed quickly.
312fn writeable_length_hint(&self) -> LengthHint {
313LengthHint::undefined()
314 }
315316/// Returns a `&str` that matches the output of `write_to`, if possible.
317 ///
318 /// This method is used to avoid materializing a [`String`] in `write_to_string`.
319fn writeable_borrow(&self) -> Option<&str> {
320None321 }
322323/// Creates a new string with the data from this `Writeable`.
324 ///
325 /// Unlike [`to_string`](ToString::to_string), this does not pull in `core::fmt`
326 /// code, and borrows the string if possible.
327 ///
328 /// To remove the `Cow` wrapper, call `.into_owned()` or `.as_str()` as appropriate.
329 ///
330 /// # Examples
331 ///
332 /// Inspect a [`Writeable`] before writing it to the sink:
333 ///
334 /// ```
335 /// use core::fmt::{Result, Write};
336 /// use writeable::Writeable;
337 ///
338 /// fn write_if_ascii<W, S>(w: &W, sink: &mut S) -> Result
339 /// where
340 /// W: Writeable + ?Sized,
341 /// S: Write + ?Sized,
342 /// {
343 /// let s = w.write_to_string();
344 /// if s.is_ascii() {
345 /// sink.write_str(&s)
346 /// } else {
347 /// Ok(())
348 /// }
349 /// }
350 /// ```
351 ///
352 /// Convert the `Writeable` into a fully owned `String`:
353 ///
354 /// ```
355 /// use writeable::Writeable;
356 ///
357 /// fn make_string(w: &impl Writeable) -> String {
358 /// w.write_to_string().into_owned()
359 /// }
360 /// ```
361 ///
362 /// # Note to implementors
363 ///
364 /// This method has a default implementation in terms of `writeable_borrow`,
365 /// `writeable_length_hint`, and `write_to`. The only case
366 /// where this should be implemented is if the computation of `writeable_borrow`
367 /// requires a full invocation of `write_to`. In this case, implement this
368 /// using [`to_string_or_borrow`].
369 ///
370 /// # `alloc` Cargo feature
371 ///
372 /// Calling or implementing this method requires the `alloc` Cargo feature.
373 /// However, as all the methods required by the default implementation do
374 /// not require the `alloc` Cargo feature, a caller that uses the feature
375 /// can still call this on types from crates that don't use the `alloc`
376 /// Cargo feature.
377#[cfg(feature = "alloc")]
378fn write_to_string(&self) -> Cow<'_, str> {
379if let Some(borrow) = self.writeable_borrow() {
380return Cow::Borrowed(borrow);
381 }
382let hint = self.writeable_length_hint();
383if hint.is_zero() {
384return Cow::Borrowed("");
385 }
386let mut output = String::with_capacity(hint.capacity());
387let _ = self.write_to(&mut output);
388 Cow::Owned(output)
389 }
390}
391392/// Macro to implement [`Writeable`] by delegating to another `Writeable`.
393///
394/// Useful for wrapper types.
395///
396/// # Examples
397///
398/// ```
399/// struct MyStruct(String);
400/// writeable::impl_writeable_delegate!(MyStruct, |&self| &self.0);
401/// writeable::impl_display_with_writeable!(MyStruct);
402///
403/// writeable::assert_writeable_eq!(MyStruct("hello".to_string()), "hello");
404/// ```
405///
406/// With a cfg on fn `write_to_string`:
407///
408/// ```
409/// struct MyStruct(String);
410/// writeable::impl_writeable_delegate!(MyStruct, |&self| &self.0, #[cfg(feature = "alloc")] fn write_to_string);
411/// writeable::impl_display_with_writeable!(MyStruct, #[cfg(feature = "alloc")]);
412///
413/// writeable::assert_writeable_eq!(
414/// MyStruct("hello".to_string()),
415/// "hello"
416/// );
417/// ```
418///
419/// With generics:
420///
421/// ```
422/// use writeable::Writeable;
423///
424/// struct MyStruct<T>(T);
425/// writeable::impl_writeable_delegate!(MyStruct<T>, |&self| &self.0, where T: Writeable);
426/// writeable::impl_display_with_writeable!(MyStruct<T>, where T: Writeable);
427///
428/// writeable::assert_writeable_eq!(
429/// MyStruct("hello"),
430/// "hello"
431/// );
432/// ```
433#[macro_export]
434macro_rules!impl_writeable_delegate {
435 ($ty:ty, |&$self:ident| $delegate:expr $(, #[$alloc_feature:meta] fn write_to_string)? $(, where $($generics:tt)*)?) => {
436impl $(<$($generics)*>)? $crate::Writeable for $ty {
437#[inline]
438fn write_to<W: core::fmt::Write + ?Sized>(&$self, sink: &mut W) -> core::fmt::Result {
439 ($delegate).write_to(sink)
440 }
441#[inline]
442fn write_to_parts<S: $crate::PartsWrite + ?Sized>(&$self, sink: &mut S) -> core::fmt::Result {
443 ($delegate).write_to_parts(sink)
444 }
445#[inline]
446fn writeable_length_hint(&$self) -> $crate::LengthHint {
447 ($delegate).writeable_length_hint()
448 }
449#[inline]
450fn writeable_borrow(&$self) -> Option<&str> {
451 ($delegate).writeable_borrow()
452 }
453#[inline]
454$(#[$alloc_feature])?
455fn write_to_string(&$self) -> $crate::_internal::Cow<'_, str> {
456 ($delegate).write_to_string()
457 }
458 }
459 };
460}
461462/// Implements [`Display`](core::fmt::Display) for types that implement [`Writeable`].
463///
464/// It's recommended to do this for every [`Writeable`] type, as it will add
465/// support for `core::fmt` features like [`fmt!`](std::fmt),
466/// [`print!`](std::print), [`write!`](std::write), etc.
467///
468/// This macro also adds a concrete `to_string` function. This function will shadow the
469/// standard library `ToString`, using the more efficient writeable-based code path.
470/// To add only `Display`, use the `@display` macro variant.
471///
472/// If your type has generics, list them in a `where` clause in the macro invocation.
473///
474/// # Examples
475///
476/// ```
477/// use writeable::Writeable;
478/// use std::fmt;
479///
480/// struct Message<T>(T);
481///
482/// impl<T> Writeable for Message<T> where T: Writeable {
483/// fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
484/// sink.write_str("Message: ")?;
485/// self.0.write_to(sink)
486/// }
487/// // ...
488/// }
489///
490/// writeable::impl_display_with_writeable!(Message<T>, where T: Writeable);
491///
492/// writeable::assert_writeable_eq!(Message("hello"), "Message: hello");
493/// ```
494#[macro_export]
495macro_rules!impl_display_with_writeable {
496 (@display, $type:ty $(, where $($generics:tt)*)?) => {
497/// This trait is implemented for compatibility with [`fmt!`](core::fmt).
498 /// To create a string, [`Writeable::write_to_string`] is usually more efficient.
499impl $(<$($generics)*>)? core::fmt::Display for $type {
500#[inline]
501fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
502$crate::Writeable::write_to(&self, f)
503 }
504 }
505 };
506 ($type:ty $(, #[$alloc_feature:meta])? $(, where $($generics:tt)*)?) => {
507$crate::impl_display_with_writeable!(@display, $type $(, where $($generics)*)?);
508 $(#[$alloc_feature])?
509impl $(<$($generics)*>)? $type {
510/// Converts the given value to a `String`.
511 ///
512 /// Under the hood, this uses an efficient [`Writeable`] implementation.
513 ///
514 /// If you don't need an allocated [`String`], but e.g. need to write this
515 /// to some sink, it is more efficient to use [`Writeable`] directly.
516pub fn to_string(&self) -> $crate::_internal::String {
517$crate::Writeable::write_to_string(self).into_owned()
518 }
519 }
520 };
521}
522523/// Testing macros for types implementing [`Writeable`].
524///
525/// Arguments, in order:
526///
527/// 1. The [`Writeable`] under test
528/// 2. The expected string value
529/// 3. [`*_parts_eq`] only: a list of parts (`[(start, end, Part)]`)
530///
531/// Any remaining arguments get passed to `format!`
532///
533/// The macros tests the following:
534///
535/// - Equality of string content
536/// - Equality of parts ([`*_parts_eq`] only)
537/// - Validity of size hint
538///
539/// # Examples
540///
541/// ```
542/// # use writeable::Writeable;
543/// # use writeable::LengthHint;
544/// # use writeable::Part;
545/// # use writeable::assert_writeable_eq;
546/// # use writeable::assert_writeable_parts_eq;
547/// # use std::fmt::{self, Write};
548///
549/// const WORD: Part = Part {
550/// category: "foo",
551/// value: "word",
552/// };
553///
554/// struct Demo;
555/// impl Writeable for Demo {
556/// fn write_to_parts<S: writeable::PartsWrite + ?Sized>(
557/// &self,
558/// sink: &mut S,
559/// ) -> fmt::Result {
560/// sink.with_part(WORD, |w| w.write_str("foo"))
561/// }
562/// fn writeable_length_hint(&self) -> LengthHint {
563/// LengthHint::exact(3)
564/// }
565/// }
566///
567/// writeable::impl_display_with_writeable!(Demo);
568///
569/// assert_writeable_eq!(&Demo, "foo");
570/// assert_writeable_eq!(&Demo, "foo", "Message: {}", "Hello World");
571///
572/// assert_writeable_parts_eq!(&Demo, "foo", [(0, 3, WORD)]);
573/// assert_writeable_parts_eq!(
574/// &Demo,
575/// "foo",
576/// [(0, 3, WORD)],
577/// "Message: {}",
578/// "Hello World"
579/// );
580/// ```
581///
582/// [`*_parts_eq`]: assert_writeable_parts_eq
583#[macro_export]
584#[cfg(feature = "alloc")]
585macro_rules! assert_writeable_eq {
586 ($actual_writeable:expr, $expected_str:expr $(,)?) => {
587$crate::assert_writeable_eq!($actual_writeable, $expected_str, "")
588 };
589 ($actual_writeable:expr, $expected_str:expr, $($arg:tt)+) => {{
590$crate::assert_writeable_eq!(@internal, $actual_writeable, $expected_str, $($arg)*);
591 }};
592 (@internal, $actual_writeable:expr, $expected_str:expr, $($arg:tt)+) => {{
593let actual_writeable = &$actual_writeable;
594let (actual_str, actual_parts) = $crate::_internal::writeable_to_parts_for_test(actual_writeable);
595let actual_len = actual_str.len();
596assert_eq!(actual_str, $expected_str, $($arg)*);
597let cow = $crate::Writeable::write_to_string(actual_writeable);
598assert_eq!(actual_str, cow, $($arg)+);
599if let Some(borrowed) = ($crate::Writeable::writeable_borrow(&actual_writeable)) {
600assert_eq!(borrowed, $expected_str, $($arg)*);
601assert!(matches!(cow, std::borrow::Cow::Borrowed(_)), $($arg)*);
602 }
603let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
604let lower = length_hint.0;
605assert!(
606 lower <= actual_len,
607"hint lower bound {lower} larger than actual length {actual_len}: {}",
608format!($($arg)*),
609 );
610if let Some(upper) = length_hint.1 {
611assert!(
612 actual_len <= upper,
613"hint upper bound {upper} smaller than actual length {actual_len}: {}",
614format!($($arg)*),
615 );
616 }
617assert_eq!(actual_writeable.to_string(), $expected_str, $($arg)*);
618 actual_parts // return for assert_writeable_parts_eq
619}};
620}
621622/// See [`assert_writeable_eq`].
623#[macro_export]
624#[cfg(feature = "alloc")]
625macro_rules! assert_writeable_parts_eq {
626 ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr $(,)?) => {
627$crate::assert_writeable_parts_eq!($actual_writeable, $expected_str, $expected_parts, "")
628 };
629 ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr, $($arg:tt)+) => {{
630let actual_parts = $crate::assert_writeable_eq!(@internal, $actual_writeable, $expected_str, $($arg)*);
631assert_eq!(actual_parts, $expected_parts, $($arg)+);
632 }};
633}