Skip to content

Commit 08504fb

Browse files
committed
Optimize str::repeat
1 parent a85417f commit 08504fb

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

src/liballoc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@
124124
#![feature(allocator_internals)]
125125
#![feature(on_unimplemented)]
126126
#![feature(exact_chunks)]
127+
#![feature(pointer_methods)]
127128

128129
#![cfg_attr(not(test), feature(fused, fn_traits, placement_new_protocol, swap_with_slice, i128))]
129130
#![cfg_attr(test, feature(test, box_heap))]

src/liballoc/str.rs

+34-3
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ use core::str as core_str;
4343
use core::str::pattern::Pattern;
4444
use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
4545
use core::mem;
46+
use core::ptr;
4647
use core::iter::FusedIterator;
4748
use std_unicode::str::{UnicodeStr, Utf16Encoder};
4849

@@ -2066,9 +2067,39 @@ impl str {
20662067
/// ```
20672068
#[stable(feature = "repeat_str", since = "1.16.0")]
20682069
pub fn repeat(&self, n: usize) -> String {
2069-
let mut s = String::with_capacity(self.len() * n);
2070-
s.extend((0..n).map(|_| self));
2071-
s
2070+
if n == 0 {
2071+
return String::new();
2072+
}
2073+
2074+
// n = 2^j + k (2^j > k)
2075+
2076+
// 2^j:
2077+
let mut s = Vec::with_capacity(self.len() * n);
2078+
s.extend(self.as_bytes());
2079+
let mut m = n >> 1;
2080+
while m > 0 {
2081+
let len = s.len();
2082+
unsafe {
2083+
ptr::copy_nonoverlapping(s.as_ptr(), (s.as_mut_ptr() as *mut u8).add(len), len);
2084+
s.set_len(len * 2);
2085+
}
2086+
m >>= 1;
2087+
}
2088+
2089+
// k:
2090+
let res_len = n * self.len();
2091+
if res_len > s.len() {
2092+
unsafe {
2093+
ptr::copy_nonoverlapping(
2094+
s.as_ptr(),
2095+
(s.as_mut_ptr() as *mut u8).add(s.len()),
2096+
res_len - s.len(),
2097+
);
2098+
s.set_len(res_len);
2099+
}
2100+
}
2101+
2102+
unsafe { String::from_utf8_unchecked(s) }
20722103
}
20732104

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

0 commit comments

Comments
 (0)