into_static/
lib.rs

1//! Upgrading to static lifetimes.
2//!
3//! This crate provides the [`IntoStatic`] trait, which allows upgrading all lifetimes to `'static`.
4//!
5//! [`IntoStatic`] is implemented for [`Option<T>`] and [`Result<T, E>`], provided
6//! `T` and `E` are also [`IntoStatic`].
7//!
8//! When the `std` or `alloc` feature is enabled, [`IntoStatic`] is also
9//! implemented for `Cow<'_, T>`, yielding `Cow<'static, T>` (provided `T: 'static` is satisfied).
10
11#![forbid(unsafe_code)]
12#![deny(missing_docs)]
13#![cfg_attr(not(feature = "std"), no_std)]
14#![cfg_attr(docsrs, feature(doc_auto_cfg))]
15
16#[cfg(feature = "std")]
17use std::borrow::{Cow, ToOwned};
18
19#[cfg(feature = "alloc")]
20extern crate alloc;
21
22#[cfg(all(not(feature = "std"), feature = "alloc"))]
23use alloc::borrow::{Cow, ToOwned};
24
25/// Upgrading to `'static` lifetimes.
26pub trait IntoStatic {
27    /// The type with `'static` lifetimes.
28    type Static: 'static;
29
30    /// Upgrades [`Self`] to [`Self::Static`].
31    fn into_static(self) -> Self::Static;
32}
33
34#[cfg(any(feature = "std", feature = "alloc"))]
35impl<T: ToOwned + ?Sized + 'static> IntoStatic for Cow<'_, T> {
36    type Static = Cow<'static, T>;
37
38    fn into_static(self) -> Self::Static {
39        Self::Static::Owned(self.into_owned())
40    }
41}
42
43impl<T: IntoStatic> IntoStatic for Option<T> {
44    type Static = Option<T::Static>;
45
46    fn into_static(self) -> Self::Static {
47        self.map(IntoStatic::into_static)
48    }
49}
50
51impl<T: IntoStatic, E: IntoStatic> IntoStatic for Result<T, E> {
52    type Static = Result<T::Static, E::Static>;
53
54    fn into_static(self) -> Self::Static {
55        self.map(IntoStatic::into_static)
56            .map_err(IntoStatic::into_static)
57    }
58}