Skip to content

Commit 5e42c5c

Browse files
committed
core: Add str::reserve_at_least
1 parent b3d7823 commit 5e42c5c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/libcore/str.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ export
9393
is_char_boundary,
9494
char_at,
9595
reserve,
96+
reserve_at_least,
9697

9798
unsafe;
9899

@@ -1505,6 +1506,30 @@ fn reserve(&s: str, n: uint) {
15051506
rustrt::str_reserve_shared(s, n);
15061507
}
15071508

1509+
#[doc = "
1510+
Reserves capacity for at least `n` bytes in the given string, not including
1511+
the null terminator.
1512+
1513+
Assuming single-byte characters, the resulting string will be large
1514+
enough to hold a string of length `n`. To account for the null terminator,
1515+
the underlying buffer will have the size `n` + 1.
1516+
1517+
This function will over-allocate in order to amortize the allocation costs
1518+
in scenarios where the caller may need to repeatedly reserve additional
1519+
space.
1520+
1521+
If the capacity for `s` is already equal to or greater than the requested
1522+
capacity, then no action is taken.
1523+
1524+
# Arguments
1525+
1526+
* s - A string
1527+
* n - The number of bytes to reserve space for
1528+
"]
1529+
fn reserve_at_least(&s: str, n: uint) unsafe {
1530+
reserve(s, uint::next_power_of_two(n + 1u) - 1u)
1531+
}
1532+
15081533
#[doc = "Unsafe operations"]
15091534
mod unsafe {
15101535
export

0 commit comments

Comments
 (0)