| 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 ). |
| 4 |
|
| 5 |
// 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)] |
| 17 |
|
| 18 |
//! 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 |
| 75 |
|
| 76 |
#[cfg(feature = "alloc")] |
| 77 |
extern crate alloc; |
| 78 |
|
| 79 |
mod cmp; |
| 80 |
mod concat; |
| 81 |
#[cfg(feature = "either")] |
| 82 |
mod either; |
| 83 |
mod impls; |
| 84 |
mod ops; |
| 85 |
mod parts_write_adapter; |
| 86 |
mod replace; |
| 87 |
#[cfg(feature = "alloc")] |
| 88 |
mod testing; |
| 89 |
#[cfg(feature = "alloc")] |
| 90 |
mod to_string_or_borrow; |
| 91 |
mod try_writeable; |
| 92 |
|
| 93 |
#[cfg(feature = "alloc")] |
| 94 |
use alloc::borrow::Cow; |
| 95 |
|
| 96 |
#[cfg(feature = "alloc")] |
| 97 |
use alloc::string::String; |
| 98 |
use core::fmt; |
| 99 |
|
| 100 |
pub use cmp::{cmp_str, cmp_utf8}; |
| 101 |
pub use concat::concat_writeable; |
| 102 |
#[cfg(feature = "alloc")] |
| 103 |
pub use to_string_or_borrow::to_string_or_borrow; |
| 104 |
pub use try_writeable::TryWriteable; |
| 105 |
|
| 106 |
/// Helper types for trait impls. |
| 107 |
pub mod adapters { |
| 108 |
use super::*; |
| 109 |
|
| 110 |
pub use concat::Concat; |
| 111 |
pub use parts_write_adapter::CoreWriteAsPartsWrite; |
| 112 |
pub use parts_write_adapter::WithPart; |
| 113 |
pub use replace::Replace; |
| 114 |
pub use try_writeable::TryWriteableInfallibleAsWriteable; |
| 115 |
pub use try_writeable::WriteableAsTryWriteableInfallible; |
| 116 |
|
| 117 |
/// A lossy wrapper for a [`TryWriteable`] that implements [`Writeable`] |
| 118 |
/// and ignores any errors. |
| 119 |
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 120 |
#[repr(transparent)] |
| 121 |
#[allow(clippy::exhaustive_structs)] // newtype |
| 122 |
pub struct LossyWrap<T>(pub T); |
| 123 |
|
| 124 |
impl<T: TryWriteable> Writeable for LossyWrap<T> { |
| 125 |
#[inline] |
| 126 |
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { |
| 127 |
let _ = self.0.try_write_to(sink)?; |
| 128 |
Ok(()) |
| 129 |
} |
| 130 |
|
| 131 |
#[inline] |
| 132 |
fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result { |
| 133 |
let _ = self.0.try_write_to_parts(sink)?; |
| 134 |
Ok(()) |
| 135 |
} |
| 136 |
|
| 137 |
#[inline] |
| 138 |
fn writeable_length_hint(&self) -> LengthHint { |
| 139 |
self.0.writeable_length_hint() |
| 140 |
} |
| 141 |
|
| 142 |
#[inline] |
| 143 |
fn writeable_borrow(&self) -> Option<&str> { |
| 144 |
match self.0.try_writeable_borrow()? { |
| 145 |
Ok(s) => Some(s), |
| 146 |
Err((_err, s)) => Some(s), |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
#[inline] |
| 151 |
#[cfg(feature = "alloc")] |
| 152 |
fn write_to_string(&self) -> Cow<'_, str> { |
| 153 |
match self.0.try_write_to_string() { |
| 154 |
Ok(s) => s, |
| 155 |
Err((_err, s)) => s, |
| 156 |
} |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
impl_display_with_writeable!(LossyWrap<T>, #[cfg(feature = "alloc")], where T: TryWriteable); |
| 161 |
} |
| 162 |
|
| 163 |
#[doc(hidden)] // for testing and macros |
| 164 |
pub mod _internal { |
| 165 |
#[cfg(feature = "alloc")] |
| 166 |
pub use super::testing::try_writeable_to_parts_for_test; |
| 167 |
#[cfg(feature = "alloc")] |
| 168 |
pub use super::testing::writeable_to_parts_for_test; |
| 169 |
#[cfg(feature = "alloc")] |
| 170 |
pub use alloc::borrow::Cow; |
| 171 |
#[cfg(feature = "alloc")] |
| 172 |
pub use alloc::string::String; |
| 173 |
} |
| 174 |
|
| 175 |
/// 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(Debug, PartialEq, Eq, Copy, Clone)] |
| 186 |
#[non_exhaustive] |
| 187 |
pub struct LengthHint(pub usize, pub Option<usize>); |
| 188 |
|
| 189 |
impl LengthHint { |
| 190 |
/// Unknown |
| 191 |
pub fn undefined() -> Self { |
| 192 |
Self(0, None) |
| 193 |
} |
| 194 |
|
| 195 |
/// `write_to` will use exactly n bytes. |
| 196 |
pub fn exact(n: usize) -> Self { |
| 197 |
Self(n, Some(n)) |
| 198 |
} |
| 199 |
|
| 200 |
/// `write_to` will use at least n bytes. |
| 201 |
pub fn at_least(n: usize) -> Self { |
| 202 |
Self(n, None) |
| 203 |
} |
| 204 |
|
| 205 |
/// `write_to` will use at most n bytes. |
| 206 |
pub fn at_most(n: usize) -> Self { |
| 207 |
Self(0, Some(n)) |
| 208 |
} |
| 209 |
|
| 210 |
/// `write_to` will use between `n` and `m` bytes. |
| 211 |
pub fn between(n: usize, m: usize) -> Self { |
| 212 |
Self(Ord::min(n, m), Some(Ord::max(n, m))) |
| 213 |
} |
| 214 |
|
| 215 |
/// 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 |
/// ``` |
| 228 |
pub fn capacity(&self) -> usize { |
| 229 |
self.1.unwrap_or(self.0) |
| 230 |
} |
| 231 |
|
| 232 |
/// Returns whether the `LengthHint` indicates that the string is exactly 0 bytes long. |
| 233 |
pub fn is_zero(&self) -> bool { |
| 234 |
self.1 == Some(0) |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
/// [`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(Clone, Copy, Debug, PartialEq)] |
| 263 |
#[allow(clippy::exhaustive_structs)] // stable |
| 264 |
#[allow(missing_docs)] // behavior not defined, explained in type docs |
| 265 |
pub struct Part { |
| 266 |
pub category: &'static str, |
| 267 |
pub value: &'static str, |
| 268 |
} |
| 269 |
|
| 270 |
impl Part { |
| 271 |
/// A part that should annotate error segments in [`TryWriteable`] output. |
| 272 |
/// |
| 273 |
/// For an example, see [`TryWriteable`]. |
| 274 |
pub const ERROR: Part = Part { |
| 275 |
category: "writeable", |
| 276 |
value: "error", |
| 277 |
}; |
| 278 |
} |
| 279 |
|
| 280 |
/// A sink that supports annotating parts of the string with [`Part`]s. |
| 281 |
pub trait PartsWrite: fmt::Write { |
| 282 |
/// The recursive sink |
| 283 |
type SubPartsWrite: PartsWrite + ?Sized; |
| 284 |
|
| 285 |
/// Annotates all strings written by the closure with the given [`Part`]. |
| 286 |
fn with_part( |
| 287 |
&mut self, |
| 288 |
part: Part, |
| 289 |
f: impl FnMut(&mut Self::SubPartsWrite) -> fmt::Result, |
| 290 |
) -> fmt::Result; |
| 291 |
} |
| 292 |
|
| 293 |
/// `Writeable` is an alternative to `std::fmt::Display` with the addition of a length function. |
| 294 |
pub 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. |
| 298 |
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result { |
| 299 |
self.write_to_parts(&mut parts_write_adapter::CoreWriteAsPartsWrite(sink)) |
| 300 |
} |
| 301 |
|
| 302 |
/// 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. |
| 305 |
fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result { |
| 306 |
self.write_to(sink) |
| 307 |
} |
| 308 |
|
| 309 |
/// 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. |
| 312 |
fn writeable_length_hint(&self) -> LengthHint { |
| 313 |
LengthHint::undefined() |
| 314 |
} |
| 315 |
|
| 316 |
/// 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`. |
| 319 |
fn writeable_borrow(&self) -> Option<&str> { |
| 320 |
None |
| 321 |
} |
| 322 |
|
| 323 |
/// 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")] |
| 378 |
fn write_to_string(&self) -> Cow<'_, str> { |
| 379 |
if let Some(borrow) = self.writeable_borrow() { |
| 380 |
return Cow::Borrowed(borrow); |
| 381 |
} |
| 382 |
let hint = self.writeable_length_hint(); |
| 383 |
if hint.is_zero() { |
| 384 |
return Cow::Borrowed(""); |
| 385 |
} |
| 386 |
let mut output = String::with_capacity(hint.capacity()); |
| 387 |
let _ = self.write_to(&mut output); |
| 388 |
Cow::Owned(output) |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
/// 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] |
| 434 |
macro_rules! impl_writeable_delegate { |
| 435 |
($ty:ty, |&$self:ident| $delegate:expr $(, #[$alloc_feature:meta] fn write_to_string)? $(, where $($generics:tt)*)?) => { |
| 436 |
impl $(<$($generics)*>)? $crate::Writeable for $ty { |
| 437 |
#[inline] |
| 438 |
fn write_to<W: core::fmt::Write + ?Sized>(&$self, sink: &mut W) -> core::fmt::Result { |
| 439 |
($delegate).write_to(sink) |
| 440 |
} |
| 441 |
#[inline] |
| 442 |
fn write_to_parts<S: $crate::PartsWrite + ?Sized>(&$self, sink: &mut S) -> core::fmt::Result { |
| 443 |
($delegate).write_to_parts(sink) |
| 444 |
} |
| 445 |
#[inline] |
| 446 |
fn writeable_length_hint(&$self) -> $crate::LengthHint { |
| 447 |
($delegate).writeable_length_hint() |
| 448 |
} |
| 449 |
#[inline] |
| 450 |
fn writeable_borrow(&$self) -> Option<&str> { |
| 451 |
($delegate).writeable_borrow() |
| 452 |
} |
| 453 |
#[inline] |
| 454 |
$(#[$alloc_feature])? |
| 455 |
fn write_to_string(&$self) -> $crate::_internal::Cow<'_, str> { |
| 456 |
($delegate).write_to_string() |
| 457 |
} |
| 458 |
} |
| 459 |
}; |
| 460 |
} |
| 461 |
|
| 462 |
/// 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] |
| 495 |
macro_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. |
| 499 |
impl $(<$($generics)*>)? core::fmt::Display for $type { |
| 500 |
#[inline] |
| 501 |
fn 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])? |
| 509 |
impl $(<$($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. |
| 516 |
pub fn to_string(&self) -> $crate::_internal::String { |
| 517 |
$crate::Writeable::write_to_string(self).into_owned() |
| 518 |
} |
| 519 |
} |
| 520 |
}; |
| 521 |
} |
| 522 |
|
| 523 |
/// 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")] |
| 585 |
macro_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)+) => {{ |
| 593 |
let actual_writeable = &$actual_writeable; |
| 594 |
let (actual_str, actual_parts) = $crate::_internal::writeable_to_parts_for_test(actual_writeable); |
| 595 |
let actual_len = actual_str.len(); |
| 596 |
assert_eq!(actual_str, $expected_str, $($arg)*); |
| 597 |
let cow = $crate::Writeable::write_to_string(actual_writeable); |
| 598 |
assert_eq!(actual_str, cow, $($arg)+); |
| 599 |
if let Some(borrowed) = ($crate::Writeable::writeable_borrow(&actual_writeable)) { |
| 600 |
assert_eq!(borrowed, $expected_str, $($arg)*); |
| 601 |
assert!(matches!(cow, std::borrow::Cow::Borrowed(_)), $($arg)*); |
| 602 |
} |
| 603 |
let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable); |
| 604 |
let lower = length_hint.0; |
| 605 |
assert!( |
| 606 |
lower <= actual_len, |
| 607 |
"hint lower bound {lower} larger than actual length {actual_len}: {}", |
| 608 |
format!($($arg)*), |
| 609 |
); |
| 610 |
if let Some(upper) = length_hint.1 { |
| 611 |
assert!( |
| 612 |
actual_len <= upper, |
| 613 |
"hint upper bound {upper} smaller than actual length {actual_len}: {}", |
| 614 |
format!($($arg)*), |
| 615 |
); |
| 616 |
} |
| 617 |
assert_eq!(actual_writeable.to_string(), $expected_str, $($arg)*); |
| 618 |
actual_parts // return for assert_writeable_parts_eq |
| 619 |
}}; |
| 620 |
} |
| 621 |
|
| 622 |
/// See [`assert_writeable_eq`]. |
| 623 |
#[macro_export] |
| 624 |
#[cfg(feature = "alloc")] |
| 625 |
macro_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)+) => {{ |
| 630 |
let actual_parts = $crate::assert_writeable_eq!(@internal, $actual_writeable, $expected_str, $($arg)*); |
| 631 |
assert_eq!(actual_parts, $expected_parts, $($arg)+); |
| 632 |
}}; |
| 633 |
} |