Skip to content

Commit e2c7a82

Browse files
authored
Merge pull request #158 from kpreid/transparent
Document that `NotNan` is `repr(transparent)`.
2 parents c8422ce + 7abdbc9 commit e2c7a82

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/lib.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,18 @@ fn canonicalize_signed_zero<T: FloatCore>(x: T) -> T {
7575
/// s.insert(OrderedFloat(NAN));
7676
/// assert!(s.contains(&OrderedFloat(NAN)));
7777
/// ```
78+
///
79+
/// # Representation
80+
///
81+
/// `OrderedFloat` has `#[repr(transparent)]` and permits any value, so it is sound to use
82+
/// [transmute](core::mem::transmute) or pointer casts to convert between any type `T` and
83+
/// `OrderedFloat<T>`.
84+
/// However, consider using [`bytemuck`] as a safe alternative if possible.
85+
///
86+
#[cfg_attr(
87+
not(feature = "bytemuck"),
88+
doc = "[`bytemuck`]: https://docs.rs/bytemuck/1/"
89+
)]
7890
#[derive(Default, Clone, Copy)]
7991
#[repr(transparent)]
8092
pub struct OrderedFloat<T>(pub T);
@@ -1157,6 +1169,18 @@ impl<T: FloatCore + Num> Num for OrderedFloat<T> {
11571169
/// // This will panic:
11581170
/// let c = a + b;
11591171
/// ```
1172+
///
1173+
/// # Representation
1174+
///
1175+
/// `NotNan` has `#[repr(transparent)]`, so it is sound to use
1176+
/// [transmute](core::mem::transmute) or pointer casts to convert between any type `T` and
1177+
/// `NotNan<T>`, as long as this does not create a NaN value.
1178+
/// However, consider using [`bytemuck`] as a safe alternative if possible.
1179+
///
1180+
#[cfg_attr(
1181+
not(feature = "bytemuck"),
1182+
doc = "[`bytemuck`]: https://docs.rs/bytemuck/1/"
1183+
)]
11601184
#[derive(PartialOrd, PartialEq, Default, Clone, Copy)]
11611185
#[repr(transparent)]
11621186
pub struct NotNan<T>(T);
@@ -2730,7 +2754,7 @@ mod impl_arbitrary {
27302754
#[cfg(feature = "bytemuck")]
27312755
mod impl_bytemuck {
27322756
use super::{FloatCore, NotNan, OrderedFloat};
2733-
use bytemuck::{AnyBitPattern, CheckedBitPattern, NoUninit, Pod, Zeroable};
2757+
use bytemuck::{AnyBitPattern, CheckedBitPattern, NoUninit, Pod, TransparentWrapper, Zeroable};
27342758

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

@@ -2752,6 +2776,10 @@ mod impl_bytemuck {
27522776
}
27532777
}
27542778

2779+
// OrderedFloat allows any value of the contained type, so it is a TransparentWrapper.
2780+
// NotNan does not, so it is not.
2781+
unsafe impl<T> TransparentWrapper<T> for OrderedFloat<T> {}
2782+
27552783
#[test]
27562784
fn test_not_nan_bit_pattern() {
27572785
use bytemuck::checked::{try_cast, CheckedCastError};

0 commit comments

Comments
 (0)