orderable-bytes 0.1.1

Canonical, order-preserving fixed-length byte encodings for plaintext types — feed into ORE or OPE schemes that compare encrypted values lexicographically
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Canonical, order-preserving fixed-length byte encodings for the
//! primitives `bool`, `char`, `u8`, `i8`, `i16`, `i32`, `i64`, `u128`,
//! `i128`, and the IEEE 754 floats `f32` and `f64`.
//!
//! Each impl emits the type's native byte width — no padding:
//!
//! - `bool`, `u8`, `i8` → `[u8; 1]`
//! - `i16`, `u16` → `[u8; 2]`
//! - `i32`, `u32`, `char`, `f32` → `[u8; 4]`
//! - `i64`, `u64`, `f64` → `[u8; 8]`
//! - `u128`, `i128` → `[u8; 16]`
//!
//! Consumers that need a fixed wider encoding (e.g. an ORE construction
//! whose plaintext block size is `[u8; 8]`) should zero-extend the
//! orderable bytes upstream of the encrypter; widening is monotonic on
//! lex order so it preserves the encoding's guarantees.
//!
//! ## `bool`
//!
//! Encoded as `false → 0x00`, `true → 0x01`. Already in lex order.
//!
//! ## Unsigned integers (`u8`, `u16`, `u32`, `u64`, `u128`)
//!
//! Already in lex order — no sign-flip needed. Native big-endian.
//!
//! ## Signed integers (`i8`, `i16`, `i32`, `i64`, `i128`)
//!
//! Each two's-complement input is mapped to its unsigned equivalent by
//! flipping the sign bit at its native width (`x ^ (1 << (N-1))`),
//! then serialised big-endian. Sign-flipping moves negatives below
//! positives (the sign bit `1` for negatives clears to `0`, vice versa
//! for positives) and preserves order within each sign class.
//!
//! ## `char`
//!
//! Encoded as the big-endian bytes of the underlying `u32` Unicode
//! scalar value (`*self as u32`). Rust's `Ord` impl for `char` compares
//! by code point, and surrogate code points (`U+D800`..=`U+DFFF`) are
//! not representable as `char`, so the native `u32` lex order is
//! exactly the order we need.
//!
//! ## IEEE 754 floats (`f32`, `f64`)
//!
//! Each float is mapped to a lex-orderable unsigned integer of the
//! same width (`u32` for `f32`, `u64` for `f64`) using the standard
//! monotonic encoding:
//!
//! - Negatives flip every bit (their bit pattern's lex order is the
//!   reverse of magnitude order, so flipping inverts it).
//! - Positives (and `+0.0`) flip only the sign bit (bringing them above
//!   negatives in lex order).
//!
//! `-0.0` is canonicalised to `+0.0` before encoding so the two compare
//! byte-equal — matching `-0.0 == 0.0` for IEEE 754.
//!
//! NaN handling is unspecified. Floats implement `PartialOrd` rather
//! than `Ord` (NaN compares unordered against every value, including
//! itself), so the trait's order/equality guarantees only apply to
//! non-NaN inputs. Different NaN bit patterns will produce different
//! bytes; consumers that need a canonical NaN must canonicalise
//! upstream.

use crate::ToOrderableBytes;

impl ToOrderableBytes for bool {
    const ENCODED_LEN: usize = 1;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        // `false as u8 == 0`, `true as u8 == 1`. `false` sorts strictly
        // below `true`.
        [*self as u8]
    }
}

impl ToOrderableBytes for u8 {
    const ENCODED_LEN: usize = 1;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        [*self]
    }
}

impl ToOrderableBytes for i8 {
    const ENCODED_LEN: usize = 1;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        [(*self as u8) ^ (1u8 << 7)]
    }
}

impl ToOrderableBytes for u16 {
    const ENCODED_LEN: usize = 2;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        self.to_be_bytes()
    }
}

impl ToOrderableBytes for i16 {
    const ENCODED_LEN: usize = 2;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        ((*self as u16) ^ (1u16 << 15)).to_be_bytes()
    }
}

impl ToOrderableBytes for u32 {
    const ENCODED_LEN: usize = 4;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        self.to_be_bytes()
    }
}

impl ToOrderableBytes for i32 {
    const ENCODED_LEN: usize = 4;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        ((*self as u32) ^ (1u32 << 31)).to_be_bytes()
    }
}

impl ToOrderableBytes for u64 {
    const ENCODED_LEN: usize = 8;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        self.to_be_bytes()
    }
}

impl ToOrderableBytes for i64 {
    const ENCODED_LEN: usize = 8;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        ((*self as u64) ^ (1u64 << 63)).to_be_bytes()
    }
}

impl ToOrderableBytes for u128 {
    const ENCODED_LEN: usize = 16;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        self.to_be_bytes()
    }
}

impl ToOrderableBytes for i128 {
    const ENCODED_LEN: usize = 16;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        ((*self as u128) ^ (1u128 << 127)).to_be_bytes()
    }
}

impl ToOrderableBytes for char {
    const ENCODED_LEN: usize = 4;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        (*self as u32).to_be_bytes()
    }
}

impl ToOrderableBytes for f32 {
    const ENCODED_LEN: usize = 4;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        // Canonicalise -0.0 → 0.0 so the two share one byte encoding
        // (their f32 equality demands byte equality under our contract).
        let value = if *self == -0.0 { 0.0 } else { *self };
        let bits = value.to_bits();
        // Branchless monotonic mapping (see `f64` impl for derivation).
        let sign_extension = (bits as i32 >> 31) as u32;
        let mask = sign_extension | (1u32 << 31);
        (bits ^ mask).to_be_bytes()
    }
}

impl ToOrderableBytes for f64 {
    const ENCODED_LEN: usize = 8;
    type Bytes = [u8; Self::ENCODED_LEN];

    fn to_orderable_bytes(&self) -> [u8; Self::ENCODED_LEN] {
        // Canonicalise -0.0 → 0.0 so the two share one byte encoding
        // (their f64 equality demands byte equality under our contract).
        let value = if *self == -0.0 { 0.0 } else { *self };
        let bits = value.to_bits();
        // Branchless monotonic mapping. `sign_extension` is `u64::MAX`
        // when the input is negative (sign bit `1`) and `0` when
        // positive. ORing in `1 << 63` makes the mask `u64::MAX` for
        // negatives (XOR-flip every bit) and `1 << 63` for positives
        // (XOR-flip just the sign bit).
        let sign_extension = (bits as i64 >> 63) as u64;
        let mask = sign_extension | (1u64 << 63);
        (bits ^ mask).to_be_bytes()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- bool ---

    #[test]
    fn bool_known_anchors() {
        assert_eq!(false.to_orderable_bytes(), [0x00]);
        assert_eq!(true.to_orderable_bytes(), [0x01]);
    }

    #[test]
    fn bool_byte_order_matches_natural_order() {
        assert!(false.to_orderable_bytes() < true.to_orderable_bytes());
    }

    // --- u8 ---

    #[test]
    fn u8_known_anchors() {
        // Native: u8 is already in lex order, no transform.
        assert_eq!(u8::MIN.to_orderable_bytes(), [0x00]);
        assert_eq!(0x42u8.to_orderable_bytes(), [0x42]);
        assert_eq!(u8::MAX.to_orderable_bytes(), [0xFF]);
    }

    #[test]
    fn u8_byte_order_matches_natural_order() {
        let ascending = [u8::MIN, 1, 100, 200, u8::MAX];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- i8 ---

    #[test]
    fn i8_known_anchors() {
        // Sign-flip at u8 (XOR 0x80) so MIN→0x00, 0→0x80, MAX→0xFF.
        assert_eq!(i8::MIN.to_orderable_bytes(), [0x00]);
        assert_eq!(0i8.to_orderable_bytes(), [0x80]);
        assert_eq!(i8::MAX.to_orderable_bytes(), [0xFF]);
    }

    #[test]
    fn i8_byte_order_matches_natural_order() {
        let ascending = [i8::MIN, -100, -1, 0, 1, 100, i8::MAX];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- u16 ---

    #[test]
    fn u16_known_anchors() {
        assert_eq!(u16::MIN.to_orderable_bytes(), [0x00, 0x00]);
        assert_eq!(u16::MAX.to_orderable_bytes(), [0xFF, 0xFF]);
        assert_eq!(0x1234u16.to_orderable_bytes(), [0x12, 0x34]);
    }

    #[test]
    fn u16_byte_order_matches_natural_order() {
        let ascending = [u16::MIN, 1, 256, 10000, u16::MAX - 1, u16::MAX];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- i16 ---

    #[test]
    fn i16_known_anchors() {
        // Sign-flip at u16 (XOR 0x8000), then BE.
        assert_eq!(i16::MIN.to_orderable_bytes(), [0x00, 0x00]);
        assert_eq!(0i16.to_orderable_bytes(), [0x80, 0x00]);
        assert_eq!(i16::MAX.to_orderable_bytes(), [0xFF, 0xFF]);
    }

    #[test]
    fn i16_byte_order_matches_natural_order() {
        let ascending = [i16::MIN, -10000, -1, 0, 1, 10000, i16::MAX];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- u32 ---

    #[test]
    fn u32_known_anchors() {
        assert_eq!(u32::MIN.to_orderable_bytes(), [0x00; 4]);
        assert_eq!(u32::MAX.to_orderable_bytes(), [0xFF; 4]);
        assert_eq!(
            0x1234_5678u32.to_orderable_bytes(),
            [0x12, 0x34, 0x56, 0x78]
        );
    }

    #[test]
    fn u32_byte_order_matches_natural_order() {
        let ascending = [
            u32::MIN,
            1,
            1 << 8,
            1 << 16,
            1 << 24,
            u32::MAX - 1,
            u32::MAX,
        ];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- i32 ---

    #[test]
    fn i32_known_anchors() {
        // Sign-flip at u32 (XOR 0x8000_0000), then BE.
        assert_eq!(i32::MIN.to_orderable_bytes(), [0x00, 0x00, 0x00, 0x00]);
        assert_eq!(0i32.to_orderable_bytes(), [0x80, 0x00, 0x00, 0x00]);
        assert_eq!(i32::MAX.to_orderable_bytes(), [0xFF, 0xFF, 0xFF, 0xFF]);
    }

    #[test]
    fn i32_byte_order_matches_natural_order() {
        let ascending = [i32::MIN, -1_000_000_000, -1, 0, 1, 1_000_000_000, i32::MAX];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- u64 ---

    #[test]
    fn u64_known_anchors() {
        assert_eq!(u64::MIN.to_orderable_bytes(), [0x00; 8]);
        assert_eq!(u64::MAX.to_orderable_bytes(), [0xFF; 8]);
        let one = 1u64.to_orderable_bytes();
        let mut expected_one = [0u8; 8];
        expected_one[7] = 1;
        assert_eq!(one, expected_one);
    }

    #[test]
    fn u64_byte_order_matches_natural_order() {
        let ascending = [
            u64::MIN,
            1,
            1 << 16,
            1 << 32,
            1 << 48,
            u64::MAX - 1,
            u64::MAX,
        ];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- i64 ---

    #[test]
    fn i64_known_anchors() {
        assert_eq!(i64::MIN.to_orderable_bytes(), [0x00; 8]);
        assert_eq!(
            0i64.to_orderable_bytes(),
            [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
        );
        assert_eq!(i64::MAX.to_orderable_bytes(), [0xFF; 8]);
    }

    #[test]
    fn i64_byte_order_matches_natural_order() {
        let ascending = [
            i64::MIN,
            -1_000_000_000_000,
            -1,
            0,
            1,
            1_000_000_000_000,
            i64::MAX,
        ];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- u128 ---

    #[test]
    fn u128_known_anchors() {
        assert_eq!(u128::MIN.to_orderable_bytes(), [0; 16]);
        assert_eq!(u128::MAX.to_orderable_bytes(), [0xFF; 16]);
        let one = 1u128.to_orderable_bytes();
        let mut expected_one = [0u8; 16];
        expected_one[15] = 1;
        assert_eq!(one, expected_one);
    }

    #[test]
    fn u128_byte_order_matches_natural_order() {
        let ascending = [
            u128::MIN,
            1,
            (1u128 << 32),
            (1u128 << 64),
            (1u128 << 96),
            u128::MAX - 1,
            u128::MAX,
        ];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- i128 ---

    #[test]
    fn i128_known_anchors() {
        assert_eq!(i128::MIN.to_orderable_bytes(), [0; 16]);
        assert_eq!(i128::MAX.to_orderable_bytes(), [0xFF; 16]);
        let mut expected_zero = [0u8; 16];
        expected_zero[0] = 0x80;
        assert_eq!(0i128.to_orderable_bytes(), expected_zero);
    }

    #[test]
    fn i128_byte_order_matches_natural_order() {
        let ascending = [
            i128::MIN,
            -(1i128 << 96),
            -(1i128 << 64),
            -1,
            0,
            1,
            (1i128 << 64),
            (1i128 << 96),
            i128::MAX,
        ];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{} < {} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- char ---

    #[test]
    fn char_known_anchors() {
        // 'A' = U+0041 = 0x0000_0041 BE.
        assert_eq!('A'.to_orderable_bytes(), [0x00, 0x00, 0x00, 0x41]);
        // '\0' = U+0000 (lowest code point).
        assert_eq!('\0'.to_orderable_bytes(), [0x00, 0x00, 0x00, 0x00]);
        // char::MAX = U+10FFFF (highest valid scalar value).
        assert_eq!(char::MAX.to_orderable_bytes(), [0x00, 0x10, 0xFF, 0xFF]);
    }

    #[test]
    fn char_byte_order_matches_natural_order() {
        // Spans ASCII, BMP, and supplementary planes (above the surrogate gap).
        let ascending = [
            '\0',
            '0',
            'A',
            'a',
            '\u{7F}',
            '\u{D7FF}',
            '\u{E000}',
            '\u{1F600}',
            char::MAX,
        ];
        for window in ascending.windows(2) {
            assert!(
                window[0].to_orderable_bytes() < window[1].to_orderable_bytes(),
                "{:?} < {:?} failed",
                window[0],
                window[1]
            );
        }
    }

    // --- f32 ---

    #[test]
    fn f32_zero_canonical_bytes() {
        // +0.0 → 0x8000_0000 (sign-bit-only flip on all-zero bits).
        assert_eq!(0.0f32.to_orderable_bytes(), [0x80, 0x00, 0x00, 0x00]);
    }

    #[test]
    fn f32_negative_zero_canonicalises_with_zero() {
        assert_eq!((-0.0f32).to_orderable_bytes(), 0.0f32.to_orderable_bytes());
    }

    #[test]
    fn f32_byte_order_matches_natural_order() {
        let ascending = [
            f32::NEG_INFINITY,
            f32::MIN,
            -1e30,
            -1.0,
            -f32::MIN_POSITIVE,
            0.0,
            f32::MIN_POSITIVE,
            1.0,
            1e30,
            f32::MAX,
            f32::INFINITY,
        ];
        for window in ascending.windows(2) {
            let a = window[0].to_orderable_bytes();
            let b = window[1].to_orderable_bytes();
            assert!(a < b, "{} < {} failed", window[0], window[1]);
        }
    }

    #[test]
    fn f32_subnormals_sort_above_zero_below_normals() {
        // Smallest positive subnormal (`f32::from_bits(1)`) must land
        // strictly between 0.0 and the smallest positive normal.
        let subnormal = f32::from_bits(1);
        assert!(0.0f32.to_orderable_bytes() < subnormal.to_orderable_bytes());
        assert!(subnormal.to_orderable_bytes() < f32::MIN_POSITIVE.to_orderable_bytes());
    }

    // --- f64 ---

    #[test]
    fn f64_zero_canonical_bytes() {
        // +0.0 → 0x8000_0000_0000_0000 (sign-bit-only flip on all-zero bits).
        assert_eq!(
            0.0f64.to_orderable_bytes(),
            [0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
        );
    }

    #[test]
    fn f64_negative_zero_canonicalises_with_zero() {
        assert_eq!((-0.0f64).to_orderable_bytes(), 0.0f64.to_orderable_bytes());
    }

    #[test]
    fn f64_byte_order_matches_natural_order() {
        let ascending = [
            f64::NEG_INFINITY,
            f64::MIN,
            -1e100,
            -1.0,
            -f64::MIN_POSITIVE,
            0.0,
            f64::MIN_POSITIVE,
            1.0,
            1e100,
            f64::MAX,
            f64::INFINITY,
        ];
        for window in ascending.windows(2) {
            let a = window[0].to_orderable_bytes();
            let b = window[1].to_orderable_bytes();
            assert!(a < b, "{} < {} failed", window[0], window[1]);
        }
    }

    #[test]
    fn f64_subnormals_sort_above_zero_below_normals() {
        // Smallest positive subnormal (`f64::from_bits(1)`) must land
        // strictly between 0.0 and the smallest positive normal.
        let subnormal = f64::from_bits(1);
        assert!(0.0f64.to_orderable_bytes() < subnormal.to_orderable_bytes());
        assert!(subnormal.to_orderable_bytes() < f64::MIN_POSITIVE.to_orderable_bytes());
    }
}