Skip to content

Commit ec0e90a

Browse files
committed
add ctor/dtors: new_in, from_raw_parts_in, etc
Yes, you could just use `unsafe { from_utf8_unchecked }``, but people get antsy about `unsafe`, so add some Vec ctor/dtor equivalents.
1 parent 54c2a69 commit ec0e90a

File tree

1 file changed

+179
-0
lines changed

1 file changed

+179
-0
lines changed

library/alloc/src/string.rs

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,97 @@ impl String {
937937
}
938938

939939
impl<A: Allocator> generic::String<A> {
940+
/// Creates a new empty `String`.
941+
///
942+
/// Given that the `String` is empty, this will not allocate any initial
943+
/// buffer. While that means that this initial operation is very
944+
/// inexpensive, it may cause excessive allocation later when you add
945+
/// data. If you have an idea of how much data the `String` will hold,
946+
/// consider the [`with_capacity_in`] method to prevent excessive
947+
/// re-allocation.
948+
///
949+
/// [`with_capacity_in`]: String::with_capacity_in
950+
///
951+
/// # Examples
952+
///
953+
/// ```
954+
/// #![feature(allocator_api)]
955+
///
956+
/// use std::alloc::System;
957+
/// use std::string::generic::String;
958+
///
959+
/// # #[allow(unused_mut)]
960+
/// let mut s = String::new_in(System);
961+
/// ```
962+
#[inline]
963+
#[unstable(feature = "allocator_api", issue = "32838")]
964+
#[must_use]
965+
pub const fn new_in(alloc: A) -> Self {
966+
generic::String { vec: Vec::new_in(alloc) }
967+
}
968+
969+
/// Creates a new empty `String` with at least the specified capacity in the specified allocator.
970+
///
971+
/// `String`s have an internal buffer to hold their data. The capacity is
972+
/// the length of that buffer, and can be queried with the [`capacity`]
973+
/// method. This method creates an empty `String`, but one with an initial
974+
/// buffer that can hold at least `capacity` bytes. This is useful when you
975+
/// may be appending a bunch of data to the `String`, reducing the number of
976+
/// reallocations it needs to do.
977+
///
978+
/// [`capacity`]: String::capacity
979+
///
980+
/// If the given capacity is `0`, no allocation will occur, and this method
981+
/// is identical to the [`new_in`] method.
982+
///
983+
/// [`new_in`]: String::new_in
984+
///
985+
/// # Examples
986+
///
987+
/// ```
988+
/// #![feature(allocator_api)]
989+
///
990+
/// use std::alloc::System;
991+
/// use std::string::generic::String;
992+
///
993+
/// let mut s = String::with_capacity_in(10, System);
994+
///
995+
/// // The String contains no chars, even though it has capacity for more
996+
/// assert_eq!(s.len(), 0);
997+
///
998+
/// // These are all done without reallocating...
999+
/// let cap = s.capacity();
1000+
/// for _ in 0..10 {
1001+
/// s.push('a');
1002+
/// }
1003+
///
1004+
/// assert_eq!(s.capacity(), cap);
1005+
///
1006+
/// // ...but this may make the string reallocate
1007+
/// s.push('a');
1008+
/// ```
1009+
#[inline]
1010+
#[cfg(not(no_global_oom_handling))]
1011+
#[unstable(feature = "allocator_api", issue = "32838")]
1012+
#[must_use]
1013+
pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
1014+
generic::String { vec: Vec::with_capacity_in(capacity, alloc) }
1015+
}
1016+
1017+
/// Creates a new empty `String` with at least the specified capacity, in the specified allocator.
1018+
///
1019+
/// # Errors
1020+
///
1021+
/// Returns [`Err`] if the capacity exceeds `isize::MAX` bytes,
1022+
/// or if the memory allocator reports failure.
1023+
///
1024+
#[inline]
1025+
#[unstable(feature = "allocator_api", issue = "32838")]
1026+
// #[unstable(feature = "try_with_capacity", issue = "91913")]
1027+
pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
1028+
Ok(generic::String { vec: Vec::try_with_capacity_in(capacity, alloc)? })
1029+
}
1030+
9401031
/// Converts a vector of bytes to a `String`.
9411032
///
9421033
/// A string ([`String`]) is made of bytes ([`u8`]), and a vector of bytes
@@ -2186,6 +2277,94 @@ impl<A: Allocator> generic::String<A> {
21862277
unsafe { from_boxed_utf8_unchecked(slice) }
21872278
}
21882279

2280+
/// Decomposes a `String` into its raw components: `(pointer, length, capacity, allocator)`.
2281+
///
2282+
/// Returns the raw pointer to the underlying data, the length of
2283+
/// the string (in bytes), the allocated capacity of the data
2284+
/// (in bytes), and the allocator storing the bytes. These are the same arguments in the same order as
2285+
/// the arguments to [`from_raw_parts_in`].
2286+
///
2287+
/// After calling this function, the caller is responsible for the
2288+
/// memory previously managed by the `String`. The only way to do
2289+
/// this is to convert the raw pointer, length, and capacity back
2290+
/// into a `String` with the [`from_raw_parts_in`] function, allowing
2291+
/// the destructor to perform the cleanup.
2292+
///
2293+
/// [`from_raw_parts_in`]: String::from_raw_parts_in
2294+
///
2295+
/// # Examples
2296+
///
2297+
/// ```
2298+
/// #![feature(allocator_api)]
2299+
///
2300+
/// use std::alloc::System;
2301+
/// use std::string::generic::String;
2302+
///
2303+
/// let mut s = String::new_in(System);
2304+
/// s.push_str("hello");
2305+
///
2306+
/// let (ptr, len, cap, alloc) = s.into_raw_parts_with_alloc();
2307+
///
2308+
/// let rebuilt = unsafe { String::from_raw_parts_in(ptr, len, cap, alloc) };
2309+
/// assert_eq!(rebuilt, "hello");
2310+
/// ```
2311+
#[inline]
2312+
#[must_use = "losing the pointer will leak memory"]
2313+
#[unstable(feature = "allocator_api", issue = "32838")]
2314+
pub fn into_raw_parts_with_alloc(self) -> (*mut u8, usize, usize, A) {
2315+
self.vec.into_raw_parts_with_alloc()
2316+
}
2317+
2318+
/// Creates a new `String` from a pointer, a length, a capacity, and an allocator.
2319+
///
2320+
/// # Safety
2321+
///
2322+
/// This is highly unsafe, due to the number of invariants that aren't
2323+
/// checked:
2324+
///
2325+
/// * all safety requirements for [`Vec::<u8>::from_raw_parts_in`].
2326+
/// * all safety requirements for [`String::from_utf8_unchecked`].
2327+
///
2328+
/// Violating these may cause problems like corrupting the allocator's
2329+
/// internal data structures. For example, it is normally **not** safe to
2330+
/// build a `String` from a pointer to a C `char` array containing UTF-8
2331+
/// _unless_ you are certain that array is [*currently allocated*] via the given allocator `alloc`.
2332+
///
2333+
/// The ownership of `buf` is effectively transferred to the
2334+
/// `String` which may then deallocate, reallocate or change the
2335+
/// contents of memory pointed to by the pointer at will. Ensure
2336+
/// that nothing else uses the pointer after calling this
2337+
/// function.
2338+
///
2339+
/// # Examples
2340+
///
2341+
/// ```
2342+
/// #![feature(allocator_api)]
2343+
///
2344+
/// use std::alloc::System;
2345+
/// use std::string::generic::String;
2346+
///
2347+
/// let mut s = String::new_in(System);
2348+
/// s.push_str("hello");
2349+
///
2350+
/// // Deconstruct the String into parts.
2351+
/// let (ptr, len, capacity, alloc) = s.into_raw_parts_with_alloc();
2352+
///
2353+
/// let rebuilt = unsafe { String::from_raw_parts_in(ptr, len, capacity, alloc) };
2354+
/// assert_eq!(rebuilt, "hello");
2355+
/// ```
2356+
#[inline]
2357+
#[unstable(feature = "allocator_api", issue = "32838")]
2358+
pub unsafe fn from_raw_parts_in(
2359+
ptr: *mut u8,
2360+
length: usize,
2361+
capacity: usize,
2362+
alloc: A,
2363+
) -> Self {
2364+
let vec = unsafe { Vec::from_raw_parts_in(ptr, length, capacity, alloc) };
2365+
generic::String { vec }
2366+
}
2367+
21892368
/// Consumes and leaks the `String`, returning a mutable reference to the contents,
21902369
/// `&'a mut str`.
21912370
///

0 commit comments

Comments
 (0)