1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//! Growable container builders on [`Arena`]: [`String`] and [`Vec`].
//!
//! All public methods are documented on [`Arena`] itself; this file
//! groups the family together to keep the central `mod.rs` smaller.
use allocator_api2::alloc::{AllocError, Allocator};
use super::Arena;
use crate::strings::String;
use crate::vec::Vec;
impl<A: Allocator + Clone> Arena<A> {
/// Create a new, empty growable [`String`](crate::strings::String) backed by this
/// arena. No allocation is performed until the first push.
///
/// # Example
///
/// ```
/// let arena = multitude::Arena::new();
/// let mut s = arena.alloc_string();
/// s.push_str("hello");
/// assert_eq!(&*s, "hello");
/// ```
#[must_use]
#[inline]
pub const fn alloc_string(&self) -> String<'_, A> {
String::new_in(self)
}
/// Create a new growable arena-backed [`String`](crate::strings::String) with capacity.
///
/// At least `cap` bytes are pre-allocated.
///
/// # Panics
///
/// Panics if the backing allocator fails. Use
/// [`Self::try_alloc_string_with_capacity`] for a fallible variant.
///
/// # Example
///
/// ```
/// let arena = multitude::Arena::new();
/// let mut s = arena.alloc_string_with_capacity(64);
/// s.push_str("preallocated");
/// assert!(s.capacity() >= 64);
/// ```
#[must_use]
#[inline]
pub fn alloc_string_with_capacity(&self, cap: usize) -> String<'_, A> {
String::with_capacity_in(cap, self)
}
/// Fallible variant of [`Self::alloc_string_with_capacity`].
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails.
#[inline]
pub fn try_alloc_string_with_capacity(&self, cap: usize) -> Result<String<'_, A>, AllocError> {
String::try_with_capacity_in(cap, self)
}
/// Validate `bytes` as UTF-8 and copy them into a fresh arena
/// [`String`]. The arena-bound analog of
/// [`std::string::String::from_utf8`] (taking a borrowed slice rather
/// than an owning `Vec<u8>`).
///
/// # Errors
///
/// Returns a [`Utf8Error`](core::str::Utf8Error) if `bytes` is not valid
/// UTF-8.
///
/// # Panics
///
/// Panics if the backing allocator fails. Allocation failure is reported
/// via a panic, not the returned `Result`.
pub fn alloc_string_from_utf8(&self, bytes: &[u8]) -> Result<String<'_, A>, core::str::Utf8Error> {
Ok(String::from_str_in(core::str::from_utf8(bytes)?, self))
}
/// Copy `bytes` into a fresh arena [`String`], replacing any invalid
/// UTF-8 sequences with `U+FFFD`. The arena-bound analog of
/// [`std::string::String::from_utf8_lossy`].
///
/// # Panics
///
/// Panics if the backing allocator fails.
#[must_use]
pub fn alloc_string_from_utf8_lossy(&self, bytes: &[u8]) -> String<'_, A> {
crate::arena::ExpectAlloc::expect_alloc(self.try_alloc_string_from_utf8_lossy(bytes))
}
/// Fallible variant of [`Self::alloc_string_from_utf8_lossy`].
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails.
pub fn try_alloc_string_from_utf8_lossy(&self, bytes: &[u8]) -> Result<String<'_, A>, AllocError> {
// Decode directly into the arena string; no intermediate global
// allocation (unlike `str::from_utf8_lossy`'s owned `Cow`).
let mut out = self.try_alloc_string_with_capacity(bytes.len())?;
for chunk in bytes.utf8_chunks() {
out.try_push_str(chunk.valid())?;
if !chunk.invalid().is_empty() {
out.try_push(char::REPLACEMENT_CHARACTER)?;
}
}
Ok(out)
}
/// Copy `bytes` into a fresh arena [`String`] without validating that
/// they are UTF-8. The arena-bound analog of
/// [`std::string::String::from_utf8_unchecked`].
///
/// # Safety
///
/// `bytes` must be valid UTF-8.
///
/// # Panics
///
/// Panics if the backing allocator fails.
#[must_use]
pub unsafe fn alloc_string_from_utf8_unchecked(&self, bytes: &[u8]) -> String<'_, A> {
// SAFETY: the caller guarantees `bytes` is valid UTF-8.
crate::arena::ExpectAlloc::expect_alloc(unsafe { self.try_alloc_string_from_utf8_unchecked(bytes) })
}
/// Fallible variant of [`Self::alloc_string_from_utf8_unchecked`].
///
/// # Safety
///
/// `bytes` must be valid UTF-8.
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails.
pub unsafe fn try_alloc_string_from_utf8_unchecked(&self, bytes: &[u8]) -> Result<String<'_, A>, AllocError> {
// SAFETY: the caller guarantees `bytes` is valid UTF-8.
String::try_from_str_in(unsafe { core::str::from_utf8_unchecked(bytes) }, self)
}
/// Decode native-endian UTF-16 `units` into a fresh arena [`String`].
/// The arena-bound analog of [`std::string::String::from_utf16`].
///
/// # Errors
///
/// Returns a [`DecodeUtf16Error`](core::char::DecodeUtf16Error) on the
/// first unpaired surrogate.
///
/// # Panics
///
/// Panics if the backing allocator fails. Allocation failure is reported
/// via a panic, not the returned `Result`.
pub fn alloc_string_from_utf16(&self, units: &[u16]) -> Result<String<'_, A>, core::char::DecodeUtf16Error> {
let mut out = self.alloc_string_with_capacity(units.len());
for unit in char::decode_utf16(units.iter().copied()) {
out.push(unit?);
}
Ok(out)
}
/// Decode native-endian UTF-16 `units` into a fresh arena [`String`],
/// replacing unpaired surrogates with `U+FFFD`. The arena-bound analog
/// of [`std::string::String::from_utf16_lossy`].
///
/// # Panics
///
/// Panics if the backing allocator fails.
#[must_use]
pub fn alloc_string_from_utf16_lossy(&self, units: &[u16]) -> String<'_, A> {
crate::arena::ExpectAlloc::expect_alloc(self.try_alloc_string_from_utf16_lossy(units))
}
/// Fallible variant of [`Self::alloc_string_from_utf16_lossy`].
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails.
pub fn try_alloc_string_from_utf16_lossy(&self, units: &[u16]) -> Result<String<'_, A>, AllocError> {
let mut out = self.try_alloc_string_with_capacity(units.len())?;
for unit in char::decode_utf16(units.iter().copied()) {
out.try_push(unit.unwrap_or(char::REPLACEMENT_CHARACTER))?;
}
Ok(out)
}
/// Decode little-endian UTF-16 `bytes` into a fresh arena [`String`]. The
/// arena-bound analog of [`std::string::String::from_utf16le`].
///
/// # Errors
///
/// Returns a [`FromUtf16Error`](crate::strings::FromUtf16Error) if `bytes`
/// has an odd length or contains an unpaired surrogate.
///
/// # Panics
///
/// Panics if the backing allocator fails. Allocation failure is reported
/// via a panic, not the returned `Result`.
pub fn alloc_string_from_utf16le(&self, bytes: &[u8]) -> Result<String<'_, A>, crate::strings::FromUtf16Error> {
self.alloc_string_from_utf16_bytes(bytes, false)
}
/// Decode big-endian UTF-16 `bytes` into a fresh arena [`String`]. The
/// arena-bound analog of [`std::string::String::from_utf16be`].
///
/// # Errors
///
/// Returns a [`FromUtf16Error`](crate::strings::FromUtf16Error) if `bytes`
/// has an odd length or contains an unpaired surrogate.
///
/// # Panics
///
/// Panics if the backing allocator fails. Allocation failure is reported
/// via a panic, not the returned `Result`.
pub fn alloc_string_from_utf16be(&self, bytes: &[u8]) -> Result<String<'_, A>, crate::strings::FromUtf16Error> {
self.alloc_string_from_utf16_bytes(bytes, true)
}
/// Decode little-endian UTF-16 `bytes` into a fresh arena [`String`] (lossy).
///
/// Odd trailing bytes and unpaired surrogates are replaced with `U+FFFD`. The
/// arena-bound analog of [`std::string::String::from_utf16le_lossy`].
///
/// # Panics
///
/// Panics if the backing allocator fails.
#[must_use]
pub fn alloc_string_from_utf16le_lossy(&self, bytes: &[u8]) -> String<'_, A> {
self.alloc_string_from_utf16_bytes_lossy(bytes, false)
}
/// Fallible variant of [`Self::alloc_string_from_utf16le_lossy`].
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails.
pub fn try_alloc_string_from_utf16le_lossy(&self, bytes: &[u8]) -> Result<String<'_, A>, AllocError> {
self.try_alloc_string_from_utf16_bytes_lossy(bytes, false)
}
/// Decode big-endian UTF-16 `bytes` into a fresh arena [`String`] (lossy).
///
/// Odd trailing bytes and unpaired surrogates are replaced with `U+FFFD`. The
/// arena-bound analog of [`std::string::String::from_utf16be_lossy`].
///
/// # Panics
///
/// Panics if the backing allocator fails.
#[must_use]
pub fn alloc_string_from_utf16be_lossy(&self, bytes: &[u8]) -> String<'_, A> {
self.alloc_string_from_utf16_bytes_lossy(bytes, true)
}
/// Fallible variant of [`Self::alloc_string_from_utf16be_lossy`].
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails.
pub fn try_alloc_string_from_utf16be_lossy(&self, bytes: &[u8]) -> Result<String<'_, A>, AllocError> {
self.try_alloc_string_from_utf16_bytes_lossy(bytes, true)
}
/// Shared body for the byte-oriented UTF-16 constructors. `big_endian`
/// selects the byte order used to assemble each `u16` code unit.
#[allow(
clippy::map_err_ignore,
reason = "FromUtf16Error is intentionally opaque; the DecodeUtf16Error carries no extra recoverable detail"
)]
fn alloc_string_from_utf16_bytes(&self, bytes: &[u8], big_endian: bool) -> Result<String<'_, A>, crate::strings::FromUtf16Error> {
if !bytes.len().is_multiple_of(2) {
return Err(crate::strings::FromUtf16Error::new());
}
let mut out = self.alloc_string_with_capacity(bytes.len() / 2);
let units = bytes.chunks_exact(2).map(|pair| {
let raw = [pair[0], pair[1]];
if big_endian {
u16::from_be_bytes(raw)
} else {
u16::from_le_bytes(raw)
}
});
for unit in char::decode_utf16(units) {
out.push(unit.map_err(|_| crate::strings::FromUtf16Error::new())?);
}
Ok(out)
}
/// Shared body for the lossy byte-oriented UTF-16 constructors.
fn alloc_string_from_utf16_bytes_lossy(&self, bytes: &[u8], big_endian: bool) -> String<'_, A> {
crate::arena::ExpectAlloc::expect_alloc(self.try_alloc_string_from_utf16_bytes_lossy(bytes, big_endian))
}
/// Fallible variant of [`Self::alloc_string_from_utf16_bytes_lossy`].
fn try_alloc_string_from_utf16_bytes_lossy(&self, bytes: &[u8], big_endian: bool) -> Result<String<'_, A>, AllocError> {
let mut out = self.try_alloc_string_with_capacity(bytes.len() / 2 + 1)?;
let units = bytes.chunks_exact(2).map(|pair| {
let raw = [pair[0], pair[1]];
if big_endian {
u16::from_be_bytes(raw)
} else {
u16::from_le_bytes(raw)
}
});
for unit in char::decode_utf16(units) {
out.try_push(unit.unwrap_or(char::REPLACEMENT_CHARACTER))?;
}
if !bytes.len().is_multiple_of(2) {
out.try_push(char::REPLACEMENT_CHARACTER)?;
}
Ok(out)
}
/// Create a new, empty growable [`Vec`](crate::vec::Vec) backed by this arena.
/// No allocation is performed until the first push.
///
/// # Example
///
/// ```
/// let arena = multitude::Arena::new();
/// let mut v = arena.alloc_vec::<u32>();
/// v.push(1);
/// v.push(2);
/// assert_eq!(v.as_slice(), &[1, 2]);
/// ```
#[must_use]
#[inline]
pub const fn alloc_vec<T>(&self) -> Vec<'_, T, A> {
Vec::new_in(self)
}
/// Create a new growable arena-backed [`Vec`](crate::vec::Vec) with capacity.
///
/// At least `cap` elements of capacity are pre-allocated.
///
/// # Panics
///
/// Panics if the backing allocator fails or if the data alignment is at least 32 KiB.
/// Use [`Self::try_alloc_vec_with_capacity`] for a fallible variant.
///
/// # Example
///
/// ```
/// let arena = multitude::Arena::new();
/// let mut v = arena.alloc_vec_with_capacity::<u32>(100);
/// for i in 0..50 {
/// v.push(i);
/// }
/// assert!(v.capacity() >= 100);
/// ```
#[must_use]
#[inline]
pub fn alloc_vec_with_capacity<T>(&self, cap: usize) -> Vec<'_, T, A> {
Vec::with_capacity_in(cap, self)
}
/// Fallible variant of [`Self::alloc_vec_with_capacity`].
///
/// # Errors
///
/// Returns [`AllocError`] if the backing allocator fails or if the data alignment
/// is at least 32 KiB.
#[inline]
pub fn try_alloc_vec_with_capacity<T>(&self, cap: usize) -> Result<Vec<'_, T, A>, AllocError> {
Vec::try_with_capacity_in(cap, self)
}
}