Skip to content
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

Add .as_str() to str::Chars and str::CharIndices #27900

Merged
merged 1 commit into from
Aug 29, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,18 @@ impl<'a> DoubleEndedIterator for Chars<'a> {
}
}

impl<'a> Chars<'a> {
/// View the underlying data as a subslice of the original data.
///
/// This has the same lifetime as the original slice, and so the
/// iterator can continue to be used while this exists.
#[unstable(feature = "iter_to_slice", issue = "27775")]
#[inline]
pub fn as_str(&self) -> &'a str {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this safely be done? We don't know that iteration isn't in the middle of a multi byte character, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, that’s a good point. I’ll make this one return &'a [u8].

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

… or remove it entirely because it accesses the inner iterator in Map.

unsafe { from_utf8_unchecked(self.iter.as_slice()) }
}
}

/// Iterator for a string's characters and their byte offsets.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down Expand Up @@ -339,6 +351,18 @@ impl<'a> DoubleEndedIterator for CharIndices<'a> {
}
}

impl<'a> CharIndices<'a> {
/// View the underlying data as a subslice of the original data.
///
/// This has the same lifetime as the original slice, and so the
/// iterator can continue to be used while this exists.
#[unstable(feature = "iter_to_slice", issue = "27775")]
#[inline]
pub fn as_str(&self) -> &'a str {
self.iter.as_str()
}
}

/// External iterator for a string's bytes.
/// Use with the `std::iter` module.
///
Expand Down