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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#![allow(missing_docs)] // due to FnNamed

use serde::{Deserialize, Serialize};
use serde_closure::{traits, FnNamed};
use std::{
	cmp::Ordering, fmt::{self, Debug}, iter, ops
};

FnNamed! {
	pub type NeverEqual<F, T> = |self, f: F|a=> &T, b=> &T| -> Ordering where ; where F: (for<'a> traits::Fn<(&'a T, &'a T), Output = Ordering>) {
		match (self.f).call((a, b)) {
			Ordering::Equal => Ordering::Less,
			ord => ord
		}
	}
}

/// This data structure tracks the `n` top values given a stream. It uses only `O(n)` space.
#[derive(Clone, Serialize, Deserialize)]
#[serde(bound(
	serialize = "T: Serialize, F: Serialize + for<'a> traits::Fn<(&'a T, &'a T), Output = Ordering>",
	deserialize = "T: Deserialize<'de>, F: Deserialize<'de> + for<'a> traits::Fn<(&'a T, &'a T), Output = Ordering>"
))]
pub struct Sort<T, F> {
	top: BTreeSet<T, NeverEqual<F, T>>,
	n: usize,
}
impl<T, F> Sort<T, F> {
	/// Create an empty `Sort` data structure with the specified `n` capacity.
	pub fn new(cmp: F, n: usize) -> Self {
		Self {
			top: BTreeSet::with_cmp(NeverEqual::new(cmp)),
			n,
		}
	}

	/// The `n` top elements we have capacity to track.
	pub fn capacity(&self) -> usize {
		self.n
	}

	/// The number of elements currently held.
	pub fn len(&self) -> usize {
		self.top.len()
	}

	/// If `.len() == 0`
	pub fn is_empty(&self) -> bool {
		self.top.is_empty()
	}

	/// Clears the `Sort` data structure, as if it was new.
	pub fn clear(&mut self) {
		self.top.clear();
	}

	/// An iterator visiting all elements in ascending order. The iterator element type is `&'_ T`.
	pub fn iter(&self) -> std::collections::btree_set::Iter<'_, T> {
		self.top.iter()
	}
}
#[cfg_attr(not(nightly), serde_closure::desugar)]
impl<T, F> Sort<T, F>
where
	F: traits::Fn(&T, &T) -> Ordering,
{
	/// "Visit" an element.
	pub fn push(&mut self, item: T) {
		let mut at_capacity = false;
		if self.top.len() < self.n || {
			at_capacity = true;
			!matches!(self.top.partial_cmp(&item), Some(Ordering::Less))
		} {
			let x = self.top.insert(item);
			assert!(x);
			if at_capacity {
				let _ = self.top.pop_last().unwrap();
			}
		}
	}
}
impl<T, F> IntoIterator for Sort<T, F> {
	type Item = T;
	type IntoIter = std::collections::btree_set::IntoIter<T>;

	fn into_iter(self) -> Self::IntoIter {
		self.top.into_iter()
	}
}
#[cfg_attr(not(nightly), serde_closure::desugar)]
impl<T, F> iter::Sum<Sort<T, F>> for Option<Sort<T, F>>
where
	F: traits::Fn(&T, &T) -> Ordering,
{
	fn sum<I>(mut iter: I) -> Self
	where
		I: Iterator<Item = Sort<T, F>>,
	{
		let mut total = iter.next()?;
		for sample in iter {
			total += sample;
		}
		Some(total)
	}
}
#[cfg_attr(not(nightly), serde_closure::desugar)]
impl<T, F> ops::Add for Sort<T, F>
where
	F: traits::Fn(&T, &T) -> Ordering,
{
	type Output = Self;

	fn add(mut self, other: Self) -> Self {
		self += other;
		self
	}
}
#[cfg_attr(not(nightly), serde_closure::desugar)]
impl<T, F> ops::AddAssign for Sort<T, F>
where
	F: traits::Fn(&T, &T) -> Ordering,
{
	fn add_assign(&mut self, other: Self) {
		assert_eq!(self.n, other.n);
		for t in other.top {
			self.push(t);
		}
	}
}
impl<T, F> Debug for Sort<T, F>
where
	T: Debug,
{
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.debug_list().entries(self.iter()).finish()
	}
}

use btree_set::BTreeSet;
mod btree_set {
	use serde::{Deserialize, Deserializer, Serialize, Serializer};
	use serde_closure::traits;
	use std::{
		borrow::Borrow, cmp::Ordering, collections::btree_set, marker::PhantomData, mem::{self, ManuallyDrop, MaybeUninit}
	};

	#[derive(Clone, Serialize, Deserialize)]
	#[serde(bound(
		serialize = "T: Serialize, F: Serialize + for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering>",
		deserialize = "T: Deserialize<'de>, F: Deserialize<'de> + for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering>"
	))]
	pub struct BTreeSet<T, F> {
		set: std::collections::BTreeSet<Node<T, F>>,
		cmp: F,
	}
	impl<T, F> BTreeSet<T, F> {
		// pub fn new() -> BTreeSet<T, Cmp> {
		//     Self::with_cmp(Cmp)
		// }
		pub fn with_cmp(cmp: F) -> Self {
			// Sound due to repr(transparent)
			let set = unsafe {
				mem::transmute::<
					btree_set::BTreeSet<TrivialOrd<Node<T, F>>>,
					btree_set::BTreeSet<Node<T, F>>,
				>(btree_set::BTreeSet::new())
			};
			Self { set, cmp }
		}
		pub fn cmp(&self) -> &F {
			&self.cmp
		}
		pub fn cmp_mut(&mut self) -> &mut F {
			&mut self.cmp
		}
		pub fn clear(&mut self) {
			self.trivial_ord_mut().clear();
		}
		pub fn iter(&self) -> btree_set::Iter<'_, T> {
			// Sound due to repr(transparent)
			unsafe { mem::transmute(self.set.iter()) }
		}
		pub fn len(&self) -> usize {
			self.set.len()
		}
		pub fn is_empty(&self) -> bool {
			self.set.is_empty()
		}
		pub fn pop_last(&mut self) -> Option<T> {
			#[cfg(nightly)]
			return self.trivial_ord_mut().pop_last().map(|value| value.0.t);
			#[cfg(not(nightly))]
			todo!();
		}
		fn trivial_ord_mut(&mut self) -> &mut std::collections::BTreeSet<TrivialOrd<Node<T, F>>> {
			let set: *mut std::collections::BTreeSet<Node<T, F>> = &mut self.set;
			let set: *mut std::collections::BTreeSet<TrivialOrd<Node<T, F>>> = set as _;
			// Sound due to repr(transparent)
			unsafe { &mut *set }
		}
	}
	impl<T, F> BTreeSet<T, F>
	where
		F: for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering>,
	{
		pub fn insert(&mut self, value: T) -> bool {
			self.set.insert(Node::new(value, &self.cmp))
		}
		pub fn remove(&mut self, value: &T) -> Option<T> {
			let value: *const T = value;
			let value: *const TrivialOrd<T> = value as _;
			let value = unsafe { &*value };
			self.set.take(value).map(|node| node.t)
		}
	}
	impl<T, F> IntoIterator for BTreeSet<T, F> {
		type Item = T;
		type IntoIter = btree_set::IntoIter<T>;

		fn into_iter(self) -> Self::IntoIter {
			// Sound due to repr(transparent)
			unsafe { mem::transmute(self.set.into_iter()) }
		}
	}
	#[cfg_attr(not(nightly), serde_closure::desugar)]
	impl<T, F> PartialEq<T> for BTreeSet<T, F>
	where
		F: traits::Fn(&T, &T) -> Ordering,
	{
		fn eq(&self, other: &T) -> bool {
			matches!(
				self.cmp.call((self.iter().next().unwrap(), other)),
				Ordering::Equal
			) && matches!(
				self.cmp.call((self.iter().last().unwrap(), other)),
				Ordering::Equal
			)
		}
	}
	#[cfg_attr(not(nightly), serde_closure::desugar)]
	impl<T, F> PartialOrd<T> for BTreeSet<T, F>
	where
		F: traits::Fn(&T, &T) -> Ordering,
	{
		fn partial_cmp(&self, other: &T) -> Option<Ordering> {
			match (
				self.cmp.call((self.iter().next().unwrap(), other)),
				self.cmp.call((self.iter().last().unwrap(), other)),
			) {
				(Ordering::Less, Ordering::Less) => Some(Ordering::Less),
				(Ordering::Equal, Ordering::Equal) => Some(Ordering::Equal),
				(Ordering::Greater, Ordering::Greater) => Some(Ordering::Greater),
				_ => None,
			}
		}
	}

	#[repr(transparent)]
	struct TrivialOrd<T: ?Sized>(T);
	impl<T: ?Sized> PartialEq for TrivialOrd<T> {
		fn eq(&self, _other: &Self) -> bool {
			unreachable!()
		}
	}
	impl<T: ?Sized> Eq for TrivialOrd<T> {}
	impl<T: ?Sized> PartialOrd for TrivialOrd<T> {
		fn partial_cmp(&self, _other: &Self) -> Option<Ordering> {
			unreachable!()
		}
	}
	impl<T: ?Sized> Ord for TrivialOrd<T> {
		fn cmp(&self, _other: &Self) -> Ordering {
			unreachable!()
		}
	}

	#[repr(transparent)]
	struct Node<T, F: ?Sized> {
		t: T,
		marker: PhantomData<fn() -> F>,
	}
	impl<T, F: ?Sized> Node<T, F> {
		fn new(t: T, f: &F) -> Self {
			if mem::size_of_val(f) != 0 {
				panic!("Closures with nonzero size not supported");
			}
			Self {
				t,
				marker: PhantomData,
			}
		}
	}
	impl<T, F: ?Sized> Borrow<T> for Node<T, F> {
		fn borrow(&self) -> &T {
			&self.t
		}
	}
	impl<T, F: ?Sized> Borrow<TrivialOrd<T>> for Node<T, F> {
		fn borrow(&self) -> &TrivialOrd<T> {
			let self_: *const T = &self.t;
			let self_: *const TrivialOrd<T> = self_ as _;
			unsafe { &*self_ }
		}
	}
	impl<T, F> PartialEq for Node<T, F>
	where
		F: for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering>,
	{
		fn eq(&self, other: &Self) -> bool {
			matches!(self.cmp(other), Ordering::Equal)
		}
	}
	impl<T, F> Eq for Node<T, F> where F: for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering> {}
	impl<T, F> PartialOrd for Node<T, F>
	where
		F: for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering>,
	{
		fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
			Some(self.cmp(other))
		}
	}
	impl<T, F> Ord for Node<T, F>
	where
		F: for<'a> traits::FnMut<(&'a T, &'a T), Output = Ordering>,
	{
		fn cmp(&self, other: &Self) -> Ordering {
			// This is safe as an F has already been materialized (so we know it isn't
			// uninhabited) and its size is zero. Related:
			// https://internals.rust-lang.org/t/is-synthesizing-zero-sized-values-safe/11506
			#[allow(clippy::uninit_assumed_init)]
			let mut cmp: ManuallyDrop<F> = unsafe { MaybeUninit::uninit().assume_init() };
			cmp.call_mut((&self.t, &other.t))
		}
	}

	impl<T, F: ?Sized> Clone for Node<T, F>
	where
		T: Clone,
	{
		fn clone(&self) -> Self {
			Self {
				t: self.t.clone(),
				marker: PhantomData,
			}
		}
	}
	impl<T, F: ?Sized> Serialize for Node<T, F>
	where
		T: Serialize,
	{
		fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
		where
			S: Serializer,
		{
			self.t.serialize(serializer)
		}
	}
	impl<'de, T, F: ?Sized> Deserialize<'de> for Node<T, F>
	where
		T: Deserialize<'de>,
	{
		fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
		where
			D: Deserializer<'de>,
		{
			T::deserialize(deserializer).map(|t| Self {
				t,
				marker: PhantomData,
			})
		}
	}
}