universal_radix_sort 1.0.0

A high-performance, generic Radix Sort implementation for Rust supporting integers, floats, and strings
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
635
636
637
638
//! String Radix Sort implementation.
//!
//! This module provides MSD (Most Significant Digit) first radix sorting
//! for strings with proper lexicographical ordering.
//!
//! # Overview
//!
//! String sorting requires special handling due to variable-length data.
//! This implementation supports both:
//! - **MSB-first**: Optimal for lexicographical ordering with early termination
//! - **LSB-first**: Fallback for compatibility with fixed-width processing
//!
//! # Performance Considerations
//!
//! - Uses UTF-8 byte extraction (256 radix) instead of UTF-16 (65536 radix)
//! - Avoids excessive memory allocation with adaptive counting
//! - Handles empty strings and variable lengths correctly
//!
//! # Examples
//!
//! ```rust
//! use universal_radix_sort::{RadixSort, RadixDataType, SortDirection};
//!
//! let mut strings = vec!["banana".to_string(), "apple".to_string(), "cherry".to_string()];
//! let sorter = RadixSort::<String>::new(RadixDataType::String, SortDirection::Ascending);
//! sorter.sort(&mut strings).unwrap();
//! assert_eq!(strings, vec!["apple", "banana", "cherry"]);
//! ```

use crate::{ProcessingOrder, RadixDataType, RadixError, RadixResult, RadixSort, RadixSortable};

impl<T> RadixSort<T>
where
    T: RadixSortable,
{
    /// Generic string sorting that works with [`RadixSortable`] trait.
    ///
    /// This method uses the trait's string methods to properly handle
    /// variable-length strings.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice of strings to sort
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, `Err(RadixError)` if sorting fails.
    ///
    /// # Errors
    ///
    /// Returns `UnsupportedOperation` if the type is not `String` or `&str`.
    pub(crate) fn sort_strings_generic(&self, slice: &mut [T]) -> RadixResult<()> {
        if slice.len() <= 1 {
            return Ok(());
        }

        // Verify we're sorting strings by data type
        if T::data_type() != RadixDataType::String {
            return Err(RadixError::unsupported_operation(
                "sort_strings_generic requires RadixDataType::String",
            ));
        }

        // FIX: Use trait method that now exists in RadixSortable
        let max_len = slice.iter().map(|s| T::string_length(s)).max().unwrap_or(0);

        if max_len == 0 {
            return Ok(());
        }

        // Use MSD-first for strings (lexicographical order)
        if self.processing_order == ProcessingOrder::MsbFirst {
            self.msd_radix_sort_generic(slice, 0, max_len)
        } else {
            // Fallback to LSB-first with padding
            self.lsb_radix_sort_generic(slice, max_len)
        }
    }

    /// MSD (Most Significant Digit) first radix sort for generic string types.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `start` - Start index of the current segment
    /// * `max_len` - Maximum string length in the collection
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, `Err(RadixError)` if sorting fails.
    fn msd_radix_sort_generic(
        &self,
        slice: &mut [T],
        start: usize,
        max_len: usize,
    ) -> RadixResult<()> {
        self.msd_radix_sort_recursive(slice, start, slice.len(), 0, max_len)
    }

    /// Recursive MSD radix sort implementation.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `start` - Start index of current segment
    /// * `end` - End index of current segment
    /// * `char_index` - Current character position being processed
    /// * `max_len` - Maximum string length
    ///
    /// # Returns
    ///
    /// `Ok(())` on success
    fn msd_radix_sort_recursive(
        &self,
        slice: &mut [T],
        start: usize,
        end: usize,
        char_index: usize,
        max_len: usize,
    ) -> RadixResult<()> {
        if start >= end.saturating_sub(1) || char_index >= max_len {
            return Ok(());
        }

        const RADIX: usize = 256; // UTF-8 bytes
        let mut count = [0usize; RADIX + 1]; // +1 for strings shorter than char_index

        // Count occurrences
        for i in start..end {
            // FIX: Use trait method that now exists
            let byte = T::string_byte_at(&slice[i], char_index) as usize;
            count[byte + 1] += 1;
        }

        // Prefix sum
        for i in 1..count.len() {
            count[i] += count[i - 1];
        }

        // Create output buffer
        let mut output: Vec<T> = Vec::with_capacity(end - start);
        // Initialize with clones from input
        for i in start..end {
            output.push(slice[i].clone());
        }

        // Distribute to output
        let count_copy = count;
        for i in start..end {
            let byte = T::string_byte_at(&slice[i], char_index) as usize;
            let pos = count_copy[byte];
            output[pos - count_copy[0]] = slice[i].clone();
            count[byte] += 1;
        }

        // Copy back
        for (i, item) in output.into_iter().enumerate() {
            slice[start + i] = item;
        }

        // Recursively sort each bucket
        let mut prev_end = start;
        for i in 0..RADIX + 1 {
            let bucket_end = start + count[i] - count[0];
            if bucket_end > prev_end + 1 {
                self.msd_radix_sort_recursive(
                    slice,
                    prev_end,
                    bucket_end,
                    char_index + 1,
                    max_len,
                )?;
            }
            prev_end = bucket_end;
        }

        Ok(())
    }

    /// LSB (Least Significant Byte) first radix sort for generic string types.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `max_len` - Maximum string length
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, `Err(RadixError)` if sorting fails.
    fn lsb_radix_sort_generic(&self, slice: &mut [T], max_len: usize) -> RadixResult<()> {
        let mut buffer: Vec<T> = Vec::with_capacity(slice.len());
        // Initialize with clones from input
        for item in slice.iter() {
            buffer.push(item.clone());
        }

        // Sort from last character to first
        for char_index in (0..max_len).rev() {
            self.counting_sort_strings_by_char_generic(slice, &mut buffer, char_index);
            slice.swap_with_slice(&mut buffer);
        }

        Ok(())
    }

    /// Counting sort for strings by a specific character position.
    ///
    /// # Arguments
    ///
    /// * `input` - The input slice to sort
    /// * `output` - The output buffer
    /// * `char_index` - The character position to sort by
    fn counting_sort_strings_by_char_generic(
        &self,
        input: &mut [T],
        output: &mut [T],
        char_index: usize,
    ) {
        const RADIX: usize = 256;
        let mut count = [0usize; RADIX + 1];
        let len = input.len();

        // Count
        for item in input.iter() {
            // FIX: Use trait method that now exists
            let byte = T::string_byte_at(item, char_index) as usize;
            count[byte + 1] += 1;
        }

        // Prefix sum
        for i in 1..count.len() {
            count[i] += count[i - 1];
        }

        // Build output (stable)
        for i in 0..len {
            let byte = T::string_byte_at(&input[i], char_index) as usize;
            output[count[byte]] = input[i].clone();
            count[byte] += 1;
        }
    }
}

// Specialized implementation for String type
impl RadixSort<String> {
    /// MSD (Most Significant Digit) first radix sort for [`String`].
    ///
    /// This is more efficient for strings as it allows early termination when
    /// differences are found in higher-order characters.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice of Strings to sort
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, `Err(RadixError)` if sorting fails.
    pub fn sort_strings_msd(&self, slice: &mut [String]) -> RadixResult<()> {
        if slice.len() <= 1 {
            return Ok(());
        }

        // Find maximum string length for MSD sorting
        let max_len = slice.iter().map(|s| s.len()).max().unwrap_or(0);
        if max_len == 0 {
            return Ok(());
        }

        // Use MSD-first for strings (lexicographical order)
        if self.processing_order == ProcessingOrder::MsbFirst {
            self.msd_radix_sort_strings(slice, 0, slice.len(), 0, max_len)?;
        } else {
            // Fallback to LSB-first with padding
            self.lsb_radix_sort_strings_impl(slice, max_len)?;
        }

        Ok(())
    }

    /// MSD radix sort implementation for [`String`] slice.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `start` - Start index of the current segment
    /// * `end` - End index of the current segment
    /// * `char_index` - Current character position being processed
    /// * `max_len` - Maximum string length in the collection
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, `Err(RadixError)` if sorting fails.
    fn msd_radix_sort_strings(
        &self,
        slice: &mut [String],
        start: usize,
        end: usize,
        char_index: usize,
        max_len: usize,
    ) -> RadixResult<()> {
        if start >= end.saturating_sub(1) || char_index >= max_len {
            return Ok(());
        }

        const RADIX: usize = 256; // UTF-8 bytes
        let mut count = [0usize; RADIX + 1]; // +1 for strings shorter than char_index

        // Count occurrences
        for i in start..end {
            let byte = slice[i].as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            count[byte + 1] += 1;
        }

        // Prefix sum
        for i in 1..count.len() {
            count[i] += count[i - 1];
        }

        // Create output buffer
        let mut output: Vec<String> = Vec::with_capacity(end - start);
        for _ in 0..(end - start) {
            output.push(String::new());
        }

        // Distribute to output
        let count_copy = count;
        for i in start..end {
            let byte = slice[i].as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            let pos = count_copy[byte];
            output[pos - count_copy[0]] = slice[i].clone();
            count[byte] += 1;
        }

        // Copy back
        for (i, item) in output.into_iter().enumerate() {
            slice[start + i] = item;
        }

        // Recursively sort each bucket
        let mut prev_end = start;
        for i in 0..RADIX + 1 {
            let bucket_end = start + count[i] - count[0];
            if bucket_end > prev_end + 1 {
                self.msd_radix_sort_strings(slice, prev_end, bucket_end, char_index + 1, max_len)?;
            }
            prev_end = bucket_end;
        }

        Ok(())
    }

    /// LSB radix sort implementation for [`String`] slice.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `max_len` - Maximum string length
    ///
    /// # Returns
    ///
    /// `Ok(())` on success.
    fn lsb_radix_sort_strings_impl(&self, slice: &mut [String], max_len: usize) -> RadixResult<()> {
        let mut buffer: Vec<String> = vec![String::new(); slice.len()];

        for char_index in (0..max_len).rev() {
            self.counting_sort_strings_by_char_impl(slice, &mut buffer, char_index);
            slice.swap_with_slice(&mut buffer);
        }

        Ok(())
    }

    /// Counting sort for strings by a specific character position.
    ///
    /// # Arguments
    ///
    /// * `input` - The input slice to sort
    /// * `output` - The output buffer
    /// * `char_index` - The character position to sort by
    fn counting_sort_strings_by_char_impl(
        &self,
        input: &mut [String],
        output: &mut [String],
        char_index: usize,
    ) {
        const RADIX: usize = 256;
        let mut count = [0usize; RADIX + 1];
        let len = input.len();

        // Count
        for item in input.iter() {
            let byte = item.as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            count[byte + 1] += 1;
        }

        // Prefix sum
        for i in 1..count.len() {
            count[i] += count[i - 1];
        }

        // Build output (stable)
        for i in 0..len {
            let byte = input[i].as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            output[count[byte]] = input[i].clone();
            count[byte] += 1;
        }
    }
}

// Specialized implementation for &str type
impl RadixSort<&str> {
    /// MSD radix sort for `&str` slice.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    ///
    /// # Returns
    ///
    /// `Ok(())` on success.
    pub fn sort_str_slice_msd(&self, slice: &mut [&str]) -> RadixResult<()> {
        if slice.len() <= 1 {
            return Ok(());
        }

        let max_len = slice.iter().map(|s| s.len()).max().unwrap_or(0);
        if max_len == 0 {
            return Ok(());
        }

        if self.processing_order == ProcessingOrder::MsbFirst {
            self.msd_radix_sort_str_slice(slice, 0, slice.len(), 0, max_len)?;
        } else {
            self.lsb_radix_sort_str_slice_impl(slice, max_len)?;
        }

        Ok(())
    }

    /// MSD radix sort implementation for `&str` slice.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `start` - Start index
    /// * `end` - End index
    /// * `char_index` - Current character position
    /// * `max_len` - Maximum string length
    ///
    /// # Returns
    ///
    /// `Ok(())` on success.
    fn msd_radix_sort_str_slice(
        &self,
        slice: &mut [&str],
        start: usize,
        end: usize,
        char_index: usize,
        max_len: usize,
    ) -> RadixResult<()> {
        if start >= end.saturating_sub(1) || char_index >= max_len {
            return Ok(());
        }

        const RADIX: usize = 256;
        let mut count = [0usize; RADIX + 1];

        // Count
        for i in start..end {
            let byte = slice[i].as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            count[byte + 1] += 1;
        }

        // Prefix sum
        for i in 1..count.len() {
            count[i] += count[i - 1];
        }

        // Output buffer - FIX: Use Vec with proper initialization
        let mut output: Vec<&str> = Vec::with_capacity(end - start);
        for i in start..end {
            output.push(slice[i]);
        }

        // Distribute
        let count_copy = count;
        for i in start..end {
            let byte = slice[i].as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            let pos = count_copy[byte];
            output[pos - count_copy[0]] = slice[i];
            count[byte] += 1;
        }

        // Copy back
        for (i, item) in output.into_iter().enumerate() {
            slice[start + i] = item;
        }

        // Recursive sort
        let mut prev_end = start;
        for i in 0..RADIX + 1 {
            let bucket_end = start + count[i] - count[0];
            if bucket_end > prev_end + 1 {
                self.msd_radix_sort_str_slice(
                    slice,
                    prev_end,
                    bucket_end,
                    char_index + 1,
                    max_len,
                )?;
            }
            prev_end = bucket_end;
        }

        Ok(())
    }

    /// LSB radix sort for `&str` slice.
    ///
    /// # Arguments
    ///
    /// * `slice` - The mutable slice to sort
    /// * `max_len` - Maximum string length
    ///
    /// # Returns
    ///
    /// `Ok(())` on success.
    fn lsb_radix_sort_str_slice_impl(&self, slice: &mut [&str], max_len: usize) -> RadixResult<()> {
        let mut buffer: Vec<&str> = Vec::with_capacity(slice.len());
        for &s in slice.iter() {
            buffer.push(s);
        }

        for char_index in (0..max_len).rev() {
            self.counting_sort_str_by_char_impl(slice, &mut buffer, char_index);
            slice.swap_with_slice(&mut buffer);
        }

        Ok(())
    }

    /// Counting sort for `&str` by character position.
    ///
    /// # Arguments
    ///
    /// * `input` - The input slice to sort
    /// * `char_index` - The character position to sort by
    fn counting_sort_str_by_char_impl<'a>(
        &self,
        input: &mut [&'a str],
        output: &mut [&'a str],
        char_index: usize,
    ) {
        const RADIX: usize = 256;
        let mut count = [0usize; RADIX + 1];
        let len = input.len();

        // Count
        for item in input.iter() {
            let byte = item.as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            count[byte + 1] += 1;
        }

        // Prefix sum
        for i in 1..count.len() {
            count[i] += count[i - 1];
        }

        // Build output (stable)
        for i in 0..len {
            let byte = input[i].as_bytes().get(char_index).copied().unwrap_or(0) as usize;
            output[count[byte]] = input[i];
            count[byte] += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{RadixDataType, SortDirection};

    #[test]
    fn test_sort_strings_basic() {
        let mut strings = vec![
            "banana".to_string(),
            "apple".to_string(),
            "cherry".to_string(),
        ];
        let sorter = RadixSort::<String>::new(RadixDataType::String, SortDirection::Ascending);
        sorter.sort(&mut strings).unwrap();
        assert_eq!(strings, vec!["apple", "banana", "cherry"]);
    }

    #[test]
    fn test_sort_strings_different_lengths() {
        let mut strings = vec!["a".to_string(), "abc".to_string(), "ab".to_string()];
        let sorter = RadixSort::<String>::default();
        sorter.sort(&mut strings).unwrap();
        assert_eq!(strings, vec!["a", "ab", "abc"]);
    }

    #[test]
    fn test_sort_strings_descending() {
        let mut strings = vec![
            "banana".to_string(),
            "apple".to_string(),
            "cherry".to_string(),
        ];
        let sorter = RadixSort::<String>::new(RadixDataType::String, SortDirection::Descending);
        sorter.sort(&mut strings).unwrap();
        assert_eq!(strings, vec!["cherry", "banana", "apple"]);
    }

    #[test]
    fn test_sort_strings_empty() {
        let mut strings: Vec<String> = vec![];
        let sorter = RadixSort::<String>::default();
        sorter.sort(&mut strings).unwrap();
        assert!(strings.is_empty());
    }

    #[test]
    fn test_sort_strings_with_empty_strings() {
        let mut strings = vec!["b".to_string(), "".to_string(), "a".to_string()];
        let sorter = RadixSort::<String>::default();
        sorter.sort(&mut strings).unwrap();
        assert_eq!(strings, vec!["", "a", "b"]);
    }

    #[test]
    fn test_sort_str_slice() {
        let mut strings = vec!["banana", "apple", "cherry"];
        let sorter = RadixSort::<&str>::default();
        sorter.sort(&mut strings).unwrap();
        assert_eq!(strings, vec!["apple", "banana", "cherry"]);
    }
}