Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document that NotNan is repr(transparent). #158

Merged
merged 2 commits into from
Oct 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ fn canonicalize_signed_zero<T: FloatCore>(x: T) -> T {
/// s.insert(OrderedFloat(NAN));
/// assert!(s.contains(&OrderedFloat(NAN)));
/// ```
///
/// # Representation
///
/// `OrderedFloat` has `#[repr(transparent)]` and permits any value, so it is sound to use
/// [transmute](core::mem::transmute) or pointer casts to convert between any type `T` and
/// `OrderedFloat<T>`.
/// However, consider using [`bytemuck`] as a safe alternative if possible.
///
#[cfg_attr(
not(feature = "bytemuck"),
doc = "[`bytemuck`]: https://docs.rs/bytemuck/1/"
)]
#[derive(Default, Clone, Copy)]
#[repr(transparent)]
pub struct OrderedFloat<T>(pub T);
Expand Down Expand Up @@ -1157,6 +1169,18 @@ impl<T: FloatCore + Num> Num for OrderedFloat<T> {
/// // This will panic:
/// let c = a + b;
/// ```
///
/// # Representation
///
/// `NotNan` has `#[repr(transparent)]`, so it is sound to use
/// [transmute](core::mem::transmute) or pointer casts to convert between any type `T` and
/// `NotNan<T>`, as long as this does not create a NaN value.
/// However, consider using [`bytemuck`] as a safe alternative if possible.
///
#[cfg_attr(
not(feature = "bytemuck"),
doc = "[`bytemuck`]: https://docs.rs/bytemuck/1/"
)]
#[derive(PartialOrd, PartialEq, Default, Clone, Copy)]
#[repr(transparent)]
pub struct NotNan<T>(T);
Expand Down Expand Up @@ -2730,7 +2754,7 @@ mod impl_arbitrary {
#[cfg(feature = "bytemuck")]
mod impl_bytemuck {
use super::{FloatCore, NotNan, OrderedFloat};
use bytemuck::{AnyBitPattern, CheckedBitPattern, NoUninit, Pod, Zeroable};
use bytemuck::{AnyBitPattern, CheckedBitPattern, NoUninit, Pod, TransparentWrapper, Zeroable};

unsafe impl<T: Zeroable> Zeroable for OrderedFloat<T> {}

Expand All @@ -2752,6 +2776,10 @@ mod impl_bytemuck {
}
}

// OrderedFloat allows any value of the contained type, so it is a TransparentWrapper.
// NotNan does not, so it is not.
unsafe impl<T> TransparentWrapper<T> for OrderedFloat<T> {}

#[test]
fn test_not_nan_bit_pattern() {
use bytemuck::checked::{try_cast, CheckedCastError};
Expand Down
Loading