1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//! This crate adds the `TotallyOrderable` trait for `f32` and `f64` values as well as the ABI-transparent `TotallyOrdered` type which adds `Ord + Eq + Hash` to wrapped floating point values.
//! Main use case: sorting of floating-point arrays which may or may not contain not-a-numbers, infinities, and positive or negative zeros.
//!
//! ```
//! use totally_ordered::TotallyOrdered;
//! let mut values : [f64; 4] = [-0.0, 0.0, -1.0, 1.0];
//! TotallyOrdered::new_slice_mut(&mut values).sort();
//! # assert_eq!(values[0], -1.0);
//! # assert_eq!(values[1].to_bits(), (-0.0f64).to_bits());
//! # assert_eq!(values[2].to_bits(), (0.0f64).to_bits());
//! # assert_eq!(values[3], 1.0);
//! ```

#![no_std]

use core::cmp::Ordering;
use core::hash::{Hash, Hasher};

/// Implement this for types that are not directly `Ord + Eq`, but
/// can be at a slightly higher runtime cost. Implemented for `f32`
/// and `f64`.
pub trait TotallyOrderable {
	/// A true equality comparison. Can be more expensive than standard
	/// `PartialEq`.
	fn total_eq(&self, other: &Self) -> bool;
	/// A totally ordered comparison. Can be more expensive than standard
	/// `PartialOrd`.
	fn total_cmp(&self, other: &Self) -> Ordering;
	/// A hashing function that matches `total_eq`. As the wrapped type
	/// doesn't implement `Eq`, it can't be `Hash` directly.
	fn total_hash<H: Hasher>(&self, state: &mut H);
}

macro_rules! implement_float_order {
	($F:ident, $U:ident, $I:ident, $N:literal) => {
		/// Implements the IEEE 754-2008 binary32/binary64 total ordering predicate.
		impl TotallyOrderable for $F {
			fn total_eq(&self, other: &Self) -> bool {
				self.to_bits() == other.to_bits()
			}

			fn total_cmp(&self, other: &Self) -> Ordering {
				let mut a = self.to_bits() as $I;
				let mut b = other.to_bits() as $I;
				a ^= (((a >> ($N - 1)) as $U) >> 1) as $I;
				b ^= (((b >> ($N - 1)) as $U) >> 1) as $I;
				a.cmp(&b)
			}

			fn total_hash<H: Hasher>(&self, state: &mut H) {
				self.to_bits().hash(state);
			}
		}
	};
}

implement_float_order!(f32, u32, i32, 32);
implement_float_order!(f64, u64, i64, 64);

/// An ABI-transparent newtype wrapper around types that
/// adds Ord + Eq to TotallyOrderable types (f32 and f64).
#[derive(Copy, Clone, Debug, Default)]
#[repr(transparent)]
pub struct TotallyOrdered<F: TotallyOrderable>(pub F);

impl<F: TotallyOrderable> TotallyOrdered<F> {
	/// Creates a wrapped value from an inner value
	pub fn new(v: F) -> Self {
		Self(v)
	}

	/// Creates a wrapped slice without copying data.
	/// Not implemented as `From<&[F]> for &[Self]` as
	/// slices are always foreign.
	///
	/// Follows the usual borrowing rules:
	/// ```compile_fail
	/// # use totally_ordered::*;
	/// let mut values = [1.0, 2.0, 3.0];
	/// let values_to = TotallyOrdered::new_slice(&values);
	/// values[2] = 4.0; // error, can't mutate while borrowed
	/// assert_eq!(values_to[2], TotallyOrdered::new(3.0));
	/// ```
	pub fn new_slice(s: &[F]) -> &[Self] {
		use core::slice::from_raw_parts;
		// TotallyOrdered is repr(transparent)
		unsafe { from_raw_parts(s.as_ptr() as *const _, s.len()) }
	}

	/// Creates a mutable wrapped slice without copying data.
	/// Not implemented as `From<&mut [F]> for &mut [Self]` as
	/// slices are always foreign.
	///
	/// Follows the usual borrowing rules:
	/// ```compile_fail
	/// # use totally_ordered::*;
	/// let mut values = [3.0, 2.0, 1.0];
	/// let values_to = TotallyOrdered::new_slice_mut(&mut values);
	/// assert_eq!(values[2], 1.0); // error, can't borrow while mutably borrowed
	/// values_to.sort();
	/// ```
	pub fn new_slice_mut(s: &mut [F]) -> &mut [Self] {
		use core::slice::from_raw_parts_mut;
		// TotallyOrdered is repr(transparent)
		unsafe { from_raw_parts_mut(s.as_ptr() as *mut _, s.len()) }
	}
}

impl<F: TotallyOrderable> PartialEq for TotallyOrdered<F> {
	fn eq(&self, other: &Self) -> bool {
		self.0.total_eq(&other.0)
	}
}

impl<F: TotallyOrderable> Eq for TotallyOrdered<F> {}

impl<F: TotallyOrderable> PartialOrd for TotallyOrdered<F> {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.0.total_cmp(&other.0))
	}
}

impl<F: TotallyOrderable> Ord for TotallyOrdered<F> {
	fn cmp(&self, other: &Self) -> Ordering {
		self.0.total_cmp(&other.0)
	}
}

impl<F: TotallyOrderable> Hash for TotallyOrdered<F> {
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.0.total_hash(state);
	}
}

impl<F: TotallyOrderable> From<F> for TotallyOrdered<F> {
	fn from(v: F) -> Self {
		Self(v)
	}
}

impl<'a, F: TotallyOrderable> From<&'a F> for &'a TotallyOrdered<F> {
	/// The explicit lifetime bound ensures that both From
	/// ```compile_fail
	/// # use totally_ordered::*;
	/// let mut value : f32 = 1.0;
	/// let value_to : &TotallyOrdered<_> = From::from(&value);
	/// value = 2.0; // error, can't mutate while borrowed
	/// assert_eq!(*value_to, TotallyOrdered::new(1.0));
	/// ```
	/// and Into
	/// ```compile_fail
	/// # use totally_ordered::*;
	/// let mut value : f32 = 1.0;
	/// let value_to : &TotallyOrdered<_> = (&value).into();
	/// value = 2.0; // error, can't mutate while borrowed
	/// assert_eq!(*value_to, TotallyOrdered::new(1.0));
	/// ```
	/// respect the lifetime of the borrow on the original value.
	fn from(v: &F) -> Self {
		// TotallyOrdered is repr(transparent)
		unsafe { &*(v as *const _ as *const _) }
	}
}

impl<'a, F: TotallyOrderable> From<&'a mut F> for &'a mut TotallyOrdered<F> {
	/// The explicit lifetime bound ensures that both From
	/// ```compile_fail
	/// # use totally_ordered::*;
	/// let mut value : f32 = 1.0;
	/// let value_to : &mut TotallyOrdered<_> = From::from(&mut value);
	/// assert_eq!(value, 1.0); // error, can't borrow while mutably borrowed
	/// *value_to = TotallyOrdered::new(2.0);
	/// ```
	/// and Into
	/// ```compile_fail
	/// # use totally_ordered::*;
	/// let mut value : f32 = 1.0;
	/// let value_to : &mut TotallyOrdered<_> = (&mut value).into();
	/// assert_eq!(value, 1.0); // error, can't borrow while mutably borrowed
	/// *value_to = TotallyOrdered::new(2.0);
	/// ```
	/// respect the lifetime of the mutable borrow on the original value.
	fn from(v: &mut F) -> Self {
		// TotallyOrdered is repr(transparent)
		unsafe { &mut *(v as *mut _ as *mut _) }
	}
}

#[cfg(test)]
mod test {
	#[test]
	fn test_total_order_f32() {
		use crate::TotallyOrdered;
		use core::f32;

		let mut values = [
			-0.0,
			0.0,
			-1.0,
			1.0,
			f32::NEG_INFINITY,
			f32::INFINITY,
			-f32::NAN,
			f32::NAN,
			-f32::MIN_POSITIVE,
			f32::MIN_POSITIVE,
			f32::MIN,
			f32::MAX,
		];

		TotallyOrdered::new_slice_mut(&mut values).sort();
		let values_total = TotallyOrdered::new_slice(&values);

		assert_eq!(values_total[0], (-f32::NAN).into());
		assert_eq!(values_total[1], f32::NEG_INFINITY.into());
		assert_eq!(values_total[2], f32::MIN.into());
		assert_eq!(values_total[3], (-1.0).into());
		assert_eq!(values_total[4], (-f32::MIN_POSITIVE).into());
		assert_eq!(values_total[5], (-0.0).into());
		assert_eq!(values_total[6], 0.0.into());
		assert_eq!(values_total[7], f32::MIN_POSITIVE.into());
		assert_eq!(values_total[8], 1.0.into());
		assert_eq!(values_total[9], f32::MAX.into());
		assert_eq!(values_total[10], f32::INFINITY.into());
		assert_eq!(values_total[11], f32::NAN.into());

		assert_ne!(
			TotallyOrdered::new(-f32::NAN),
			TotallyOrdered::new(f32::NAN)
		);
		assert_ne!(TotallyOrdered::new(-0.0f32), TotallyOrdered::new(0.0f32));
	}

	#[test]
	fn test_total_order_f64() {
		use crate::TotallyOrdered;
		use core::f64;

		let mut values = [
			-0.0,
			0.0,
			-1.0,
			1.0,
			f64::NEG_INFINITY,
			f64::INFINITY,
			-f64::NAN,
			f64::NAN,
			-f64::MIN_POSITIVE,
			f64::MIN_POSITIVE,
			f64::MIN,
			f64::MAX,
		];

		TotallyOrdered::new_slice_mut(&mut values).sort();
		let values_total = TotallyOrdered::new_slice(&values);

		assert_eq!(values_total[0], (-f64::NAN).into());
		assert_eq!(values_total[1], f64::NEG_INFINITY.into());
		assert_eq!(values_total[2], f64::MIN.into());
		assert_eq!(values_total[3], (-1.0).into());
		assert_eq!(values_total[4], (-f64::MIN_POSITIVE).into());
		assert_eq!(values_total[5], (-0.0).into());
		assert_eq!(values_total[6], 0.0.into());
		assert_eq!(values_total[7], f64::MIN_POSITIVE.into());
		assert_eq!(values_total[8], 1.0.into());
		assert_eq!(values_total[9], f64::MAX.into());
		assert_eq!(values_total[10], f64::INFINITY.into());
		assert_eq!(values_total[11], f64::NAN.into());

		assert_ne!(
			TotallyOrdered::new(-f64::NAN),
			TotallyOrdered::new(f64::NAN)
		);
		assert_ne!(TotallyOrdered::new(-0.0f64), TotallyOrdered::new(0.0f64));
	}
}