ref_map/str.rs
1/*
2 * str.rs
3 *
4 * ref-map - Convenience methods for references of Option and Result.
5 * Copyright (c) 2020-2026 Emmie Maeda
6 *
7 * ref-map is available free of charge under the terms of the MIT
8 * License. You are free to redistribute and/or modify it under those
9 * terms. It is distributed in the hopes that it will be useful, but
10 * WITHOUT ANY WARRANTY. See the LICENSE file for more details.
11 *
12 */
13
14use std::borrow::Cow;
15
16/// Adds the `as_str()` extension method onto owned string [`Option`] values.
17///
18/// ```
19/// use ref_map::*;
20///
21/// let maybe_string = Some(String::from("foo_bar"));
22/// let maybe_str: Option<&str> = maybe_string.as_str();
23/// ```
24pub trait OptionStringRef<'o> {
25 /// Borrows the internal (probably owned) string as an `Option`.
26 fn as_str(&'o self) -> Option<&'o str>;
27}
28
29impl<'o> OptionStringRef<'o> for Option<String> {
30 fn as_str(&'o self) -> Option<&'o str> {
31 self.as_ref().map(|s| s.as_ref())
32 }
33}
34
35impl<'o> OptionStringRef<'o> for Option<Cow<'o, str>> {
36 fn as_str(&'o self) -> Option<&'o str> {
37 self.as_ref().map(|s| s.as_ref())
38 }
39}
40
41// Pass-through case
42impl<'o> OptionStringRef<'o> for Option<&'o str> {
43 #[inline]
44 fn as_str(&'o self) -> Option<&'o str> {
45 *self
46 }
47}