Skip to content

implement FromIterator<char> for Box<str> #65168

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
wants to merge 12 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 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
10 changes: 10 additions & 0 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ use core::task::{Context, Poll};
use crate::alloc::{self, Global, Alloc};
use crate::vec::Vec;
use crate::raw_vec::RawVec;
use crate::string::String;
use crate::str::from_boxed_utf8_unchecked;

/// A pointer type for heap allocation.
Expand Down Expand Up @@ -1070,3 +1071,12 @@ impl<F: ?Sized + Future + Unpin> Future for Box<F> {
F::poll(Pin::new(&mut *self), cx)
}
}

#[unstable(feature = "box_str_from_iter", issue = "0")]
Copy link
Member

Choose a reason for hiding this comment

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

impls are going to be insta-stable, you can probably make this just be stable with the same feature name

impl FromIterator<char> for Box<str> {
fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Box<str> {
let mut buf = String::new();
buf.extend(iter);
buf.into_boxed_str()
Copy link
Contributor

Choose a reason for hiding this comment

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

Can the string creation reuse String::from_iter?

String::from_iter(iter).into_boxed_str()

Copy link
Author

Choose a reason for hiding this comment

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

You're right, thanks!

}
}
10 changes: 10 additions & 0 deletions src/liballoc/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use core::f64;
use core::i64;

use std::boxed::Box;
use std::string::String;

#[test]
fn test_owned_clone() {
Expand Down Expand Up @@ -151,3 +152,12 @@ fn test_array_from_slice() {
let a: Result<Box<[u32; 2]>, _> = r.clone().try_into();
assert!(a.is_err());
}

#[test]
fn box_str_from_iter(){
let iter = (0..100).map(|_|{'☺'});
Copy link
Contributor

Choose a reason for hiding this comment

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

let string: Box<str> = iter.collect();

assert_eq!(string.len(), 100);
assert_eq!(string.chars().nth(5), '☺');
}