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
use crate::{
alloc::{TryClone, str_ptr_from_raw_parts, try_realloc},
error::OutOfMemory,
};
use core::{borrow::Borrow, fmt, mem, ops};
use std_alloc::{alloc::Layout, boxed::Box, string as inner};
/// A newtype wrapper around [`std::string::String`] that only exposes
/// fallible-allocation methods.
#[derive(Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct TryString {
inner: inner::String,
}
impl TryClone for TryString {
fn try_clone(&self) -> Result<Self, OutOfMemory> {
let mut s = Self::new();
s.push_str(self)?;
Ok(s)
}
}
impl fmt::Debug for TryString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.inner, f)
}
}
impl fmt::Display for TryString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl ops::Deref for TryString {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl ops::DerefMut for TryString {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl AsRef<str> for TryString {
fn as_ref(&self) -> &str {
self
}
}
impl Borrow<str> for TryString {
fn borrow(&self) -> &str {
self
}
}
impl From<inner::String> for TryString {
#[inline]
fn from(inner: inner::String) -> Self {
Self { inner }
}
}
#[cfg(feature = "serde")]
impl serde::ser::Serialize for TryString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::de::Deserialize<'de> for TryString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = TryString;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a `wasmtime_core::alloc::String` str")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let mut s = TryString::new();
s.reserve_exact(v.len()).map_err(|oom| E::custom(oom))?;
s.push_str(v).expect("reserved capacity");
Ok(s)
}
}
// NB: do not use `deserialize_string` as that eagerly allocates the
// `String` and does not give us a chance to handle OOM. Instead, use
// `deserialize_str` which passes the visitor the borrowed `str`, giving
// us a chance to fallibly allocate space.
deserializer.deserialize_str(Visitor)
}
}
impl TryString {
/// Same as [`std::string::String::new`].
#[inline]
pub fn new() -> Self {
Self {
inner: inner::String::new(),
}
}
/// Same as [`std::string::String::with_capacity`] but returns an error on
/// allocation failure.
#[inline]
pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
let mut s = Self::new();
s.reserve(capacity)?;
Ok(s)
}
/// Same as [`std::string::String::capacity`].
#[inline]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
/// Same as [`std::string::String::as_str`].
#[inline]
pub const fn as_str(&self) -> &str {
self.inner.as_str()
}
/// Same as [`std::string::String::reserve`] but returns an error on
/// allocation failure.
#[inline]
pub fn reserve(&mut self, additional: usize) -> Result<(), OutOfMemory> {
self.inner
.try_reserve(additional)
.map_err(|_| OutOfMemory::new(self.len().saturating_add(additional)))
}
/// Same as [`std::string::String::reserve_exact`] but returns an error on
/// allocation failure.
#[inline]
pub fn reserve_exact(&mut self, additional: usize) -> Result<(), OutOfMemory> {
self.inner
.try_reserve_exact(additional)
.map_err(|_| OutOfMemory::new(self.len().saturating_add(additional)))
}
/// Same as [`std::string::String::push`] but returns an error on allocation
/// failure.
#[inline]
pub fn push(&mut self, c: char) -> Result<(), OutOfMemory> {
self.reserve(c.len_utf8())?;
self.inner.push(c);
Ok(())
}
/// Same as [`std::string::String::push_str`] but returns an error on
/// allocation failure.
#[inline]
pub fn push_str(&mut self, s: &str) -> Result<(), OutOfMemory> {
self.reserve(s.len())?;
self.inner.push_str(s);
Ok(())
}
/// Same as [`std::string::String::into_raw_parts`].
pub fn into_raw_parts(mut self) -> (*mut u8, usize, usize) {
// NB: Can't use `String::into_raw_parts` until our MSRV is >= 1.93.
#[cfg(not(miri))]
{
let ptr = self.as_mut_ptr();
let len = self.len();
let cap = self.capacity();
mem::forget(self);
(ptr, len, cap)
}
// NB: Miri requires using `into_raw_parts`, but always run on nightly,
// so it's fine to use there.
#[cfg(miri)]
{
let _ = &mut self;
self.inner.into_raw_parts()
}
}
/// Same as [`std::string::String::from_raw_parts`].
pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> Self {
Self {
// Safety: Same as our unsafe contract.
inner: unsafe { inner::String::from_raw_parts(buf, length, capacity) },
}
}
/// Same as [`std::string::String::shrink_to_fit`] but returns an error on
/// allocation failure.
pub fn shrink_to_fit(&mut self) -> Result<(), OutOfMemory> {
// If our length is already equal to our capacity, then there is nothing
// to shrink.
if self.len() == self.capacity() {
return Ok(());
}
// `realloc` requires a non-zero original layout as well as a non-zero
// destination layout, so this guard ensures that the sizes below are
// all nonzero. This handles a couple cases:
//
// * If `len == cap == 0` then no allocation has ever been made.
// * If `len == 0` and `cap != 0` then this function effectively frees
// the memory.
//
// In both of these cases delegate to the standard library's
// `shrink_to_fit` which is guaranteed to not perform a `realloc`.
if self.is_empty() {
self.inner.shrink_to_fit();
return Ok(());
}
let (ptr, len, cap) = mem::take(self).into_raw_parts();
debug_assert!(!ptr.is_null());
debug_assert!(len > 0);
debug_assert!(cap > len);
let old_layout = Layout::array::<u8>(cap).unwrap();
debug_assert_eq!(old_layout.size(), cap);
let new_layout = Layout::array::<u8>(len).unwrap();
debug_assert_eq!(old_layout.align(), new_layout.align());
debug_assert_eq!(new_layout.size(), len);
// SAFETY: `ptr` was previously allocated in the global allocator,
// `layout` has a nonzero size and matches the current allocation of
// `ptr`, `len` is nonzero, and `len` is a valid array size
// for `len` elements given its constructor.
let result = unsafe { try_realloc(ptr, old_layout, len) };
match result {
Ok(ptr) => {
// SAFETY: `result` is allocated with the global allocator and
// has room for exactly `[u8; len]`.
*self = unsafe { Self::from_raw_parts(ptr.as_ptr(), len, len) };
Ok(())
}
Err(oom) => {
// SAFETY: If reallocation fails then it's guaranteed that the
// original allocation is not tampered with, so it's safe to
// reassemble the original vector.
*self = unsafe { Self::from_raw_parts(ptr, len, cap) };
Err(oom)
}
}
}
/// Same as [`std::string::String::into_boxed_str`] but returns an error on
/// allocation failure.
pub fn into_boxed_str(mut self) -> Result<Box<str>, OutOfMemory> {
self.shrink_to_fit()?;
let (ptr, len, cap) = self.into_raw_parts();
debug_assert_eq!(len, cap);
let ptr = str_ptr_from_raw_parts(ptr, len);
// SAFETY: The `ptr` is allocated with the global allocator and points
// to a valid block of utf8.
let boxed = unsafe { Box::from_raw(ptr) };
Ok(boxed)
}
}