Skip to content

Commit

Permalink
auto merge of #8204 : kballard/rust/str-into-owned, r=graydon
Browse files Browse the repository at this point in the history
The method .into_owned() is meant to be used as an optimization when you
need to get a ~str from a Str, but don't want to unnecessarily copy it
if it's already a ~str.

This is meant to ease functions that look like

  fn foo<S: Str>(strs: &[S])

Previously they could work with the strings as slices using .as_slice(),
but producing ~str required copying the string, even if the vector
turned out be a &[~str] already.

I don't have any concrete uses for this yet, since the one conversion I've done to `&[S]` so far (see PR #8203) didn't actually need owned strings. But having this here may make using `Str` more attractive.

It also may be worth adding an `into_managed()` function, but that one is less obviously useful than `into_owned()`.
  • Loading branch information
bors committed Aug 3, 2013
2 parents 20fad0f + aa94dfa commit 39fafd6
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/libstd/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1079,25 +1079,37 @@ pub mod traits {}
pub trait Str {
/// Work with `self` as a slice.
fn as_slice<'a>(&'a self) -> &'a str;

/// Convert `self` into a ~str.
fn into_owned(self) -> ~str;
}

impl<'self> Str for &'self str {
#[inline]
fn as_slice<'a>(&'a self) -> &'a str { *self }

#[inline]
fn into_owned(self) -> ~str { self.to_owned() }
}

impl<'self> Str for ~str {
#[inline]
fn as_slice<'a>(&'a self) -> &'a str {
let s: &'a str = *self; s
}

#[inline]
fn into_owned(self) -> ~str { self }
}

impl<'self> Str for @str {
#[inline]
fn as_slice<'a>(&'a self) -> &'a str {
let s: &'a str = *self; s
}

#[inline]
fn into_owned(self) -> ~str { self.to_owned() }
}

impl<'self> Container for &'self str {
Expand Down

0 comments on commit 39fafd6

Please sign in to comment.