Skip to content

Optimize str::repeat #48657

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

Merged
merged 3 commits into from
Mar 6, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Optimize str::repeat
  • Loading branch information
sinkuu committed Mar 2, 2018
commit 08504fbb0b05abdd9543f08102b0d6275dde210c
1 change: 1 addition & 0 deletions src/liballoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
#![feature(allocator_internals)]
#![feature(on_unimplemented)]
#![feature(exact_chunks)]
#![feature(pointer_methods)]

#![cfg_attr(not(test), feature(fused, fn_traits, placement_new_protocol, swap_with_slice, i128))]
#![cfg_attr(test, feature(test, box_heap))]
Expand Down
37 changes: 34 additions & 3 deletions src/liballoc/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use core::str as core_str;
use core::str::pattern::Pattern;
use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
use core::mem;
use core::ptr;
use core::iter::FusedIterator;
use std_unicode::str::{UnicodeStr, Utf16Encoder};

Expand Down Expand Up @@ -2066,9 +2067,39 @@ impl str {
/// ```
#[stable(feature = "repeat_str", since = "1.16.0")]
pub fn repeat(&self, n: usize) -> String {
let mut s = String::with_capacity(self.len() * n);
s.extend((0..n).map(|_| self));
s
if n == 0 {
return String::new();
}

// n = 2^j + k (2^j > k)

// 2^j:
let mut s = Vec::with_capacity(self.len() * n);
s.extend(self.as_bytes());
let mut m = n >> 1;
while m > 0 {
let len = s.len();
unsafe {
ptr::copy_nonoverlapping(s.as_ptr(), (s.as_mut_ptr() as *mut u8).add(len), len);
s.set_len(len * 2);
}
m >>= 1;
}

// k:
let res_len = n * self.len();
if res_len > s.len() {
unsafe {
ptr::copy_nonoverlapping(
s.as_ptr(),
(s.as_mut_ptr() as *mut u8).add(s.len()),
res_len - s.len(),
);
s.set_len(res_len);
}
}

unsafe { String::from_utf8_unchecked(s) }
}

/// Checks if all characters in this string are within the ASCII range.
Expand Down