1use super::*;
6use crate::parts_write_adapter::CoreWriteAsPartsWrite;
7use core::convert::Infallible;
8
9pub trait TryWriteable {
96 type Error;
98
99 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 fn try_write_to_parts<S: PartsWrite + ?Sized>(
166 &self,
167 sink: &mut S,
168 ) -> Result<Result<(), Self::Error>, fmt::Error>;
169
170 fn writeable_length_hint(&self) -> LengthHint {
175 LengthHint::undefined()
176 }
177
178 fn try_writeable_borrow(&self) -> Option<Result<&str, (Self::Error, &str)>> {
182 None
183 }
184
185 #[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#[derive(#[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
TryWriteableInfallibleAsWriteable<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TryWriteableInfallibleAsWriteable", &&self.0)
}
}Debug, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::clone::Clone> ::core::clone::Clone for
TryWriteableInfallibleAsWriteable<T> {
#[inline]
fn clone(&self) -> TryWriteableInfallibleAsWriteable<T> {
TryWriteableInfallibleAsWriteable(::core::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
TryWriteableInfallibleAsWriteable<T> {
#[inline]
fn eq(&self, other: &TryWriteableInfallibleAsWriteable<T>) -> bool {
self.0 == other.0
}
}PartialEq, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for
TryWriteableInfallibleAsWriteable<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
TryWriteableInfallibleAsWriteable<T> {
#[inline]
fn partial_cmp(&self, other: &TryWriteableInfallibleAsWriteable<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
TryWriteableInfallibleAsWriteable<T> {
#[inline]
fn cmp(&self, other: &TryWriteableInfallibleAsWriteable<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
TryWriteableInfallibleAsWriteable<T> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
288#[repr(transparent)]
289#[allow(clippy::exhaustive_structs)] pub 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#[derive(#[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
WriteableAsTryWriteableInfallible<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"WriteableAsTryWriteableInfallible", &&self.0)
}
}Debug, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::clone::Clone> ::core::clone::Clone for
WriteableAsTryWriteableInfallible<T> {
#[inline]
fn clone(&self) -> WriteableAsTryWriteableInfallible<T> {
WriteableAsTryWriteableInfallible(::core::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for
WriteableAsTryWriteableInfallible<T> {
#[inline]
fn eq(&self, other: &WriteableAsTryWriteableInfallible<T>) -> bool {
self.0 == other.0
}
}PartialEq, #[automatically_derived]
#[allow(clippy::exhaustive_structs)]
impl<T: ::core::cmp::Eq> ::core::cmp::Eq for
WriteableAsTryWriteableInfallible<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
WriteableAsTryWriteableInfallible<T> {
#[inline]
fn partial_cmp(&self, other: &WriteableAsTryWriteableInfallible<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
WriteableAsTryWriteableInfallible<T> {
#[inline]
fn cmp(&self, other: &WriteableAsTryWriteableInfallible<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
WriteableAsTryWriteableInfallible<T> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash)]
348#[repr(transparent)]
349#[allow(clippy::exhaustive_structs)] pub 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_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<T: TryWriteable + ?Sized> crate::TryWriteable for &T {
type Error = T::Error;
#[inline]
fn try_write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W)
->
core::result::Result<core::result::Result<(), Self::Error>,
core::fmt::Error> {
let result = (*self).try_write_to(sink)?;
Ok(result)
}
#[inline]
fn try_write_to_parts<S: crate::PartsWrite + ?Sized>(&self, sink: &mut S)
->
core::result::Result<core::result::Result<(), Self::Error>,
core::fmt::Error> {
let result = (*self).try_write_to_parts(sink)?;
Ok(result)
}
#[inline]
fn writeable_length_hint(&self) -> crate::LengthHint {
(*self).writeable_length_hint()
}
#[inline]
fn try_writeable_borrow(&self)
-> Option<Result<&str, (Self::Error, &str)>> {
let result = (*self).try_writeable_borrow()?;
Some(result)
}
}impl_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#[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 }};
611}
612
613#[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}