fray 0.1.2

A type-safe and ergonomic Rust library for working with bitfields.
Documentation
//! Utilities for customizing debug output.
//!
//! This module currently provides [`PrettyResult`], a wrapper around [`Result`]
//! that formats the inner value directly instead of displaying `Ok(..)` or `Err(..)`.

use core::fmt;

/// A wrapper around [`Result`] that customizes its [`Debug`] output.
///
/// Instead of formatting as `Ok(T)` or `Err(E)`, this type only displays:
/// - the inner `T` when the result is `Ok(T)`,
/// - the full `Err(E)` when the result is an error.
///
/// This type can be created via [`From<&Result<T, E>>`](From).
///
/// Both `T` and `E` must implement [`Debug`].
///
/// # Example
///
/// ```
/// use fray::debug::PrettyResult;
///
/// let ok: Result<u32, &str> = Ok(42);
/// let err: Result<u32, &str> = Err("fail");
///
/// assert_eq!(format!("{:?}", PrettyResult::from(&ok)), "42");
/// assert_eq!(format!("{:?}", PrettyResult::from(&err)), "Err(\"fail\")");
/// ```
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct PrettyResult<'a, T, E>(&'a Result<T, E>);

impl<'a, T, E> From<&'a Result<T, E>> for PrettyResult<'a, T, E> {
    fn from(value: &'a Result<T, E>) -> Self {
        Self(value)
    }
}

impl<'a, T, E> fmt::Debug for PrettyResult<'a, T, E>
where
    T: fmt::Debug,
    E: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Ok(v) => v.fmt(f),
            err => err.fmt(f),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::format;

    #[test]
    fn pretty_result_format_ok() {
        let val: Result<i32, ()> = Ok(42);
        let pretty = PrettyResult(&val);
        assert_eq!(format!("{:?}", pretty), "42");
    }

    #[test]
    fn pretty_result_format_err() {
        let val: Result<i32, &str> = Err("oops");
        let pretty = PrettyResult(&val);
        assert_eq!(format!("{:?}", pretty), "Err(\"oops\")");
    }
}