Skip to content

Commit

Permalink
Optimize str::repeat
Browse files Browse the repository at this point in the history
  • Loading branch information
sinkuu committed Mar 2, 2018
1 parent a85417f commit 08504fb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
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

0 comments on commit 08504fb

Please sign in to comment.