Skip to content

Avoid unnecessary allocation in <Value as From<Cow<'a, str>>>::from() #405

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
H2CO3 opened this issue Jan 20, 2018 · 3 comments
Closed

Avoid unnecessary allocation in <Value as From<Cow<'a, str>>>::from() #405

H2CO3 opened this issue Jan 20, 2018 · 3 comments

Comments

@H2CO3
Copy link

H2CO3 commented Jan 20, 2018

The current implementation of From<Cow<'a, str>>::from() is:

fn from(f: Cow<'a, str>) -> Self {
    Value::String(f.to_string())
}

Now, Cow<'a, str>::to_string() unconditionally allocates and copies (and it has to, because it takes &self by pointer, as dictated by the ToString trait). But since From::from takes its argument by value, I believe it would be possible to implement it like this instead:

fn from(f: Cow<'a, str>) -> Self {
    match f {
        Cow::Borrowed(slice) => Value::String(slice.to_owned()),
        Cow::Owned(buf) => Value::String(buf),
    }
}

What do you think? If it's possible and worth implementing, I'd be happy to open a PR.

@dtolnay
Copy link
Member

dtolnay commented Jan 20, 2018

Seems reasonable! Please send a PR.

@dtolnay
Copy link
Member

dtolnay commented Jan 20, 2018

Value::String(f.into_owned()) should work.

@H2CO3
Copy link
Author

H2CO3 commented Jan 20, 2018

Oh, indeed, good catch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants