| 1 |
//! Implement Fallible Vec |
| 2 |
use super::TryClone; |
| 3 |
use crate::TryReserveError; |
| 4 |
#[allow(unused_imports)] |
| 5 |
use alloc::alloc::{alloc, realloc, Layout}; |
| 6 |
use alloc::vec::Vec; |
| 7 |
use core::convert::TryInto as _; |
| 8 |
|
| 9 |
#[cfg(feature = "unstable")] |
| 10 |
#[macro_export] |
| 11 |
/// macro trying to create a vec, return a |
| 12 |
/// Result<Vec<T>,TryReserveError> |
| 13 |
macro_rules! try_vec { |
| 14 |
($elem:expr; $n:expr) => ( |
| 15 |
$crate::vec::try_from_elem($elem, $n) |
| 16 |
); |
| 17 |
($($x:expr),*) => ( |
| 18 |
match <alloc::boxed::Box<_> as $crate::boxed::FallibleBox<_>>::try_new([$($x),*]) { |
| 19 |
Err(e) => Err(e), |
| 20 |
Ok(b) => Ok(<[_]>::into_vec(b)), |
| 21 |
} |
| 22 |
); |
| 23 |
($($x:expr,)*) => ($crate::try_vec![$($x),*]) |
| 24 |
} |
| 25 |
|
| 26 |
/// trait implementing all fallible methods on vec |
| 27 |
pub trait FallibleVec<T> { |
| 28 |
/// see reserve |
| 29 |
fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>; |
| 30 |
/// see push |
| 31 |
fn try_push(&mut self, elem: T) -> Result<(), TryReserveError>; |
| 32 |
/// try push and give back ownership in case of error |
| 33 |
fn try_push_give_back(&mut self, elem: T) -> Result<(), (T, TryReserveError)>; |
| 34 |
/// see with capacity, (Self must be sized by the constraint of Result) |
| 35 |
fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> |
| 36 |
where |
| 37 |
Self: core::marker::Sized; |
| 38 |
/// see insert |
| 39 |
fn try_insert(&mut self, index: usize, element: T) -> Result<(), (T, TryReserveError)>; |
| 40 |
/// see append |
| 41 |
fn try_append(&mut self, other: &mut Self) -> Result<(), TryReserveError>; |
| 42 |
/// see resize, only works when the `value` implements Copy, otherwise, look at try_resize_no_copy |
| 43 |
fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> |
| 44 |
where |
| 45 |
T: Copy + Clone; |
| 46 |
fn try_resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), TryReserveError> |
| 47 |
where |
| 48 |
F: FnMut() -> T; |
| 49 |
/// resize the vec by trying to clone the value repeatingly |
| 50 |
fn try_resize_no_copy(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> |
| 51 |
where |
| 52 |
T: TryClone; |
| 53 |
/// see resize, only works when the `value` implements Copy, otherwise, look at try_extend_from_slice_no_copy |
| 54 |
fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> |
| 55 |
where |
| 56 |
T: Copy + Clone; |
| 57 |
/// extend the vec by trying to clone the value in `other` |
| 58 |
fn try_extend_from_slice_no_copy(&mut self, other: &[T]) -> Result<(), TryReserveError> |
| 59 |
where |
| 60 |
T: TryClone; |
| 61 |
} |
| 62 |
|
| 63 |
/// TryVec is a thin wrapper around alloc::vec::Vec to provide support for |
| 64 |
/// fallible allocation. |
| 65 |
/// |
| 66 |
/// See the crate documentation for more. |
| 67 |
#[derive(PartialEq)] |
| 68 |
pub struct TryVec<T> { |
| 69 |
inner: Vec<T>, |
| 70 |
} |
| 71 |
|
| 72 |
impl<T> Default for TryVec<T> { |
| 73 |
#[inline(always)] |
| 74 |
fn default() -> Self { |
| 75 |
Self { |
| 76 |
inner: Default::default(), |
| 77 |
} |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
impl<T: core::fmt::Debug> core::fmt::Debug for TryVec<T> { |
| 82 |
#[inline] |
| 83 |
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 84 |
self.inner.fmt(f) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
impl<T> TryVec<T> { |
| 89 |
#[inline(always)] |
| 90 |
pub fn new() -> Self { |
| 91 |
Self { inner: Vec::new() } |
| 92 |
} |
| 93 |
|
| 94 |
#[inline] |
| 95 |
pub fn with_capacity(capacity: usize) -> Result<Self, TryReserveError> { |
| 96 |
Ok(Self { |
| 97 |
inner: FallibleVec::try_with_capacity(capacity)?, |
| 98 |
}) |
| 99 |
} |
| 100 |
|
| 101 |
#[inline(always)] |
| 102 |
pub fn append(&mut self, other: &mut Self) -> Result<(), TryReserveError> { |
| 103 |
FallibleVec::try_append(&mut self.inner, &mut other.inner) |
| 104 |
} |
| 105 |
|
| 106 |
#[inline(always)] |
| 107 |
pub fn as_mut_slice(&mut self) -> &mut [T] { |
| 108 |
self |
| 109 |
} |
| 110 |
|
| 111 |
#[inline(always)] |
| 112 |
pub fn as_slice(&self) -> &[T] { |
| 113 |
self |
| 114 |
} |
| 115 |
|
| 116 |
#[inline(always)] |
| 117 |
pub fn clear(&mut self) { |
| 118 |
self.inner.clear() |
| 119 |
} |
| 120 |
|
| 121 |
#[cfg(test)] |
| 122 |
pub fn into_inner(self) -> Vec<T> { |
| 123 |
self.inner |
| 124 |
} |
| 125 |
|
| 126 |
#[inline(always)] |
| 127 |
pub fn is_empty(&self) -> bool { |
| 128 |
self.inner.is_empty() |
| 129 |
} |
| 130 |
|
| 131 |
#[inline(always)] |
| 132 |
pub fn iter_mut(&mut self) -> IterMut<T> { |
| 133 |
IterMut { |
| 134 |
inner: self.inner.iter_mut(), |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
#[inline(always)] |
| 139 |
pub fn iter(&self) -> Iter<T> { |
| 140 |
Iter { |
| 141 |
inner: self.inner.iter(), |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
#[inline(always)] |
| 146 |
pub fn pop(&mut self) -> Option<T> { |
| 147 |
self.inner.pop() |
| 148 |
} |
| 149 |
|
| 150 |
#[inline(always)] |
| 151 |
pub fn push(&mut self, value: T) -> Result<(), TryReserveError> { |
| 152 |
FallibleVec::try_push(&mut self.inner, value) |
| 153 |
} |
| 154 |
|
| 155 |
#[inline(always)] |
| 156 |
pub fn reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { |
| 157 |
FallibleVec::try_reserve(&mut self.inner, additional) |
| 158 |
} |
| 159 |
|
| 160 |
#[inline(always)] |
| 161 |
pub fn resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), TryReserveError> |
| 162 |
where |
| 163 |
F: FnMut() -> T, |
| 164 |
{ |
| 165 |
FallibleVec::try_resize_with(&mut self.inner, new_len, f) |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
impl<T: TryClone> TryClone for TryVec<T> { |
| 170 |
#[inline] |
| 171 |
fn try_clone(&self) -> Result<Self, TryReserveError> { |
| 172 |
self.as_slice().try_into() |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
impl<T: TryClone> TryVec<TryVec<T>> { |
| 177 |
pub fn concat(&self) -> Result<TryVec<T>, TryReserveError> { |
| 178 |
let size = self.iter().map(|v| v.inner.len()).sum(); |
| 179 |
let mut result = TryVec::with_capacity(size)?; |
| 180 |
for v in self.iter() { |
| 181 |
result.inner.try_extend_from_slice_no_copy(&v.inner)?; |
| 182 |
} |
| 183 |
Ok(result) |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
impl<T: TryClone> TryVec<T> { |
| 188 |
#[inline(always)] |
| 189 |
pub fn extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> { |
| 190 |
self.inner.try_extend_from_slice_no_copy(other) |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
impl<T> IntoIterator for TryVec<T> { |
| 195 |
type Item = T; |
| 196 |
type IntoIter = alloc::vec::IntoIter<T>; |
| 197 |
|
| 198 |
#[inline(always)] |
| 199 |
fn into_iter(self) -> Self::IntoIter { |
| 200 |
self.inner.into_iter() |
| 201 |
} |
| 202 |
} |
| 203 |
|
| 204 |
impl<'a, T> IntoIterator for &'a TryVec<T> { |
| 205 |
type Item = &'a T; |
| 206 |
type IntoIter = alloc::slice::Iter<'a, T>; |
| 207 |
|
| 208 |
#[inline(always)] |
| 209 |
fn into_iter(self) -> Self::IntoIter { |
| 210 |
self.inner.iter() |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
#[cfg(feature = "std_io")] |
| 215 |
pub mod std_io { |
| 216 |
use super::*; |
| 217 |
use std::io::{self, Read, Take, Write}; |
| 218 |
|
| 219 |
pub trait TryRead { |
| 220 |
fn try_read_to_end(&mut self, buf: &mut TryVec<u8>) -> io::Result<usize>; |
| 221 |
|
| 222 |
#[inline] |
| 223 |
fn read_into_try_vec(&mut self) -> io::Result<TryVec<u8>> { |
| 224 |
let mut buf = TryVec::new(); |
| 225 |
self.try_read_to_end(&mut buf)?; |
| 226 |
Ok(buf) |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
impl<T: Read> TryRead for Take<T> { |
| 231 |
/// This function reserves the upper limit of what `src` can generate before |
| 232 |
/// reading all bytes until EOF in this source, placing them into `buf`. If the |
| 233 |
/// allocation is unsuccessful, or reading from the source generates an error |
| 234 |
/// before reaching EOF, this will return an error. Otherwise, it will return |
| 235 |
/// the number of bytes read. |
| 236 |
/// |
| 237 |
/// Since `Take::limit()` may return a value greater than the number of bytes |
| 238 |
/// which can be read from the source, it's possible this function may fail |
| 239 |
/// in the allocation phase even though allocating the number of bytes available |
| 240 |
/// to read would have succeeded. In general, it is assumed that the callers |
| 241 |
/// have accurate knowledge of the number of bytes of interest and have created |
| 242 |
/// `src` accordingly. |
| 243 |
#[inline] |
| 244 |
fn try_read_to_end(&mut self, buf: &mut TryVec<u8>) -> io::Result<usize> { |
| 245 |
try_read_up_to(self, self.limit(), buf) |
| 246 |
} |
| 247 |
} |
| 248 |
|
| 249 |
/// Read up to `limit` bytes from `src`, placing them into `buf` and returning the |
| 250 |
/// number of bytes read. Space for `limit` additional bytes is reserved in `buf`, so |
| 251 |
/// this function will return an error if the allocation fails. |
| 252 |
pub fn try_read_up_to<R: Read>( |
| 253 |
src: &mut R, |
| 254 |
limit: u64, |
| 255 |
buf: &mut TryVec<u8>, |
| 256 |
) -> io::Result<usize> { |
| 257 |
let additional = limit |
| 258 |
.try_into() |
| 259 |
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; |
| 260 |
buf.reserve(additional) |
| 261 |
.map_err(|_| io::Error::new(io::ErrorKind::Other, "reserve allocation failed"))?; |
| 262 |
let bytes_read = src.take(limit).read_to_end(&mut buf.inner)?; |
| 263 |
Ok(bytes_read) |
| 264 |
} |
| 265 |
|
| 266 |
impl Write for TryVec<u8> { |
| 267 |
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 268 |
self.extend_from_slice(buf) |
| 269 |
.map_err(|_| io::Error::new(io::ErrorKind::Other, "extend_from_slice failed"))?; |
| 270 |
Ok(buf.len()) |
| 271 |
} |
| 272 |
|
| 273 |
#[inline(always)] |
| 274 |
fn flush(&mut self) -> io::Result<()> { |
| 275 |
Ok(()) |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
#[cfg(test)] |
| 280 |
mod tests { |
| 281 |
use super::*; |
| 282 |
|
| 283 |
#[test] |
| 284 |
fn try_read_to_end() { |
| 285 |
let mut src = b"1234567890".take(5); |
| 286 |
let mut buf = TryVec::new(); |
| 287 |
src.try_read_to_end(&mut buf).unwrap(); |
| 288 |
assert_eq!(buf.len(), 5); |
| 289 |
assert_eq!(buf, b"12345".as_ref()); |
| 290 |
} |
| 291 |
|
| 292 |
#[test] |
| 293 |
fn read_into_try_vec() { |
| 294 |
let mut src = b"1234567890".take(5); |
| 295 |
let buf = src.read_into_try_vec().unwrap(); |
| 296 |
assert_eq!(buf.len(), 5); |
| 297 |
assert_eq!(buf, b"12345".as_ref()); |
| 298 |
} |
| 299 |
|
| 300 |
#[test] |
| 301 |
fn read_into_try_vec_oom() { |
| 302 |
let mut src = b"1234567890".take(core::usize::MAX.try_into().expect("usize < u64")); |
| 303 |
assert!(src.read_into_try_vec().is_err()); |
| 304 |
} |
| 305 |
|
| 306 |
#[test] |
| 307 |
fn try_read_up_to() { |
| 308 |
let src = b"1234567890"; |
| 309 |
let mut buf = TryVec::new(); |
| 310 |
super::try_read_up_to(&mut src.as_ref(), 5, &mut buf).unwrap(); |
| 311 |
assert_eq!(buf.len(), 5); |
| 312 |
assert_eq!(buf, b"12345".as_ref()); |
| 313 |
} |
| 314 |
|
| 315 |
#[test] |
| 316 |
fn try_read_up_to_oom() { |
| 317 |
let src = b"1234567890"; |
| 318 |
let mut buf = TryVec::new(); |
| 319 |
let limit = core::usize::MAX.try_into().expect("usize < u64"); |
| 320 |
let res = super::try_read_up_to(&mut src.as_ref(), limit, &mut buf); |
| 321 |
assert!(res.is_err()); |
| 322 |
} |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
impl<T: PartialEq> PartialEq<Vec<T>> for TryVec<T> { |
| 327 |
#[inline(always)] |
| 328 |
fn eq(&self, other: &Vec<T>) -> bool { |
| 329 |
self.inner.eq(other) |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
impl<'a, T: PartialEq> PartialEq<&'a [T]> for TryVec<T> { |
| 334 |
#[inline(always)] |
| 335 |
fn eq(&self, other: &&[T]) -> bool { |
| 336 |
self.inner.eq(other) |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
impl PartialEq<&str> for TryVec<u8> { |
| 341 |
#[inline] |
| 342 |
fn eq(&self, other: &&str) -> bool { |
| 343 |
self.as_slice() == other.as_bytes() |
| 344 |
} |
| 345 |
} |
| 346 |
|
| 347 |
impl core::convert::AsRef<[u8]> for TryVec<u8> { |
| 348 |
#[inline(always)] |
| 349 |
fn as_ref(&self) -> &[u8] { |
| 350 |
self.inner.as_ref() |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
impl<T> core::convert::From<Vec<T>> for TryVec<T> { |
| 355 |
#[inline(always)] |
| 356 |
fn from(value: Vec<T>) -> Self { |
| 357 |
Self { inner: value } |
| 358 |
} |
| 359 |
} |
| 360 |
|
| 361 |
impl<T: TryClone> core::convert::TryFrom<&[T]> for TryVec<T> { |
| 362 |
type Error = TryReserveError; |
| 363 |
|
| 364 |
#[inline] |
| 365 |
fn try_from(value: &[T]) -> Result<Self, Self::Error> { |
| 366 |
let mut v = Self::new(); |
| 367 |
v.inner.try_extend_from_slice_no_copy(value)?; |
| 368 |
Ok(v) |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
impl core::convert::TryFrom<&str> for TryVec<u8> { |
| 373 |
type Error = TryReserveError; |
| 374 |
|
| 375 |
#[inline] |
| 376 |
fn try_from(value: &str) -> Result<Self, Self::Error> { |
| 377 |
let mut v = Self::new(); |
| 378 |
v.extend_from_slice(value.as_bytes())?; |
| 379 |
Ok(v) |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
impl<T> core::ops::Deref for TryVec<T> { |
| 384 |
type Target = [T]; |
| 385 |
|
| 386 |
#[inline(always)] |
| 387 |
fn deref(&self) -> &[T] { |
| 388 |
self.inner.deref() |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
impl<T> core::ops::DerefMut for TryVec<T> { |
| 393 |
fn deref_mut(&mut self) -> &mut [T] { |
| 394 |
self.inner.deref_mut() |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
pub struct Iter<'a, T> { |
| 399 |
inner: alloc::slice::Iter<'a, T>, |
| 400 |
} |
| 401 |
|
| 402 |
impl<'a, T> Iterator for Iter<'a, T> { |
| 403 |
type Item = &'a T; |
| 404 |
|
| 405 |
#[inline(always)] |
| 406 |
fn next(&mut self) -> Option<Self::Item> { |
| 407 |
self.inner.next() |
| 408 |
} |
| 409 |
|
| 410 |
#[inline(always)] |
| 411 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 412 |
self.inner.size_hint() |
| 413 |
} |
| 414 |
} |
| 415 |
|
| 416 |
pub struct IterMut<'a, T> { |
| 417 |
inner: alloc::slice::IterMut<'a, T>, |
| 418 |
} |
| 419 |
|
| 420 |
impl<'a, T> Iterator for IterMut<'a, T> { |
| 421 |
type Item = &'a mut T; |
| 422 |
|
| 423 |
#[inline(always)] |
| 424 |
fn next(&mut self) -> Option<Self::Item> { |
| 425 |
self.inner.next() |
| 426 |
} |
| 427 |
|
| 428 |
#[inline(always)] |
| 429 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 430 |
self.inner.size_hint() |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
/// Grow capacity exponentially |
| 435 |
#[cold] |
| 436 |
fn vec_try_reserve_for_growth<T>(v: &mut Vec<T>, additional: usize) -> Result<(), TryReserveError> { |
| 437 |
// saturating, because can't use CapacityOverflow here if rust_1_57 flag is enabled |
| 438 |
FallibleVec::try_reserve(v, additional.max(v.capacity().saturating_mul(2) - v.len())) |
| 439 |
} |
| 440 |
|
| 441 |
fn needs_to_grow<T>(v: &Vec<T>, len: usize) -> bool { |
| 442 |
v.len().checked_add(len).map_or(true, |needed| needed > v.capacity()) |
| 443 |
} |
| 444 |
|
| 445 |
#[cfg(not(any(feature = "unstable", feature = "rust_1_57")))] |
| 446 |
fn vec_try_reserve<T>(v: &mut Vec<T>, additional: usize) -> Result<(), TryReserveError> { |
| 447 |
let available = v.capacity().checked_sub(v.len()).expect("capacity >= len"); |
| 448 |
if additional > available { |
| 449 |
let increase = additional |
| 450 |
.checked_sub(available) |
| 451 |
.expect("additional > available"); |
| 452 |
let new_cap = v |
| 453 |
.capacity() |
| 454 |
.checked_add(increase) |
| 455 |
.ok_or(TryReserveError::CapacityOverflow)?; |
| 456 |
vec_try_extend(v, new_cap)?; |
| 457 |
debug_assert!(v.capacity() == new_cap); |
| 458 |
} |
| 459 |
|
| 460 |
Ok(()) |
| 461 |
} |
| 462 |
|
| 463 |
#[cfg(not(any(feature = "unstable", feature = "rust_1_57")))] |
| 464 |
fn vec_try_extend<T>(v: &mut Vec<T>, new_cap: usize) -> Result<(), TryReserveError> { |
| 465 |
let old_len = v.len(); |
| 466 |
let old_cap: usize = v.capacity(); |
| 467 |
|
| 468 |
if old_cap >= new_cap { |
| 469 |
return Ok(()); |
| 470 |
} |
| 471 |
|
| 472 |
let elem_size = core::mem::size_of::<T>(); |
| 473 |
let new_alloc_size = new_cap |
| 474 |
.checked_mul(elem_size) |
| 475 |
.filter(|size| *size <= isize::MAX as usize) |
| 476 |
.ok_or(TryReserveError::CapacityOverflow)?; |
| 477 |
|
| 478 |
// required for alloc safety |
| 479 |
// See https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html#safety-1 |
| 480 |
// Should be unreachable given prior `old_cap >= new_cap` check. |
| 481 |
assert!(new_alloc_size > 0); |
| 482 |
|
| 483 |
let align = core::mem::align_of::<T>(); |
| 484 |
|
| 485 |
let (new_ptr, layout) = { |
| 486 |
if old_cap == 0 { |
| 487 |
let layout = Layout::from_size_align(new_alloc_size, align).expect("Invalid layout"); |
| 488 |
let new_ptr = unsafe { alloc(layout) }; |
| 489 |
(new_ptr, layout) |
| 490 |
} else { |
| 491 |
let old_alloc_size = old_cap |
| 492 |
.checked_mul(elem_size) |
| 493 |
.ok_or(TryReserveError::CapacityOverflow)?; |
| 494 |
let layout = Layout::from_size_align(old_alloc_size, align).expect("Invalid layout"); |
| 495 |
let new_ptr = unsafe { realloc(v.as_mut_ptr() as *mut u8, layout, new_alloc_size) }; |
| 496 |
(new_ptr, layout) |
| 497 |
} |
| 498 |
}; |
| 499 |
|
| 500 |
if new_ptr.is_null() { |
| 501 |
return Err(TryReserveError::AllocError { layout }); |
| 502 |
} |
| 503 |
|
| 504 |
let new_vec = unsafe { Vec::from_raw_parts(new_ptr.cast(), old_len, new_cap) }; |
| 505 |
|
| 506 |
core::mem::forget(core::mem::replace(v, new_vec)); |
| 507 |
Ok(()) |
| 508 |
} |
| 509 |
|
| 510 |
impl<T> FallibleVec<T> for Vec<T> { |
| 511 |
#[inline(always)] |
| 512 |
fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { |
| 513 |
#[cfg(all(feature = "unstable", not(feature = "rust_1_57")))] |
| 514 |
{ |
| 515 |
self.try_reserve(additional) |
| 516 |
} |
| 517 |
|
| 518 |
#[cfg(all(not(feature = "unstable"), not(feature = "rust_1_57")))] |
| 519 |
{ |
| 520 |
vec_try_reserve(self, additional) |
| 521 |
} |
| 522 |
|
| 523 |
#[cfg(feature = "rust_1_57")] |
| 524 |
{ |
| 525 |
// TryReserveError is an opaque type in 1.57 |
| 526 |
self.try_reserve(additional).map_err(|_| { |
| 527 |
crate::make_try_reserve_error(self.len(), additional, core::mem::size_of::<T>(), core::mem::align_of::<T>()) |
| 528 |
}) |
| 529 |
} |
| 530 |
} |
| 531 |
|
| 532 |
#[inline] |
| 533 |
fn try_push(&mut self, elem: T) -> Result<(), TryReserveError> { |
| 534 |
if self.len() == self.capacity() { |
| 535 |
vec_try_reserve_for_growth(self, 1)?; |
| 536 |
} |
| 537 |
Ok(self.push(elem)) |
| 538 |
} |
| 539 |
|
| 540 |
#[inline] |
| 541 |
fn try_push_give_back(&mut self, elem: T) -> Result<(), (T, TryReserveError)> { |
| 542 |
if self.len() == self.capacity() { |
| 543 |
if let Err(e) = vec_try_reserve_for_growth(self, 1) { |
| 544 |
return Err((elem, e)); |
| 545 |
} |
| 546 |
} |
| 547 |
Ok(self.push(elem)) |
| 548 |
} |
| 549 |
|
| 550 |
#[inline] |
| 551 |
fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> |
| 552 |
where |
| 553 |
Self: core::marker::Sized, |
| 554 |
{ |
| 555 |
let mut n = Self::new(); |
| 556 |
FallibleVec::try_reserve(&mut n, capacity)?; |
| 557 |
Ok(n) |
| 558 |
} |
| 559 |
|
| 560 |
#[inline] |
| 561 |
fn try_insert(&mut self, index: usize, element: T) -> Result<(), (T, TryReserveError)> { |
| 562 |
if self.len() == self.capacity() { |
| 563 |
if let Err(e) = vec_try_reserve_for_growth(self, 1) { |
| 564 |
return Err((element, e)); |
| 565 |
} |
| 566 |
} |
| 567 |
Ok(self.insert(index, element)) |
| 568 |
} |
| 569 |
#[inline] |
| 570 |
fn try_append(&mut self, other: &mut Self) -> Result<(), TryReserveError> { |
| 571 |
FallibleVec::try_reserve(self, other.len())?; |
| 572 |
Ok(self.append(other)) |
| 573 |
} |
| 574 |
fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> |
| 575 |
where |
| 576 |
T: Copy + Clone, |
| 577 |
{ |
| 578 |
let len = self.len(); |
| 579 |
if new_len > len { |
| 580 |
FallibleVec::try_reserve(self, new_len - len)?; |
| 581 |
} |
| 582 |
Ok(self.resize(new_len, value)) |
| 583 |
} |
| 584 |
fn try_resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), TryReserveError> |
| 585 |
where |
| 586 |
F: FnMut() -> T, |
| 587 |
{ |
| 588 |
let len = self.len(); |
| 589 |
if new_len > len { |
| 590 |
FallibleVec::try_reserve(self, new_len - len)?; |
| 591 |
} |
| 592 |
Ok(self.resize_with(new_len, f)) |
| 593 |
} |
| 594 |
fn try_resize_no_copy(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> |
| 595 |
where |
| 596 |
T: TryClone, |
| 597 |
{ |
| 598 |
let len = self.len(); |
| 599 |
|
| 600 |
if new_len > len { |
| 601 |
self.try_extend_with(new_len - len, TryExtendElement(value)) |
| 602 |
} else { |
| 603 |
Ok(self.truncate(new_len)) |
| 604 |
} |
| 605 |
} |
| 606 |
#[inline] |
| 607 |
fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> |
| 608 |
where |
| 609 |
T: Clone, |
| 610 |
{ |
| 611 |
if needs_to_grow(self, other.len()) { |
| 612 |
vec_try_reserve_for_growth(self, other.len())?; |
| 613 |
} |
| 614 |
Ok(self.extend_from_slice(other)) |
| 615 |
} |
| 616 |
fn try_extend_from_slice_no_copy(&mut self, other: &[T]) -> Result<(), TryReserveError> |
| 617 |
where |
| 618 |
T: TryClone, |
| 619 |
{ |
| 620 |
if needs_to_grow(self, other.len()) { |
| 621 |
vec_try_reserve_for_growth(self, other.len())?; |
| 622 |
} |
| 623 |
let mut len = self.len(); |
| 624 |
let mut iterator = other.iter(); |
| 625 |
while let Some(element) = iterator.next() { |
| 626 |
unsafe { |
| 627 |
core::ptr::write(self.as_mut_ptr().add(len), element.try_clone()?); |
| 628 |
// NB can't overflow since we would have had to alloc the address space |
| 629 |
len += 1; |
| 630 |
self.set_len(len); |
| 631 |
} |
| 632 |
} |
| 633 |
Ok(()) |
| 634 |
} |
| 635 |
} |
| 636 |
|
| 637 |
trait ExtendWith<T> { |
| 638 |
fn next(&mut self) -> Result<T, TryReserveError>; |
| 639 |
fn last(self) -> T; |
| 640 |
} |
| 641 |
|
| 642 |
struct TryExtendElement<T: TryClone>(T); |
| 643 |
impl<T: TryClone> ExtendWith<T> for TryExtendElement<T> { |
| 644 |
#[inline(always)] |
| 645 |
fn next(&mut self) -> Result<T, TryReserveError> { |
| 646 |
self.0.try_clone() |
| 647 |
} |
| 648 |
#[inline(always)] |
| 649 |
fn last(self) -> T { |
| 650 |
self.0 |
| 651 |
} |
| 652 |
} |
| 653 |
|
| 654 |
trait TryExtend<T> { |
| 655 |
fn try_extend_with<E: ExtendWith<T>>( |
| 656 |
&mut self, |
| 657 |
n: usize, |
| 658 |
value: E, |
| 659 |
) -> Result<(), TryReserveError>; |
| 660 |
} |
| 661 |
|
| 662 |
impl<T> TryExtend<T> for Vec<T> { |
| 663 |
/// Extend the vector by `n` values, using the given generator. |
| 664 |
fn try_extend_with<E: ExtendWith<T>>( |
| 665 |
&mut self, |
| 666 |
n: usize, |
| 667 |
mut value: E, |
| 668 |
) -> Result<(), TryReserveError> { |
| 669 |
if needs_to_grow(self, n) { |
| 670 |
vec_try_reserve_for_growth(self, n)?; |
| 671 |
} |
| 672 |
|
| 673 |
unsafe { |
| 674 |
let mut ptr = self.as_mut_ptr().add(self.len()); |
| 675 |
|
| 676 |
let mut local_len = self.len(); |
| 677 |
// Write all elements except the last one |
| 678 |
for _ in 1..n { |
| 679 |
core::ptr::write(ptr, value.next()?); |
| 680 |
ptr = ptr.offset(1); |
| 681 |
// Increment the length in every step in case next() panics |
| 682 |
local_len += 1; |
| 683 |
self.set_len(local_len); |
| 684 |
} |
| 685 |
|
| 686 |
if n > 0 { |
| 687 |
// We can write the last element directly without cloning needlessly |
| 688 |
core::ptr::write(ptr, value.last()); |
| 689 |
local_len += 1; |
| 690 |
self.set_len(local_len); |
| 691 |
} |
| 692 |
|
| 693 |
// len set by scope guard |
| 694 |
} |
| 695 |
Ok(()) |
| 696 |
} |
| 697 |
} |
| 698 |
|
| 699 |
trait Truncate { |
| 700 |
fn truncate(&mut self, len: usize); |
| 701 |
} |
| 702 |
|
| 703 |
impl<T> Truncate for Vec<T> { |
| 704 |
fn truncate(&mut self, len: usize) { |
| 705 |
let current_len = self.len(); |
| 706 |
unsafe { |
| 707 |
let mut ptr = self.as_mut_ptr().add(current_len); |
| 708 |
// Set the final length at the end, keeping in mind that |
| 709 |
// dropping an element might panic. Works around a missed |
| 710 |
// optimization, as seen in the following issue: |
| 711 |
// https://github.com/rust-lang/rust/issues/51802 |
| 712 |
let mut local_len = self.len(); |
| 713 |
|
| 714 |
// drop any extra elements |
| 715 |
for _ in len..current_len { |
| 716 |
ptr = ptr.offset(-1); |
| 717 |
core::ptr::drop_in_place(ptr); |
| 718 |
local_len -= 1; |
| 719 |
self.set_len(local_len); |
| 720 |
} |
| 721 |
} |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
/// try creating a vec from an `elem` cloned `n` times, see std::from_elem |
| 726 |
#[cfg(feature = "unstable")] |
| 727 |
pub fn try_from_elem<T: TryClone>(elem: T, n: usize) -> Result<Vec<T>, TryReserveError> { |
| 728 |
<T as SpecFromElem>::try_from_elem(elem, n) |
| 729 |
} |
| 730 |
|
| 731 |
// Specialization trait used for Vec::from_elem |
| 732 |
#[cfg(feature = "unstable")] |
| 733 |
trait SpecFromElem: Sized { |
| 734 |
fn try_from_elem(elem: Self, n: usize) -> Result<Vec<Self>, TryReserveError>; |
| 735 |
} |
| 736 |
|
| 737 |
#[cfg(feature = "unstable")] |
| 738 |
impl<T: TryClone> SpecFromElem for T { |
| 739 |
default fn try_from_elem(elem: Self, n: usize) -> Result<Vec<T>, TryReserveError> { |
| 740 |
let mut v = Vec::new(); |
| 741 |
v.try_resize_no_copy(n, elem)?; |
| 742 |
Ok(v) |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
#[cfg(feature = "unstable")] |
| 747 |
impl SpecFromElem for u8 { |
| 748 |
#[inline] |
| 749 |
fn try_from_elem(elem: u8, n: usize) -> Result<Vec<u8>, TryReserveError> { |
| 750 |
unsafe { |
| 751 |
let mut v: Vec<u8> = FallibleVec::try_with_capacity(n)?; |
| 752 |
core::ptr::write_bytes(v.as_mut_ptr(), elem, n); |
| 753 |
v.set_len(n); |
| 754 |
Ok(v) |
| 755 |
} |
| 756 |
} |
| 757 |
} |
| 758 |
|
| 759 |
impl<T: TryClone> TryClone for Vec<T> { |
| 760 |
#[inline] |
| 761 |
fn try_clone(&self) -> Result<Self, TryReserveError> |
| 762 |
where |
| 763 |
Self: core::marker::Sized, |
| 764 |
{ |
| 765 |
let mut v = Vec::new(); |
| 766 |
v.try_extend_from_slice_no_copy(self)?; |
| 767 |
Ok(v) |
| 768 |
} |
| 769 |
} |
| 770 |
|
| 771 |
pub trait TryFromIterator<I>: Sized { |
| 772 |
fn try_from_iterator<T: IntoIterator<Item = I>>(iterator: T) -> Result<Self, TryReserveError>; |
| 773 |
} |
| 774 |
|
| 775 |
impl<I> TryFromIterator<I> for Vec<I> { |
| 776 |
fn try_from_iterator<T: IntoIterator<Item = I>>(iterator: T) -> Result<Self, TryReserveError> |
| 777 |
where |
| 778 |
T: IntoIterator<Item = I>, |
| 779 |
{ |
| 780 |
let mut new = Self::new(); |
| 781 |
for i in iterator { |
| 782 |
new.try_push(i)?; |
| 783 |
} |
| 784 |
Ok(new) |
| 785 |
} |
| 786 |
} |
| 787 |
|
| 788 |
pub trait TryCollect<I> { |
| 789 |
fn try_collect<C: TryFromIterator<I>>(self) -> Result<C, TryReserveError>; |
| 790 |
} |
| 791 |
|
| 792 |
impl<I, T> TryCollect<I> for T |
| 793 |
where |
| 794 |
T: IntoIterator<Item = I>, |
| 795 |
{ |
| 796 |
#[inline(always)] |
| 797 |
fn try_collect<C: TryFromIterator<I>>(self) -> Result<C, TryReserveError> { |
| 798 |
C::try_from_iterator(self) |
| 799 |
} |
| 800 |
} |
| 801 |
|
| 802 |
#[cfg(test)] |
| 803 |
mod tests { |
| 804 |
use super::*; |
| 805 |
|
| 806 |
#[test] |
| 807 |
#[cfg(feature = "unstable")] |
| 808 |
fn vec() { |
| 809 |
// let v: Vec<u8> = from_elem(1, 10); |
| 810 |
let v: Vec<Vec<u8>> = try_vec![try_vec![42; 10].unwrap(); 100].unwrap(); |
| 811 |
println!("{:?}", v); |
| 812 |
let v2 = try_vec![0, 1, 2]; |
| 813 |
println!("{:?}", v2); |
| 814 |
assert_eq!(2 + 2, 4); |
| 815 |
} |
| 816 |
|
| 817 |
#[test] |
| 818 |
fn try_clone_vec() { |
| 819 |
// let v: Vec<u8> = from_elem(1, 10); |
| 820 |
let v = vec![42; 100]; |
| 821 |
assert_eq!(v.try_clone().unwrap(), v); |
| 822 |
} |
| 823 |
|
| 824 |
#[test] |
| 825 |
fn try_clone_oom() { |
| 826 |
let layout = Layout::new::<u8>(); |
| 827 |
let v = |
| 828 |
unsafe { Vec::<u8>::from_raw_parts(alloc(layout), core::isize::MAX as usize, core::isize::MAX as usize) }; |
| 829 |
assert!(v.try_clone().is_err()); |
| 830 |
} |
| 831 |
|
| 832 |
#[test] |
| 833 |
fn tryvec_try_clone_oom() { |
| 834 |
let layout = Layout::new::<u8>(); |
| 835 |
let inner = |
| 836 |
unsafe { Vec::<u8>::from_raw_parts(alloc(layout), core::isize::MAX as usize, core::isize::MAX as usize) }; |
| 837 |
let tv = TryVec { inner }; |
| 838 |
assert!(tv.try_clone().is_err()); |
| 839 |
} |
| 840 |
|
| 841 |
// #[test] |
| 842 |
// fn try_out_of_mem() { |
| 843 |
// let v = try_vec![42_u8; 1000000000]; |
| 844 |
// assert_eq!(v.try_clone().unwrap(), v); |
| 845 |
// } |
| 846 |
|
| 847 |
#[test] |
| 848 |
fn oom() { |
| 849 |
let mut vec: Vec<char> = Vec::new(); |
| 850 |
match FallibleVec::try_reserve(&mut vec, core::usize::MAX / std::mem::size_of::<char>()) { |
| 851 |
Ok(_) => panic!("it should be OOM"), |
| 852 |
_ => (), |
| 853 |
} |
| 854 |
match FallibleVec::try_reserve(&mut vec, core::usize::MAX) { |
| 855 |
Ok(_) => panic!("it should be OOM"), |
| 856 |
_ => (), |
| 857 |
} |
| 858 |
} |
| 859 |
|
| 860 |
#[test] |
| 861 |
fn tryvec_oom() { |
| 862 |
let mut vec: TryVec<char> = TryVec::new(); |
| 863 |
match vec.reserve(core::usize::MAX / std::mem::size_of::<char>()) { |
| 864 |
Ok(_) => panic!("it should be OOM"), |
| 865 |
_ => (), |
| 866 |
} |
| 867 |
match vec.reserve(core::usize::MAX) { |
| 868 |
Ok(_) => panic!("it should be OOM"), |
| 869 |
_ => (), |
| 870 |
} |
| 871 |
} |
| 872 |
|
| 873 |
#[test] |
| 874 |
fn try_reserve() { |
| 875 |
let mut vec: Vec<_> = vec![1]; |
| 876 |
let additional_room = vec.capacity() - vec.len(); |
| 877 |
let additional = additional_room + 1; |
| 878 |
let old_cap = vec.capacity(); |
| 879 |
FallibleVec::try_reserve(&mut vec, additional).unwrap(); |
| 880 |
assert!(vec.capacity() > old_cap); |
| 881 |
} |
| 882 |
|
| 883 |
#[test] |
| 884 |
fn tryvec_reserve() { |
| 885 |
let mut vec: TryVec<_> = vec![1].into(); |
| 886 |
let old_cap = vec.inner.capacity(); |
| 887 |
let new_cap = old_cap + 1; |
| 888 |
vec.reserve(new_cap).unwrap(); |
| 889 |
assert!(vec.inner.capacity() >= new_cap); |
| 890 |
} |
| 891 |
|
| 892 |
#[test] |
| 893 |
fn try_reserve_idempotent() { |
| 894 |
let mut vec: Vec<_> = vec![1]; |
| 895 |
let additional_room = vec.capacity() - vec.len(); |
| 896 |
let additional = additional_room + 1; |
| 897 |
FallibleVec::try_reserve(&mut vec, additional).unwrap(); |
| 898 |
let cap_after_reserve = vec.capacity(); |
| 899 |
FallibleVec::try_reserve(&mut vec, additional).unwrap(); |
| 900 |
assert_eq!(vec.capacity(), cap_after_reserve); |
| 901 |
} |
| 902 |
|
| 903 |
#[test] |
| 904 |
fn tryvec_reserve_idempotent() { |
| 905 |
let mut vec: TryVec<_> = vec![1].into(); |
| 906 |
let old_cap = vec.inner.capacity(); |
| 907 |
let new_cap = old_cap + 1; |
| 908 |
vec.reserve(new_cap).unwrap(); |
| 909 |
let cap_after_reserve = vec.inner.capacity(); |
| 910 |
vec.reserve(new_cap).unwrap(); |
| 911 |
assert_eq!(cap_after_reserve, vec.inner.capacity()); |
| 912 |
} |
| 913 |
|
| 914 |
#[test] |
| 915 |
fn capacity_overflow() { |
| 916 |
let mut vec: Vec<_> = vec![1]; |
| 917 |
match FallibleVec::try_reserve(&mut vec, core::usize::MAX) { |
| 918 |
Ok(_) => panic!("capacity calculation should overflow"), |
| 919 |
_ => (), |
| 920 |
} |
| 921 |
} |
| 922 |
|
| 923 |
#[test] |
| 924 |
fn tryvec_capacity_overflow() { |
| 925 |
let mut vec: TryVec<_> = vec![1].into(); |
| 926 |
match vec.reserve(core::usize::MAX) { |
| 927 |
Ok(_) => panic!("capacity calculation should overflow"), |
| 928 |
_ => (), |
| 929 |
} |
| 930 |
} |
| 931 |
|
| 932 |
#[test] |
| 933 |
fn extend_from_slice() { |
| 934 |
let mut vec: Vec<u8> = b"foo".as_ref().into(); |
| 935 |
vec.shrink_to_fit(); |
| 936 |
vec.reserve(5); |
| 937 |
assert_eq!(8, vec.capacity()); |
| 938 |
vec.try_extend_from_slice(b"bar").unwrap(); |
| 939 |
assert_eq!(vec, b"foobar".as_ref()); |
| 940 |
vec.try_extend_from_slice(b"1").unwrap(); |
| 941 |
assert_eq!(vec, b"foobar1".as_ref()); |
| 942 |
assert_eq!(8, vec.capacity()); |
| 943 |
vec.try_extend_from_slice(b"11").unwrap(); |
| 944 |
assert_eq!(16, vec.capacity()); |
| 945 |
} |
| 946 |
|
| 947 |
#[test] |
| 948 |
fn tryvec_extend_from_slice() { |
| 949 |
let mut vec: TryVec<u8> = b"foo".as_ref().try_into().unwrap(); |
| 950 |
vec.extend_from_slice(b"bar").unwrap(); |
| 951 |
assert_eq!(vec, b"foobar".as_ref()); |
| 952 |
} |
| 953 |
|
| 954 |
#[test] |
| 955 |
#[cfg(not(any(feature = "unstable", feature = "rust_1_57")))] |
| 956 |
fn try_extend_zst() { |
| 957 |
let mut vec: Vec<()> = Vec::new(); |
| 958 |
assert_eq!(vec.capacity(), core::usize::MAX); |
| 959 |
assert!(vec_try_extend(&mut vec, 10).is_ok()); |
| 960 |
assert!(vec_try_extend(&mut vec, core::usize::MAX).is_ok()); |
| 961 |
} |
| 962 |
|
| 963 |
#[test] |
| 964 |
fn try_reserve_zst() { |
| 965 |
let mut vec: Vec<()> = Vec::new(); |
| 966 |
assert!(FallibleVec::try_reserve(&mut vec, core::usize::MAX).is_ok()); |
| 967 |
} |
| 968 |
} |