Skip to content

Commit 4b07101

Browse files
committed
Document that NotNan is repr(transparent).
Currently, rustdoc only displays `repr(transparent)` if the type’s fields are public, so there is no indication in the documentation that `NotNan` has `repr(transparent)`. Even if it was visible, there is not currently a strong consensus that such a repr may be assumed to be a stable part of the public API. Therefore, add paragraphs to `NotNan` and `OrderedFloat`’s documentation guaranteeing the repr. I also mentioned `bytemuck` so as to not be encouraging unsafe code, though the phrasing isn’t great.
1 parent c8422ce commit 4b07101

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/lib.rs

Lines changed: 24 additions & 0 deletions
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);

0 commit comments

Comments
 (0)