const_sort/
lib.rs

1// Copyright 2018 Jeremy Rubin
2
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7fn prior_power_of_two(x: usize) -> usize {
8    ((x as u128).next_power_of_two() >> 1) as usize
9}
10
11// Algorithm From Knuth's Sorting and Searching 5.2.2M
12pub fn const_sort<T, F>(v: &mut [T], cmp: &F)
13where
14    F: Fn(&T, &T) -> subtle::Choice,
15    T: subtle::ConditionallySwappable,
16{
17    let t = prior_power_of_two(v.len());
18    let mut p = t;
19    while p > 0 {
20        let mut q = t;
21        let mut r = 0;
22        let mut d = p;
23        while d > 0 {
24            for i in 0..(v.len()-d) {
25                if (i & p) == r {
26                    let (f,l) = v.split_at_mut(1+i);
27                    compare_and_swap(&mut l[d-1], &mut f[i], cmp);
28                }
29            }
30            d = q -p;
31            q >>=1;
32            r = p;
33        }
34        p >>=1;
35    }
36}
37#[inline(always)]
38fn compare_and_swap<T, F>(v: &mut T, s: &mut T, cmp: &F)
39where
40    F: Fn(&T, &T) -> subtle::Choice,
41    T: subtle::ConditionallySwappable,
42{
43    let choice: subtle::Choice = cmp(&v, &s);
44    v.conditional_swap(s, choice);
45}
46
47
48#[cfg(test)]
49mod tests {
50    use rand::prelude::*;
51    #[test]
52    fn test_correct() {
53        for x in 0..=255usize {
54            let mut a = vec![0; x];
55            for val in a.iter_mut() {
56                *val = thread_rng().gen_range(0, 100);
57            }
58            crate::const_sort(&mut a, &|l, r| ((l < r) as u8).into());
59            let mut ans = a.clone();
60            ans.sort();
61            assert_eq!(ans, a);
62        }
63    }
64    #[test]
65    fn test_bitonic_u8_exhaustive() {
66        for x in 0..=7u8 {
67            let mut a = [1u8 & (x >> 0), 1u8 & (x >> 1), 1u8 & (x >> 2)];
68            crate::const_sort(&mut a, &|l, r| ((l < r) as u8).into());
69            let mut ans = a.clone();
70            ans.sort();
71            assert_eq!(ans, a);
72        }
73    }
74
75    // If this succeeds, we can probably sort correctly -- reason being,
76    // we are maximally testing that the network can handle weird sizes.
77    //
78    #[test]
79    fn test_bitonic_random_large_prime() {
80        for _ in 0..=255u8 {
81            let mut a = [0u8; 7919];
82            for i in 0..7919 {
83                a[i] = thread_rng().gen_range(0, 1);
84            }
85            crate::const_sort(&mut a, &|l, r| ((l < r) as u8).into());
86            let mut ans = a.clone();
87            ans.sort();
88            assert_eq!(ans[..], a[..]);
89        }
90    }
91}