leaky_cow/
lib.rs

1// This library is released under the same terms as Rust itself.
2
3//! Leaky cows: convert a clone-on-write reference into a plain reference. If it's just the
4//! plain reference, just return that. If it's the owned structure, leak it and return a
5//! reference to it.
6
7extern crate leak;
8use leak::Leak;
9use std::borrow::{Borrow, Cow, ToOwned};
10
11pub trait LeakyCow<'a, B: ?Sized> {
12    fn leak(self) -> &'a B;
13}
14
15impl<'a, B: ?Sized> LeakyCow<'a, B> for Cow<'a, B> where B: 'a + ToOwned, B::Owned: Leak<B> {
16    fn leak(self) -> &'a B {
17        match self {
18            Cow::Owned(x) => x.leak(),
19            Cow::Borrowed(x) => x,
20        }
21    }
22}
23
24#[cfg(test)]
25mod test {
26    use super::LeakyCow;
27    use std::borrow::Cow;
28    #[test]
29    fn test_string() {
30        let _ = {
31            let c = Cow::Borrowed("Let it go!");
32            c.leak();
33        };
34    }
35}