Commit Graph

29 Commits

Author SHA1 Message Date
zachs18
291a924518
Allow casting between slices of ZSTs and slices of non-ZSTs in all cases. (#256)
Casting ZST to non-ZST will result in a slice length of 0.
Casting non-ZST to ZST will only work if the input slice has length 0, and results in a slice length of 0; if the input slice is not of length 0, PodCastError::OutputSliceWouldHaveSlop is returned.

Updates the docs of the PodCastError variants to reflect when they can occur.
Updates the docs of try_cast_slice (and checked::) to remove note about ZST <-> non-ZST not being allowed.
Update bytes_of(_mut) to remove ZST check, since casting [ZST] -> [u8] is now allowed directly using cast_slice(_mut).
Update must_cast_slice checks and doctests to allow [ZST] -> [non-ZST], but disallow [non-ZST] -> [ZST].
2024-07-30 17:05:11 -06:00
zachs18
1c75146bb6
Fix UB when dropping BoxBytes owning a zero-sized layout (#258) 2024-07-30 16:23:38 -06:00
zachs18
005ee3254f
Fix panics in try_cast_slice_box etc (#254)
* Fix panics in try_cast_slice_{box,rc,arc},cast_vec.

Casting from non-empty non-ZST slices to ZST slices now returns Err(SizeMismatch) (instead of panicking).
Casting from empty non-ZST slices to ZST slices is allowed and returns an empty slice (instead of panicking).
Casting from ZST slices to non-ZST slices is allowed and returns an empty slice (status quo).

* Add tests for cast_slice_box,rc,arc.
2024-07-21 10:24:43 -06:00
Lokathor
5f4717633d clear up some warnings in tests. 2024-02-08 22:09:44 -07:00
Julien Cretin
fd27a5b018
Add from_box_bytes and box_bytes_of with BoxBytes type (#211)
* Add from_box_bytes and box_bytes_of with BoxBytes type

* Apply suggestions from code review

Co-authored-by: zachs18 <8355914+zachs18@users.noreply.github.com>

* Add into_raw_parts

* Add tests

* Rename from_parts to from_raw_parts

---------

Co-authored-by: zachs18 <8355914+zachs18@users.noreply.github.com>
2023-10-19 22:50:33 -06:00
Lokathor
16610417be tell clippy to quiet down 2023-09-05 13:26:08 -06:00
Lokathor
1b1b9a0e89
Fix 177 (#178)
* reduce required bounds.

* clippy get off my case

* spelling

* clippy lints on tests.
2023-02-28 13:29:34 -07:00
zachs18
1039388f0b
Fix soundness issue of TransparentWrapper derive macro. (#173)
Uses the compiler to check that all non-wrapped fields are actually 1-ZSTs,
and uses Zeroable to check that all non-wrapped fields are "conjurable".

Additionally, relaxes the bound of `PhantomData<T: Zeroable>: Zeroable` to all `T: ?Sized`.
2023-02-17 12:24:16 -07:00
Dirk Stolle
d1655f541b
Fix a few typos (#169) 2023-01-29 16:41:40 -07:00
zachs18
4c37652113
Implement CheckedBitPattern for core::num::NonZero*. (#151)
* Implement CheckedBitPattern for core::num::NonZero*.

* Add tests for CheckedBitPattern.

* Fix stacked borrows violation.

`<&mut T>::as_ptr` gives a `*const T` which is read-only. `<&mut T>::as_mut_ptr` is necessary to get a `*mut T`.

* MSRV fix.

* Add layout checks for CheckedBitPattern for NonZero*.

(Until Rust guarantees the layout of NonZero[int] matches [int].)
Also adds a test that will fail if any NonZero[int] has a different size or alignment than [int].
2022-11-30 12:09:17 -07:00
zachs18
c9e1ae1373
Remove where clause from derived TransparentWrapper impls. (#146)
* Remove where clause from derived TransparentWrapper impls.

* Add test for TransparentWrapper trait bound regression.
2022-11-20 16:40:20 -07:00
Christopher Serr
7311e9b4b8
Implement ByteEq and ByteHash derives (#144)
* Implement `ByteEq` and `ByteHash` derives

This adds the derives `ByteEq` and `ByteHash` that can be used as an
alternative to the `Eq` / `PartialEq` and `Hash` derives from the
standard library. The difference is that these variants use `bytemuck`
to convert their values to byte slices before comparing / hashing them.
This allows the comparisons to turn into a simple `memcmp` / `bcmp` (or
completely inlined as a few vector instructions) and allows hashers to
process all bytes at once, possibly allowing for some vector operations
as well.

Here's a quick comparison of the generated assembly:
![https://i.imgur.com/CGTSWTZ.png](https://i.imgur.com/CGTSWTZ.png)

* Address review comments
2022-11-17 13:13:24 -07:00
Christopher Serr
02021fba24
Conditionally compile in Arc (#140)
Apparently the latest release of `bytemuck` doesn't compile on some of
the targets that it used to because it uses `Arc`. `Arc` is not a type
that exists on every target, because not every targets supports atomics.
2022-11-05 07:00:40 -06:00
zachs18
09dd2ffd68
Add cast_{arc,rc} (and slice and try), and {wrap,peel}_{arc,rc}. (#132)
* Add `allocation::{try_,}cast_{arc,rc}`, and add `{wrap,peel}_{arc,rc}` to `TransparentWrapperAlloc`.

* Avoid intermediate slice reference in `try_cast_slice_{arc,rc}`.

* remove `unsafe` block; run `cargo +nightly fmt` (ignoring files I didn't modify)

* Make `cast_rc` (etc) have the same bounds as `cast_mut`, due to the existence of `Rc::get_mut_unchecked`.
2022-09-01 17:23:28 -06:00
Waffle Maybe
331762b014
run cargo fmt (#120) 2022-07-24 09:27:49 -06:00
Waffle Maybe
0fe2b2c568
Add {wrap,peel}_box functions to TransparentWrapperAlloc (#119)
* Add `{wrap,peel}_box` functions to `TransparentWrapperAlloc`

* Add tests for `{wrap,peel}_box`
2022-07-23 21:09:32 -06:00
Edward
abe55e525e
feat: add TransparentWrapperAlloc trait (#111)
* feat: add TransparentWrapperAlloc trait

* implements wrap_vec and peel_vec

* fix: review comments

* remote asserts as they don't do anything
* avoid issue with stacked borrows
2022-06-28 17:55:31 -06:00
Christopher Durham
1a4c11a675
Replace unsound usage of transmute_copy (#72)
* Use transmute! to enforce safer transmute_copy use

* Test fix for #71
2021-07-22 23:12:56 -06:00
Lokathor
99ecb1f6cb rename "unwrap" to "peel". 2021-06-10 14:05:15 -06:00
Connor Horman
cd8dbd64e9
Attach min_const_generics to a crate feature (#63)
* Attach min_const_generics to a crate feature

* Remove `min_const_generics` detection logic
2021-06-05 08:25:57 -06:00
Luis Wirth
30a96066fa
[Feature] extend TransparentWrapper conversion functions (#58)
* update rustfmt.toml

replace `merge_imports = true` (deprecated) with `imports_granularity = "Crate"`

* run `cargo +nightly fmt`

* rewrite docs and rename `Wrapped` to `Inner`

rewriting some docs for conciseness

rename `Wrapped` to `Inner`, because it's hard to visually differentiate between
`Wrapper` and `Wrapped`

* impl missing `TransparentWrapper::wrap_{}` fns

Implement 3 new wrapping functions on `TransparentWrapper` providing new
conversions.

- `TransparentWrapper::wrap(s: Inner) -> Self`
- `TransparentWrapper::wrap_slice(s: &[Inner]) -> &[Self]`
- `TransparentWrapper::wrap_slice_mut(s: &mut [Inner]) -> &mut [Self]`

* impl `TransparentWrapper::unwrap_{}` fns

Implement counterparts to `TransparentWrapper::wrap_{}` functions
providing reverse conversions.

- `TransparentWrapper::unwrap(self) -> Inner`
- `TransparentWrapper::unwrap_ref(&self) -> &Inner`
- `TransparentWrapper::unwrap_mut(&mut self) -> &mut Inner`
- `TransparentWrapper::unwrap_slice(s: &[Self]) -> &[Inner]`
- `TransparentWrapper::unwrap_slice_mut(s: &mut [Self]) -> &mut [Inner]`

* add `TransparentWrapper` UB test

This test is only for MIRI to check all trait functions on
`TransparentWrapper` if they cause any UB.
The output of the functions is not checked.

* small `TransparentWrapper` doc adjustments

* change fn signature on `TransparentWrapper`

Methods on `TransparentWrapper` trait are now associated functions.
They now take `Self` instead of `self` as argument)

- `TransparentWrapper::unwrap(s: Self)`
- `TransparentWrapper::unwrap_ref(s: &Self)`
- `TransparentWrapper::unwrap_mut(s: &mut Self)`
2021-03-28 23:11:13 -06:00
Marvin Löbel
92ce415317
Prevent try_zeroed_box<T>() from reserving size_of<T>() space on the stack. (#43)
* Add test

* Change try_zeroed_box implementation to not allocate space for T on the stack

* Add second test
2020-10-21 14:11:09 -06:00
Thom Chiovoloni
64cc5973c4
Add more tests, overhaul CI, and fix plug soundness hole in bytemuck::offset_of! (#38)
* Ensure functions that take generic <A, B> don't call them <T, U>

* Plug soundness hole in offset_of with safe_packed_borrows lint

* Add some more tests I noticed were missing (still many missing)

* Make CI way more thorough

* Fix running MSRV tests with unsupported `--feature`s

* Disable derive tests in sanitizers, and fix miri ci
2020-09-06 18:56:41 -06:00
Robin Appelman
cf944452b7
add basic derive macro for Pod, Zeroable and TransparentWrapper for structs (#30)
* add basic derive macro for Pod and Zeroable for structs

* add derive macro for TransparentWrapper

* use core::mem::size_of instead of std::mem::size_of in generated code

* cleanup error handling a bit

* remove unneeded iter logic

* remove unneeded clone and order impl

* fix generics

* fix doc typo

Co-authored-by: Lucien Greathouse <me@lpghatguy.com>

* remove unneeded lifetime anotation

* use unreachable for already rejected patch

Co-authored-by: Lucien Greathouse <me@lpghatguy.com>
2020-08-20 19:04:36 -06:00
Lokathor
c9a387a8da update offset_of to have 2-arg and 3-arg versions. 2020-07-23 20:21:09 -06:00
Thom Chiovoloni
e415a28966 Duplicate the doctests for the sake of miri 2020-01-11 08:01:58 -08:00
Lokathor
79143a6295 cargo fmt is a strict one 2019-11-03 23:55:51 -07:00
Lokathor
0e3948b8b8
Update cast_slice_tests.rs 2019-11-01 10:39:32 -06:00
Lokathor
b199fad411 Create cast_slice_tests.rs 2019-10-26 04:22:15 -06:00