about summary refs log tree commit diff
path: root/library/alloc/tests
AgeCommit message (Collapse)AuthorLines
2022-09-29Stabilize `nonnull_slice_from_raw_parts`Yuki Okushi-2/+1
2022-09-28Rollup merge of #102232 - Urgau:stabilize-bench_black_box, r=TaKO8KiYuki Okushi-1/+0
Stabilize bench_black_box This PR stabilize `feature(bench_black_box)`. ```rust pub fn black_box<T>(dummy: T) -> T; ``` The FCP was completed in https://github.com/rust-lang/rust/issues/64102. `@rustbot` label +T-libs-api -T-libs
2022-09-27Stabilize bench_black_boxUrgau-1/+0
2022-09-23Stabilize const `BTree{Map,Set}::new`Nilstrieb-1/+1
Since `len` and `is_empty` are not const stable yet, this also creates a new feature for them since they previously used the same `const_btree_new` feature.
2022-09-10Update testGiacomo Stevanato-33/+34
2022-09-10Adapt inplace collection leak test to check for no leaksGiacomo Stevanato-16/+20
2022-08-31fix into_iter on ZSTRalf Jung-0/+6
2022-08-30Rollup merge of #95376 - WaffleLapkin:drain_keep_rest, r=dtolnayDylan DPC-0/+60
Add `vec::Drain{,Filter}::keep_rest` This PR adds `keep_rest` methods to `vec::Drain` and `vec::DrainFilter` under `drain_keep_rest` feature gate: ```rust // mod alloc::vec impl<T, A: Allocator> Drain<'_, T, A> { pub fn keep_rest(self); } impl<T, F, A: Allocator> DrainFilter<'_, T, F, A> where F: FnMut(&mut T) -> bool, { pub fn keep_rest(self); } ``` Both these methods cancel draining of elements that were not yet yielded from the iterators. While this needs more testing & documentation, I want at least start the discussion. This may be a potential way out of the "should `DrainFilter` exhaust itself on drop?" argument.
2022-08-22Rollup merge of #100820 - WaffleLapkin:use_ptr_is_aligned_methods, r=scottmcmDylan DPC-4/+5
Use pointer `is_aligned*` methods This PR replaces some manual alignment checks with calls to `pointer::{is_aligned, is_aligned_to}` and removes a useless pointer cast. r? `@scottmcm` _split off from #100746_
2022-08-22Rollup merge of #99386 - AngelicosPhosphoros:add_retain_test_maybeuninit, ↵Dylan DPC-0/+45
r=JohnTitor Add tests that check `Vec::retain` predicate execution order. This behaviour is documented for `Vec::retain` which means that there is code that rely on that but there weren't tests about that.
2022-08-21Make use of `pointer::is_aligned[_to]`Maybe Waffle-4/+5
2022-08-21Replace most uses of `pointer::offset` with `add` and `sub`Maybe Waffle-5/+5
2022-07-27Auto merge of #98553 - the8472:next_chunk_opt, r=Mark-Simulacrumbors-0/+11
Optimized vec::IntoIter::next_chunk impl ``` x86_64v1, default test vec::bench_next_chunk ... bench: 696 ns/iter (+/- 22) x86_64v1, pr test vec::bench_next_chunk ... bench: 309 ns/iter (+/- 4) znver2, default test vec::bench_next_chunk ... bench: 17,272 ns/iter (+/- 117) znver2, pr test vec::bench_next_chunk ... bench: 211 ns/iter (+/- 3) ``` On znver2 the default impl seems to be slow due to different inlining decisions. It goes through `core::array::iter_next_chunk` which has a deep call tree.
2022-07-26add test for vec::IntoIter::next_chunk() implThe 8472-0/+11
an adaption of the default impl's doctest
2022-07-17Add tests that check `Vec::retain` predicate execution order.AngelicosPhosphoros-0/+45
2022-07-15Stabilize `core::ffi::CStr`, `alloc::ffi::CString`, and friendsJosh Triplett-1/+0
Stabilize the `core_c_str` and `alloc_c_string` feature gates. Change `std::ffi` to re-export these types rather than creating type aliases, since they now have matching stability.
2022-07-14Rollup merge of #98315 - joshtriplett:stabilize-core-ffi-c, r=Mark-SimulacrumDylan DPC-1/+0
Stabilize `core::ffi:c_*` and rexport in `std::ffi` This only stabilizes the base types, not the non-zero variants, since those have their own separate tracking issue and have not gone through FCP to stabilize.
2022-07-13Stabilize `core::ffi:c_*` and rexport in `std::ffi`Josh Triplett-1/+0
This only stabilizes the base types, not the non-zero variants, since those have their own separate tracking issue and have not gone through FCP to stabilize.
2022-07-10Auto merge of #95295 - CAD97:layout-isize, r=scottmcmbors-311/+142
Enforce that layout size fits in isize in Layout As it turns out, enforcing this _in APIs that already enforce `usize` overflow_ is fairly trivial. `Layout::from_size_align_unchecked` continues to "allow" sizes which (when rounded up) would overflow `isize`, but these are now declared as library UB for `Layout`, meaning that consumers of `Layout` no longer have to check this before making an allocation. (Note that this is "immediate library UB;" IOW it is valid for a future release to make this immediate "language UB," and there is an extant patch to do so, to allow Miri to catch this misuse.) See also #95252, [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Layout.20Isn't.20Enforcing.20The.20isize.3A.3AMAX.20Rule). Fixes https://github.com/rust-lang/rust/issues/95334 Some relevant quotes: `@eddyb,` https://github.com/rust-lang/rust/pull/95252#issuecomment-1078513769 > [B]ecause of the non-trivial presence of both of these among code published on e.g. crates.io: > > 1. **`Layout` "producers" / `GlobalAlloc` "users"**: smart pointers (including `alloc::rc` copies with small tweaks), collections, etc. > 2. **`Layout` "consumers" / `GlobalAlloc` "providers"**: perhaps fewer of these, but anything built on top of OS APIs like `mmap` will expose `> isize::MAX` allocations (on 32-bit hosts) if they lack extra checks > > IMO the only responsible option is to enforce the `isize::MAX` limit in `Layout`, which: > > * makes `Layout` _sound_ in terms of only ever allowing allocations where `(alloc_base_ptr: *mut u8).offset(size)` is never UB > * frees both "producers" and "consumers" of `Layout` from manually reimplementing the checks > * manual checks can be risky, e.g. if the final size passed to the allocator isn't the one being checked > * this applies retroactively, fixing the overall soundness of existing code with zero transition period or _any_ changes required from users (as long as going through `Layout` is mandatory, making a "choke point") > > > Feel free to quote this comment onto any relevant issue, I might not be able to keep track of developments. `@Gankra,` https://github.com/rust-lang/rust/pull/95252#issuecomment-1078556371 > As someone who spent way too much time optimizing libcollections checks for this stuff and tried to splatter docs about it everywhere on the belief that it was a reasonable thing for people to manually take care of: I concede the point, it is not reasonable. I am wholy spiritually defeated by the fact that _liballoc_ of all places is getting this stuff wrong. This isn't throwing shade at the folks who implemented these Rc features, but rather a statement of how impractical it is to expect anyone out in the wider ecosystem to enforce them if _some of the most audited rust code in the library that defines the very notion of allocating memory_ can't even reliably do it. > > We need the nuclear option of Layout enforcing this rule. Code that breaks this rule is _deeply_ broken and any "regressions" from changing Layout's contract is a _correctness_ fix. Anyone who disagrees and is sufficiently motivated can go around our backs but the standard library should 100% refuse to enable them. cc also `@RalfJung` `@rust-lang/wg-allocators.` Even though this technically supersedes #95252, those potential failure points should almost certainly still get nicer panics than just "unwrap failed" (which they would get by this PR). It might additionally be worth recommending to users of the `Layout` API that they should ideally use `.and_then`/`?` to complete the entire layout calculation, and then `panic!` from a single location at the end of `Layout` manipulation, to reduce the overhead of the checks and optimizations preserving the exact location of each `panic` which are conceptually just one failure: allocation too big. Probably deserves a T-lang and/or T-libs-api FCP (this technically solidifies the [objects must be no larger than `isize::MAX`](https://rust-lang.github.io/unsafe-code-guidelines/layout/scalars.html#isize-and-usize) rule further, and the UCG document says this hasn't been RFCd) and a crater run. Ideally, no code exists that will start failing with this addition; if it does, it was _likely_ (but not certainly) causing UB. Changes the raw_vec allocation path, thus deserves a perf run as well. I suggest hiding whitespace-only changes in the diff view.
2022-07-01Rollup merge of #98585 - cuviper:covariant-thinbox, r=thomccDylan DPC-0/+7
Make `ThinBox<T>` covariant in `T` Just like `Box<T>`, we want `ThinBox<T>` to be covariant in `T`, but the projection in `WithHeader<<T as Pointee>::Metadata>` was making it invariant. This is now hidden as `WithOpaqueHeader`, which we type-cast whenever the real `WithHeader<H>` type is needed. Fixes the problem noted in <https://github.com/rust-lang/rust/issues/92791#issuecomment-1104636249>.
2022-06-27Make `ThinBox<T>` covariant in `T`Josh Stone-0/+7
Just like `Box<T>`, we want `ThinBox<T>` to be covariant in `T`, but the projection in `WithHeader<<T as Pointee>::Metadata>` was making it invariant. This is now hidden as `WithOpaqueHeader`, which we type-cast whenever the real `WithHeader<H>` type is needed.
2022-06-27liballoc tests: avoid int2ptr castRalf Jung-1/+1
2022-06-19Fix documentation for with_capacity and reserve families of methodsjmaargh-0/+9
Documentation for the following methods with_capacity with_capacity_in with_capacity_and_hasher reserve reserve_exact try_reserve try_reserve_exact was inconsistent and often not entirely correct where they existed on the following types Vec VecDeque String OsString PathBuf BinaryHeap HashSet HashMap BufWriter LineWriter since the allocator is allowed to allocate more than the requested capacity in all such cases, and will frequently "allocate" much more in the case of zero-sized types (I also checked BufReader, but there the docs appear to be accurate as it appears to actually allocate the exact capacity). Some effort was made to make the documentation more consistent between types as well. Fix with_capacity* methods for Vec Fix *reserve* methods for Vec Fix docs for *reserve* methods of VecDeque Fix docs for String::with_capacity Fix docs for *reserve* methods of String Fix docs for OsString::with_capacity Fix docs for *reserve* methods on OsString Fix docs for with_capacity* methods on HashSet Fix docs for *reserve methods of HashSet Fix docs for with_capacity* methods of HashMap Fix docs for *reserve methods on HashMap Fix expect messages about OOM in doctests Fix docs for BinaryHeap::with_capacity Fix docs for *reserve* methods of BinaryHeap Fix typos Fix docs for with_capacity on BufWriter and LineWriter Fix consistent use of `hasher` between `HashMap` and `HashSet` Fix warning in doc test Add test for capacity of vec with ZST Fix doc test error
2022-06-08Stabilize `const_intrinsic_copy`Yuki Okushi-1/+0
2022-06-05Add vec::Drain{,Filter}::keep_restMaybe Waffle-0/+60
These methods allow to cancel draining of unyielded elements.
2022-06-04Rollup merge of #96642 - thomcc:thinbox-zst-ugh, r=yaahcDylan DPC-0/+232
Avoid zero-sized allocs in ThinBox if T and H are both ZSTs. This was surprisingly tricky, and took longer to get right than expected. `ThinBox` is a surprisingly subtle piece of code. That said, in the end, a lot of this was due to overthinking[^overthink] -- ultimately the fix ended up fairly clean and simple. [^overthink]: Honestly, for a while I was convinced this couldn't be done without allocations or runtime branches in these cases, but that's obviously untrue. Anyway, as a result of spending all that time debugging, I've extended the tests quite a bit, and also added more debug assertions. Many of these helped for subtle bugs I made in the middle (for example, the alloc/drop tracking is because I ended up double-dropping the value in the case where both were ZSTs), they're arguably a bit of overkill at this point, although I imagine they could help in the future too. Anyway, these tests cover a wide range of size/align cases, nd fully pass under miri[^1]. They also do some smoke-check asserting that the value has the correct alignment, although in practice it's totally within the compiler's rights to delete these assertions since we'd have already done UB if they get hit. They have more boilerplate than they really need, but it's not *too* bad on a per-test basis. A notable absence from testing is atypical header types, but at the moment it's impossible to manually implement `Pointee`. It would be really nice to have testing here, since it's not 100% obvious to me that the aligned read/write we use for `H` are correct in the face of arbitrary combinations of `size_of::<H>()`, `align_of::<H>()`, and `align_of::<T>()`. (That said, I spent a while thinking through it and am *pretty* sure it's fine -- I'd just feel... better if we could test some cases for non-ZST headers which have unequal and align). [^1]: Or at least, they pass under miri if I copy the code and tests into a new crate and run miri on it (after making it less stdlibified). Fixes #96485. I'd request review ``@yaahc,`` but I believe you're taking some time away from reviews, so I'll request from the previous PR's reviewer (I think that the context helps, even if the actual change didn't end up being bad here). r? ``@joshtriplett``
2022-05-29Use Box::new() instead of box syntax in alloc testsest31-12/+12
2022-05-27Avoid zero-sized allocs in ThinBox if T and H are both ZSTs.Thom Chiovoloni-0/+232
2022-05-26improve case conversion happy pathConrad Ludgate-0/+14
2022-05-02Rollup merge of #94126 - ssomers:alloc_prep_1, r=Mark-SimulacrumYuki Okushi-1173/+0
Classify BinaryHeap & LinkedList unit tests as such All but one of these so-called integration test case are unit tests, just like btree's were (#75531). In addition, reunite the unit tests of linked_list that were split off during #23104 because they needed to remain unit tests (they were later moved to the separate file they are in during #63207). The two sets could remain separate files, but I opted to merge them back together, more or less in the order they used to be, apart from one duplicate name `test_split_off` and one duplicate tiny function `list_from`.
2022-04-27Remove use of reverted std::ffi::c_charJosh Triplett-1/+2
2022-04-14library: Use type aliases to make `CStr(ing)` in libcore/liballoc unstableVadim Petrochenkov-0/+1
2022-04-14library: Move `CStr` to libcore, and `CString` to liballocVadim Petrochenkov-0/+20
2022-04-11impl const Default for Box<[T]> and Box<str>Josh Stone-0/+6
2022-04-10thin_box test: import from std, not allocRalf Jung-1/+1
2022-04-08Add ThinBox type for 1 stack pointer sized heap allocated trait objectsJane Lusby-0/+28
Relevant commit messages from squashed history in order: Add initial version of ThinBox update test to actually capture failure swap to middle ptr impl based on matthieu-m's design Fix stack overflow in debug impl The previous version would take a `&ThinBox<T>` and deref it once, which resulted in a no-op and the same type, which it would then print causing an endless recursion. I've switched to calling `deref` by name to let method resolution handle deref the correct number of times. I've also updated the Drop impl for good measure since it seemed like it could be falling prey to the same bug, and I'll be adding some tests to verify that the drop is happening correctly. add test to verify drop is behaving add doc examples and remove unnecessary Pointee bounds ThinBox: use NonNull ThinBox: tests for size Apply suggestions from code review Co-authored-by: Alphyr <47725341+a1phyr@users.noreply.github.com> use handle_alloc_error and fix drop signature update niche and size tests add cfg for allocating APIs check null before calculating offset add test for zst and trial usage prevent optimizer induced ub in drop and cleanup metadata gathering account for arbitrary size and alignment metadata Thank you nika and thomcc! Update library/alloc/src/boxed/thin.rs Co-authored-by: Josh Triplett <josh@joshtriplett.org> Update library/alloc/src/boxed/thin.rs Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2022-04-08add `<[[T; N]]>::flatten`, `<[[T; N]]>::flatten_mut`, and `Vec::<[T; ↵Cyborus04-0/+8
N]>::into_flattened`
2022-03-31make utf8_char_counts test faster in MiriRalf Jung-4/+7
2022-03-31Rollup merge of #95298 - ↵Dylan DPC-0/+28
jhorstmann:fix-double-drop-of-allocator-in-vec-into-iter, r=oli-obk Fix double drop of allocator in IntoIter impl of Vec Fixes #95269 The `drop` impl of `IntoIter` reconstructs a `RawVec` from `buf`, `cap` and `alloc`, when that `RawVec` is dropped it also drops the allocator. To avoid dropping the allocator twice we wrap it in `ManuallyDrop` in the `InttoIter` struct. Note this is my first contribution to the standard library, so I might be missing some details or a better way to solve this.
2022-03-27Debug print char 0 as '\0' rather than '\u{0}'David Tolnay-2/+2
2022-03-25Add another assertion without into_iterJörn Horstmann-2/+6
2022-03-25Add a test verifying the number of drop callsJörn Horstmann-0/+24
2022-03-25Adjust tests for isize::MAX allocation always being checkedCAD97-311/+142
2022-03-11Classify BinaryHeap & LinkedList unit tests as suchStein Somers-1173/+0
2022-03-10Rollup merge of #93950 - T-O-R-U-S:use-modern-formatting-for-format!-macros, ↵Dylan DPC-32/+32
r=Mark-Simulacrum Use modern formatting for format! macros This updates the standard library's documentation to use the new format_args syntax. The documentation is worthwhile to update as it should be more idiomatic (particularly for features like this, which are nice for users to get acquainted with). The general codebase is likely more hassle than benefit to update: it'll hurt git blame, and generally updates can be done by folks updating the code if (and when) that makes things more readable with the new format. A few places in the compiler and library code are updated (mostly just due to already having been done when this commit was first authored). `eprintln!("{}", e)` becomes `eprintln!("{e}")`, but `eprintln!("{}", e.kind())` remains untouched.
2022-03-10Use implicit capture syntax in format_argsT-O-R-U-S-32/+32
This updates the standard library's documentation to use the new syntax. The documentation is worthwhile to update as it should be more idiomatic (particularly for features like this, which are nice for users to get acquainted with). The general codebase is likely more hassle than benefit to update: it'll hurt git blame, and generally updates can be done by folks updating the code if (and when) that makes things more readable with the new format. A few places in the compiler and library code are updated (mostly just due to already having been done when this commit was first authored).
2022-03-10Revert accidental stabilizationOli Scherer-1/+1
2022-02-13stabilize const_ptr_offsetSaltyKitkat-1/+0
2022-02-07Add {floor,ceil}_char_boundary methods to strltdk-0/+93
2022-02-05Ensure non-power-of-two sizes are tested in the Chars::count testThom Chiovoloni-2/+4