ref-map 0.2.0

Helper trait for Option and Result to map references
Documentation
/*
 * str.rs
 *
 * ref-map - Convenience methods for references of Option and Result.
 * Copyright (c) 2020-2026 Emmie Maeda
 *
 * ref-map is available free of charge under the terms of the MIT
 * License. You are free to redistribute and/or modify it under those
 * terms. It is distributed in the hopes that it will be useful, but
 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
 *
 */

use std::borrow::Cow;

/// Adds the `as_str()` extension method onto owned string [`Option`] values.
///
/// ```
/// use ref_map::*;
///
/// let maybe_string = Some(String::from("foo_bar"));
/// let maybe_str: Option<&str> = maybe_string.as_str();
/// ```
pub trait OptionStringRef<'o> {
    /// Borrows the internal (probably owned) string as an `Option`.
    fn as_str(&'o self) -> Option<&'o str>;
}

impl<'o> OptionStringRef<'o> for Option<String> {
    fn as_str(&'o self) -> Option<&'o str> {
        self.as_ref().map(|s| s.as_ref())
    }
}

impl<'o> OptionStringRef<'o> for Option<Cow<'o, str>> {
    fn as_str(&'o self) -> Option<&'o str> {
        self.as_ref().map(|s| s.as_ref())
    }
}

// Pass-through case
impl<'o> OptionStringRef<'o> for Option<&'o str> {
    #[inline]
    fn as_str(&'o self) -> Option<&'o str> {
        *self
    }
}