From 04d59b77d88174fb50888a9ec0a9c9affc291ba8 Mon Sep 17 00:00:00 2001 From: missing Date: Sun, 14 Aug 2022 15:13:56 -0500 Subject: [PATCH] add test::stress_test --- Cargo.toml | 5 ++++- src/lib.rs | 8 ++++---- src/test.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 35e7150..db38f30 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,5 +7,8 @@ edition = "2021" [dependencies] +[dev-dependencies] +rand = "0.8.5" + [features] -unstable = [] \ No newline at end of file +unstable = [] diff --git a/src/lib.rs b/src/lib.rs index dd29ff8..edf66c5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -103,7 +103,7 @@ //! │ │ └──────────────────────────────────────────┘ │ │ //! │ └─────────────────────────────────────────────────────────┘ │ //! │ │ -//! └─ aligned to usize also aligned to usize ─┘ +//! └─ aligned to align_of::<*const T>() also aligned to *const T ─┘ //! ``` //! //! [`Vec`]: Vec @@ -142,7 +142,7 @@ use std::{ alloc::{alloc, dealloc, Layout}, any::Any, marker::PhantomData, - mem::{self, align_of_val, size_of, size_of_val}, + mem::{self, align_of, align_of_val, size_of, size_of_val}, ops::{Index, IndexMut}, ptr::{drop_in_place, NonNull}, slice, @@ -312,7 +312,7 @@ impl Vec { } unsafe fn realloc(&mut self, size: usize) { - let layout = Layout::from_size_align_unchecked(size, 8).pad_to_align(); + let layout = Layout::from_size_align_unchecked(size, align_of::>()).pad_to_align(); if self.capacity == 0 { // will panic if OOM self.ptr = NonNull::new(alloc(layout)).unwrap(); @@ -519,7 +519,7 @@ impl Vec { if self.capacity != 0 { dealloc( self.ptr.as_ptr(), - Layout::from_size_align_unchecked(self.capacity, 8), + Layout::from_size_align_unchecked(self.capacity, align_of::>()), ); } } diff --git a/src/test.rs b/src/test.rs index 4f1203a..528d731 100644 --- a/src/test.rs +++ b/src/test.rs @@ -1,5 +1,7 @@ //! Always use `cargo miri test`, and never just `cargo test`. +use rand::{thread_rng, Rng}; + use super::prelude::{vec, *}; use std::{ any::Any, @@ -211,3 +213,33 @@ fn remove() { assert_eq!(vec.remove(1).unwrap().debug(), "\"foo\""); assert_eq!(vec.debug(), "[1, true]"); } + +#[test] +fn stress_test() { + let mut vec: Vec = Vec::new(); + + let mut rng = thread_rng(); + + let mut len = 0; + + let iterations = if cfg!(miri) { 100_000 } else { 1_000_000 }; + + for _ in 0..iterations { + if len == 0 || rng.gen_bool(0.7) { + len += 1; + + match rng.gen_range(1..=3) { + 1 => vec.push_unsize_stable("a string", |v| v as _), + 2 => vec.push_unsize_stable(1, |v| v as _), + 3 => vec.push_unsize_stable(true, |v| v as _), + _ => unreachable!(), + } + } else { + len -= 1; + + vec.pop(); + } + + assert_eq!(len, vec.len()); + } +}