Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convenient way to transform struct with Cow-fields to owned

Tags:

rust

I have a struct defined like

struct Foo<'a> {
    field1: &'a str,
    field2: &'a str,
    field3: &'a u8,
    // ...
}

that I use for returning parsing results from an mmapped file. For some successful parses, I want to store the results for later processing and for various reasons that processing will happen after the memory is released. I could do something like

struct OwnedFoo {
    field1: String,
    field2: String,
    field3: Vec<u8>,
    // ...
}

and manually converting all Foos that I'm interested in into OwnedFoos. However I'm wondering if I could do something like:

struct Foo<'a> {
    field1: Cow<'a, str>,
    field2: Cow<'a, str>,
    field3: Cow<'a, u8>,
    ...
}

instead and if there's any way to automatically make all the Cows owned and erase the lifetime parameter. I haven't found anything in the library documentation that seems applicable.

Something like:

let a = Foo { ... };
let a_owned = a.into_owned();
// do stuff with a_owned that I can't do with a
like image 368
dnaq Avatar asked Feb 10 '17 08:02

dnaq


1 Answers

Building blocks:

  • Cow::into_owned will return the owned version.
  • 'static is the lifetime of the program

Therefore we can write a utility function:

use std::borrow::Cow;

fn into_owned<'a, B>(c: Cow<'a, B>) -> Cow<'static, B>
    where B: 'a + ToOwned + ?Sized
{
    Cow::Owned(c.into_owned())
}

You can expand this to Foo<'a> becoming Foo<'static> by simply applying the transformation on all fields.

like image 185
Matthieu M. Avatar answered Nov 15 '22 09:11

Matthieu M.