writeable/try_writeable.rs
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
5use super::*;
6use crate::parts_write_adapter::CoreWriteAsPartsWrite;
7use core::convert::Infallible;
8
9/// A writeable object that can fail while writing.
10///
11/// The default [`Writeable`] trait returns a [`fmt::Error`], which originates from the sink.
12/// In contrast, this trait allows the _writeable itself_ to trigger an error as well.
13///
14/// Implementations are expected to always make a _best attempt_ at writing to the sink
15/// and should write replacement values in the error state. Therefore, the returned `Result`
16/// can be safely ignored to emulate a "lossy" mode.
17///
18/// Any error substrings should be annotated with [`Part::ERROR`].
19///
20/// # Implementer Notes
21///
22/// This trait requires that implementers make a _best attempt_ at writing to the sink,
23/// _even in the error state_, such as with a placeholder or fallback string.
24///
25/// In [`TryWriteable::try_write_to_parts()`], error substrings should be annotated with
26/// [`Part::ERROR`]. Because of this, writing to parts is not default-implemented like
27/// it is on [`Writeable`].
28///
29/// The trait is implemented on [`Result<T, E>`] where `T` and `E` both implement [`Writeable`];
30/// In the `Ok` case, `T` is written, and in the `Err` case, `E` is written as a fallback value.
31/// This impl, which writes [`Part::ERROR`], can be used as a basis for more advanced impls.
32///
33/// # Examples
34///
35/// Implementing on a custom type:
36///
37/// ```
38/// use core::fmt;
39/// use writeable::LengthHint;
40/// use writeable::PartsWrite;
41/// use writeable::TryWriteable;
42///
43/// #[derive(Debug, PartialEq, Eq)]
44/// enum HelloWorldWriteableError {
45/// MissingName,
46/// }
47///
48/// #[derive(Debug, PartialEq, Eq)]
49/// struct HelloWorldWriteable {
50/// pub name: Option<&'static str>,
51/// }
52///
53/// impl TryWriteable for HelloWorldWriteable {
54/// type Error = HelloWorldWriteableError;
55///
56/// fn try_write_to_parts<S: PartsWrite + ?Sized>(
57/// &self,
58/// sink: &mut S,
59/// ) -> Result<Result<(), Self::Error>, fmt::Error> {
60/// sink.write_str("Hello, ")?;
61/// // Use `impl TryWriteable for Result` to generate the error part:
62/// let err = self.name.ok_or("nobody").try_write_to_parts(sink)?.err();
63/// sink.write_char('!')?;
64/// // Return a doubly-wrapped Result.
65/// // The outer Result is for fmt::Error, handled by the `?`s above.
66/// // The inner Result is for our own Self::Error.
67/// if err.is_none() {
68/// Ok(Ok(()))
69/// } else {
70/// Ok(Err(HelloWorldWriteableError::MissingName))
71/// }
72/// }
73///
74/// fn writeable_length_hint(&self) -> LengthHint {
75/// self.name.ok_or("nobody").writeable_length_hint() + 8
76/// }
77/// }
78///
79/// // Success case:
80/// writeable::assert_try_writeable_eq!(
81/// HelloWorldWriteable {
82/// name: Some("Alice")
83/// },
84/// "Hello, Alice!"
85/// );
86///
87/// // Failure case, including the ERROR part:
88/// writeable::assert_try_writeable_parts_eq!(
89/// HelloWorldWriteable { name: None },
90/// "Hello, nobody!",
91/// Err(HelloWorldWriteableError::MissingName),
92/// [(7, 13, writeable::Part::ERROR)]
93/// );
94/// ```
95pub trait TryWriteable {
96 /// The error type
97 type Error;
98
99 /// Writes the content of this writeable to a sink.
100 ///
101 /// If the sink hits an error, writing immediately ends,
102 /// `Err(`[`fmt::Error`]`)` is returned, and the sink does not contain valid output.
103 ///
104 /// If the writeable hits an error, writing is continued with a replacement value,
105 /// `Ok(Err(`[`TryWriteable::Error`]`))` is returned, and the caller may continue using the sink.
106 ///
107 /// # Lossy Mode
108 ///
109 /// The [`fmt::Error`] should always be handled, but the [`TryWriteable::Error`] can be
110 /// ignored if a fallback string is desired instead of an error.
111 ///
112 /// To handle the sink error, but not the writeable error, write:
113 ///
114 /// ```
115 /// # use writeable::TryWriteable;
116 /// # let my_writeable: Result<&str, &str> = Ok("");
117 /// # let mut sink = String::new();
118 /// let _ = my_writeable.try_write_to(&mut sink)?;
119 /// # Ok::<(), core::fmt::Error>(())
120 /// ```
121 ///
122 /// # Examples
123 ///
124 /// The following examples use `Result<&str, usize>`, which implements [`TryWriteable`] because both `&str` and `usize` do.
125 ///
126 /// Success case:
127 ///
128 /// ```
129 /// use writeable::TryWriteable;
130 ///
131 /// let w: Result<&str, usize> = Ok("success");
132 /// let mut sink = String::new();
133 /// let result = w.try_write_to(&mut sink);
134 ///
135 /// assert_eq!(result, Ok(Ok(())));
136 /// assert_eq!(sink, "success");
137 /// ```
138 ///
139 /// Failure case:
140 ///
141 /// ```
142 /// use writeable::TryWriteable;
143 ///
144 /// let w: Result<&str, usize> = Err(44);
145 /// let mut sink = String::new();
146 /// let result = w.try_write_to(&mut sink);
147 ///
148 /// assert_eq!(result, Ok(Err(44)));
149 /// assert_eq!(sink, "44");
150 /// ```
151 fn try_write_to<W: fmt::Write + ?Sized>(
152 &self,
153 sink: &mut W,
154 ) -> Result<Result<(), Self::Error>, fmt::Error> {
155 self.try_write_to_parts(&mut CoreWriteAsPartsWrite(sink))
156 }
157
158 /// Writes the content of this writeable to a sink with parts (annotations).
159 ///
160 /// For more information, see:
161 ///
162 /// - [`TryWriteable::try_write_to()`] for the general behavior.
163 /// - [`TryWriteable`] for an example with parts.
164 /// - [`Part`] for more about parts.
165 fn try_write_to_parts<S: PartsWrite + ?Sized>(
166 &self,
167 sink: &mut S,
168 ) -> Result<Result<(), Self::Error>, fmt::Error>;
169
170 /// Returns a hint for the number of UTF-8 bytes that will be written to the sink.
171 ///
172 /// This function returns the length of the "lossy mode" string; for more information,
173 /// see [`TryWriteable::try_write_to()`].
174 fn writeable_length_hint(&self) -> LengthHint {
175 LengthHint::undefined()
176 }
177
178 /// Returns a `&str` that matches the output of `try_write_to`, if possible.
179 ///
180 /// This method is used to avoid materializing a [`String`] in `write_to_string`.
181 fn try_writeable_borrow(&self) -> Option<Result<&str, (Self::Error, &str)>> {
182 None
183 }
184
185 /// Writes the content of this writeable to a string.
186 ///
187 /// In the failure case, this function returns the error and the best-effort string ("lossy mode").
188 ///
189 /// # Note to implementors
190 ///
191 /// See the note in [`Writeable::write_to_string`].
192 ///
193 /// # Examples
194 ///
195 /// ```
196 /// # use std::borrow::Cow;
197 /// # use writeable::TryWriteable;
198 /// // use the best-effort string
199 /// let r1: Cow<str> = Ok::<&str, u8>("ok")
200 /// .try_write_to_string()
201 /// .unwrap_or_else(|(_, s)| s);
202 /// // propagate the error
203 /// let r2: Result<Cow<str>, u8> = Ok::<&str, u8>("ok")
204 /// .try_write_to_string()
205 /// .map_err(|(e, _)| e);
206 /// ```
207 #[cfg(feature = "alloc")]
208 fn try_write_to_string(&self) -> Result<Cow<'_, str>, (Self::Error, Cow<'_, str>)> {
209 if let Some(borrow) = self.try_writeable_borrow() {
210 return borrow
211 .map(Cow::Borrowed)
212 .map_err(|(e, s)| (e, Cow::Borrowed(s)));
213 }
214 let hint = self.writeable_length_hint();
215 if hint.is_zero() {
216 return Ok(Cow::Borrowed(""));
217 }
218 let mut output = String::with_capacity(hint.capacity());
219 match self
220 .try_write_to(&mut output)
221 .unwrap_or_else(|fmt::Error| Ok(()))
222 {
223 Ok(()) => Ok(Cow::Owned(output)),
224 Err(e) => Err((e, Cow::Owned(output))),
225 }
226 }
227}
228
229impl<T, E> TryWriteable for Result<T, E>
230where
231 T: Writeable,
232 E: Writeable + Clone,
233{
234 type Error = E;
235
236 #[inline]
237 fn try_write_to<W: fmt::Write + ?Sized>(
238 &self,
239 sink: &mut W,
240 ) -> Result<Result<(), Self::Error>, fmt::Error> {
241 match self {
242 Ok(t) => t.write_to(sink).map(Ok),
243 Err(e) => e.write_to(sink).map(|()| Err(e.clone())),
244 }
245 }
246
247 #[inline]
248 fn try_write_to_parts<S: PartsWrite + ?Sized>(
249 &self,
250 sink: &mut S,
251 ) -> Result<Result<(), Self::Error>, fmt::Error> {
252 match self {
253 Ok(t) => t.write_to_parts(sink).map(Ok),
254 Err(e) => sink
255 .with_part(Part::ERROR, |sink| e.write_to_parts(sink))
256 .map(|()| Err(e.clone())),
257 }
258 }
259
260 #[inline]
261 fn writeable_length_hint(&self) -> LengthHint {
262 match self {
263 Ok(t) => t.writeable_length_hint(),
264 Err(e) => e.writeable_length_hint(),
265 }
266 }
267
268 fn try_writeable_borrow(&self) -> Option<Result<&str, (Self::Error, &str)>> {
269 match self {
270 Ok(t) => t.writeable_borrow().map(Ok),
271 Err(e) => e.writeable_borrow().map(|s| Err((e.clone(), s))),
272 }
273 }
274
275 #[inline]
276 #[cfg(feature = "alloc")]
277 fn try_write_to_string(&self) -> Result<Cow<'_, str>, (Self::Error, Cow<'_, str>)> {
278 match self {
279 Ok(t) => Ok(t.write_to_string()),
280 Err(e) => Err((e.clone(), e.write_to_string())),
281 }
282 }
283}
284
285/// A wrapper around [`TryWriteable`] that implements [`Writeable`]
286/// if [`TryWriteable::Error`] is [`Infallible`].
287#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
288#[repr(transparent)]
289#[allow(clippy::exhaustive_structs)] // transparent newtype
290pub struct TryWriteableInfallibleAsWriteable<T>(pub T);
291
292impl<T> Writeable for TryWriteableInfallibleAsWriteable<T>
293where
294 T: TryWriteable<Error = Infallible>,
295{
296 #[inline]
297 fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
298 match self.0.try_write_to(sink) {
299 Ok(Ok(())) => Ok(()),
300 Ok(Err(infallible)) => match infallible {},
301 Err(e) => Err(e),
302 }
303 }
304
305 #[inline]
306 fn write_to_parts<S: PartsWrite + ?Sized>(&self, sink: &mut S) -> fmt::Result {
307 match self.0.try_write_to_parts(sink) {
308 Ok(Ok(())) => Ok(()),
309 Ok(Err(infallible)) => match infallible {},
310 Err(e) => Err(e),
311 }
312 }
313
314 #[inline]
315 fn writeable_length_hint(&self) -> LengthHint {
316 self.0.writeable_length_hint()
317 }
318
319 #[inline]
320 fn writeable_borrow(&self) -> Option<&str> {
321 let Ok(s) = self.0.try_writeable_borrow()?;
322 Some(s)
323 }
324
325 #[inline]
326 #[cfg(feature = "alloc")]
327 fn write_to_string(&self) -> Cow<'_, str> {
328 match self.0.try_write_to_string() {
329 Ok(s) => s,
330 Err((infallible, _)) => match infallible {},
331 }
332 }
333}
334
335impl<T> fmt::Display for TryWriteableInfallibleAsWriteable<T>
336where
337 T: TryWriteable<Error = Infallible>,
338{
339 #[inline]
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 self.write_to(f)
342 }
343}
344
345/// A wrapper around [`Writeable`] that implements [`TryWriteable`]
346/// with [`TryWriteable::Error`] set to [`Infallible`].
347#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
348#[repr(transparent)]
349#[allow(clippy::exhaustive_structs)] // transparent newtype
350pub struct WriteableAsTryWriteableInfallible<T>(pub T);
351
352impl<T> TryWriteable for WriteableAsTryWriteableInfallible<T>
353where
354 T: Writeable,
355{
356 type Error = Infallible;
357
358 #[inline]
359 fn try_write_to<W: fmt::Write + ?Sized>(
360 &self,
361 sink: &mut W,
362 ) -> Result<Result<(), Infallible>, fmt::Error> {
363 self.0.write_to(sink).map(Ok)
364 }
365
366 #[inline]
367 fn try_write_to_parts<S: PartsWrite + ?Sized>(
368 &self,
369 sink: &mut S,
370 ) -> Result<Result<(), Infallible>, fmt::Error> {
371 self.0.write_to_parts(sink).map(Ok)
372 }
373
374 #[inline]
375 fn writeable_length_hint(&self) -> LengthHint {
376 self.0.writeable_length_hint()
377 }
378
379 #[inline]
380 fn try_writeable_borrow(&self) -> Option<Result<&str, (Self::Error, &str)>> {
381 self.0.writeable_borrow().map(Ok)
382 }
383
384 #[inline]
385 #[cfg(feature = "alloc")]
386 fn try_write_to_string(&self) -> Result<Cow<'_, str>, (Infallible, Cow<'_, str>)> {
387 Ok(self.0.write_to_string())
388 }
389}
390
391/// Macro to implement [`TryWriteable`] by delegating to another `TryWriteable`.
392///
393/// Useful for wrapper types.
394///
395/// # Examples
396///
397/// ```
398/// struct MyStruct(Result<String, String>);
399/// writeable::impl_try_writeable_delegate!(
400/// MyStruct,
401/// |&self| &self.0,
402/// Error = String
403/// );
404///
405/// writeable::assert_try_writeable_eq!(
406/// MyStruct(Ok("hello".to_string())),
407/// "hello"
408/// );
409/// ```
410///
411/// With an error mapping fn:
412///
413/// ```
414/// struct MyStruct(Result<String, String>);
415/// #[derive(Debug, PartialEq)]
416/// struct MyError;
417/// writeable::impl_try_writeable_delegate!(
418/// MyStruct,
419/// |&self| &self.0,
420/// Error = MyError,
421/// |_error| MyError
422/// );
423///
424/// writeable::assert_try_writeable_eq!(
425/// MyStruct(Ok("hello".to_string())),
426/// "hello"
427/// );
428/// writeable::assert_try_writeable_eq!(
429/// MyStruct(Err("hello".to_string())),
430/// "hello",
431/// Err(MyError)
432/// );
433/// ```
434///
435/// With a cfg on fn `write_to_string`:
436///
437/// ```
438/// struct MyStruct(Result<String, String>);
439/// writeable::impl_try_writeable_delegate!(MyStruct, |&self| &self.0, Error = String, #[cfg(feature = "alloc")] fn try_write_to_string);
440///
441/// writeable::assert_try_writeable_eq!(
442/// MyStruct(Ok("hello".to_string())),
443/// "hello"
444/// );
445/// ```
446///
447/// With generics:
448///
449/// ```
450/// use writeable::Writeable;
451///
452/// struct MyStruct<T>(Result<T, T>);
453/// writeable::impl_try_writeable_delegate!(MyStruct<T>, |&self| &self.0, Error = T, where T: Writeable + Clone);
454///
455/// writeable::assert_try_writeable_eq!(
456/// MyStruct(Ok("hello".to_string())),
457/// "hello"
458/// );
459/// ```
460///
461/// Implement both `Writeable` and `TryWriteable`:
462///
463/// ```
464/// use writeable::adapters::LossyWrap;
465///
466/// // The LossyWrap needs to be a field of MyStruct since it can be borrowed from.
467/// struct MyStruct(LossyWrap<Result<String, String>>);
468/// writeable::impl_try_writeable_delegate!(MyStruct, |&self| &self.0.0, Error = String);
469/// writeable::impl_writeable_delegate!(MyStruct, |&self| &self.0);
470/// writeable::impl_display_with_writeable!(MyStruct);
471///
472/// writeable::assert_try_writeable_eq!(
473/// MyStruct(LossyWrap(Ok("hello".to_string()))),
474/// "hello"
475/// );
476///
477/// writeable::assert_writeable_eq!(
478/// MyStruct(LossyWrap(Ok("hello".to_string()))),
479/// "hello"
480/// );
481/// ```
482#[macro_export]
483macro_rules! impl_try_writeable_delegate {
484 ($ty:ty, |&$self:ident| $delegate:expr, Error = $error:ty $(, |$error_arg:ident| $error_map:expr)? $(, #[$alloc_feature:meta] fn try_write_to_string)? $(, where $($generics:tt)*)?) => {
485 impl$(<$($generics)*>)? $crate::TryWriteable for $ty {
486 type Error = $error;
487 #[inline]
488 fn try_write_to<W: core::fmt::Write + ?Sized>(
489 &$self,
490 sink: &mut W,
491 ) -> core::result::Result<core::result::Result<(), Self::Error>, core::fmt::Error> {
492 let result = ($delegate).try_write_to(sink)?;
493 $(
494 let result = result.map_err(|$error_arg| { $error_map });
495 )?
496 Ok(result)
497 }
498 #[inline]
499 fn try_write_to_parts<S: $crate::PartsWrite + ?Sized>(
500 &$self,
501 sink: &mut S,
502 ) -> core::result::Result<core::result::Result<(), Self::Error>, core::fmt::Error> {
503 let result = ($delegate).try_write_to_parts(sink)?;
504 $(
505 let result = result.map_err(|$error_arg| { $error_map });
506 )?
507 Ok(result)
508 }
509 #[inline]
510 fn writeable_length_hint(&$self) -> $crate::LengthHint {
511 ($delegate).writeable_length_hint()
512 }
513 #[inline]
514 fn try_writeable_borrow(&$self) -> Option<Result<&str, (Self::Error, &str)>> {
515 let result = ($delegate).try_writeable_borrow()?;
516 $(
517 let error_map = |$error_arg| { $error_map };
518 let result = result.map_err(|(err, cow)| (error_map(err), cow));
519 )?
520 Some(result)
521 }
522 #[inline]
523 $(#[$alloc_feature])?
524 fn try_write_to_string(
525 &$self,
526 ) -> core::result::Result<
527 $crate::_internal::Cow<'_, str>,
528 (Self::Error, $crate::_internal::Cow<'_, str>),
529 > {
530 let result = ($delegate).try_write_to_string();
531 $(
532 let error_map = |$error_arg| { $error_map };
533 let result = result.map_err(|(err, cow)| (error_map(err), cow));
534 )?
535 result
536 }
537 }
538 };
539}
540
541impl_try_writeable_delegate!(
542 &T,
543 |&self| *self,
544 Error = T::Error,
545 #[cfg(feature = "alloc")] fn try_write_to_string,
546 where T: TryWriteable + ?Sized
547);
548
549/// Testing macros for types implementing [`TryWriteable`].
550///
551/// Arguments, in order:
552///
553/// 1. The [`TryWriteable`] under test
554/// 2. The expected string value
555/// 3. The expected result value, or `Ok(())` if omitted
556/// 3. [`*_parts_eq`] only: a list of parts (`[(start, end, Part)]`)
557///
558/// Any remaining arguments get passed to `format!`
559///
560/// The macros tests the following:
561///
562/// - Equality of string content
563/// - Equality of parts ([`*_parts_eq`] only)
564/// - Validity of size hint
565///
566/// For a usage example, see [`TryWriteable`].
567///
568/// [`*_parts_eq`]: assert_try_writeable_parts_eq
569#[macro_export]
570macro_rules! assert_try_writeable_eq {
571 ($actual_writeable:expr, $expected_str:expr $(,)?) => {
572 $crate::assert_try_writeable_eq!($actual_writeable, $expected_str, Ok(()))
573 };
574 ($actual_writeable:expr, $expected_str:expr, $expected_result:expr $(,)?) => {
575 $crate::assert_try_writeable_eq!($actual_writeable, $expected_str, $expected_result, "")
576 };
577 ($actual_writeable:expr, $expected_str:expr, $expected_result:expr, $($arg:tt)+) => {{
578 $crate::assert_try_writeable_eq!(@internal, $actual_writeable, $expected_str, $expected_result, $($arg)*);
579 }};
580 (@internal, $actual_writeable:expr, $expected_str:expr, $expected_result:expr, $($arg:tt)+) => {{
581 let actual_writeable = &$actual_writeable;
582 let (actual_str, actual_parts, actual_error) = $crate::_internal::try_writeable_to_parts_for_test(actual_writeable);
583 assert_eq!(actual_str, $expected_str, $($arg)*);
584 assert_eq!(actual_error, Result::<(), _>::from($expected_result).err(), $($arg)*);
585 let actual_result = match $crate::TryWriteable::try_write_to_string(&actual_writeable) {
586 Ok(actual_cow_str) => {
587 assert_eq!(actual_cow_str, $expected_str, $($arg)+);
588 Ok(())
589 }
590 Err((e, actual_cow_str)) => {
591 assert_eq!(actual_cow_str, $expected_str, $($arg)+);
592 Err(e)
593 }
594 };
595 assert_eq!(actual_result, Result::<(), _>::from($expected_result), $($arg)*);
596 let length_hint = $crate::TryWriteable::writeable_length_hint(&actual_writeable);
597 assert!(
598 length_hint.0 <= actual_str.len(),
599 "hint lower bound {} larger than actual length {}: {}",
600 length_hint.0, actual_str.len(), format!($($arg)*),
601 );
602 if let Some(upper) = length_hint.1 {
603 assert!(
604 actual_str.len() <= upper,
605 "hint upper bound {} smaller than actual length {}: {}",
606 length_hint.0, actual_str.len(), format!($($arg)*),
607 );
608 }
609 actual_parts // return for assert_try_writeable_parts_eq
610 }};
611}
612
613/// See [`assert_try_writeable_eq`].
614#[macro_export]
615macro_rules! assert_try_writeable_parts_eq {
616 ($actual_writeable:expr, $expected_str:expr, $expected_parts:expr $(,)?) => {
617 $crate::assert_try_writeable_parts_eq!($actual_writeable, $expected_str, Ok(()), $expected_parts)
618 };
619 ($actual_writeable:expr, $expected_str:expr, $expected_result:expr, $expected_parts:expr $(,)?) => {
620 $crate::assert_try_writeable_parts_eq!($actual_writeable, $expected_str, $expected_result, $expected_parts, "")
621 };
622 ($actual_writeable:expr, $expected_str:expr, $expected_result:expr, $expected_parts:expr, $($arg:tt)+) => {{
623 let actual_parts = $crate::assert_try_writeable_eq!(@internal, $actual_writeable, $expected_str, $expected_result, $($arg)*);
624 assert_eq!(actual_parts, $expected_parts, $($arg)+);
625 }};
626}
627
628#[test]
629fn test_result_try_writeable() {
630 let mut result: Result<&str, usize> = Ok("success");
631 assert_try_writeable_eq!(result, "success");
632 result = Err(44);
633 assert_try_writeable_eq!(result, "44", Err(44));
634 assert_try_writeable_parts_eq!(result, "44", Err(44), [(0, 2, Part::ERROR)])
635}
636
637#[cfg(test)]
638struct DelegatedTryMessage<'s>(Result<&'s str, usize>);
639
640#[cfg(test)]
641impl_try_writeable_delegate!(DelegatedTryMessage<'_>, |&self| &self.0, Error = usize);
642
643#[test]
644fn test_delegated_try_writeable() {
645 let mut message = DelegatedTryMessage(Ok("success"));
646 assert_try_writeable_eq!(message, "success");
647 message = DelegatedTryMessage(Err(44));
648 assert_try_writeable_eq!(message, "44", Err(44));
649}