string_sorts/
string-sorts.rs

1// SPDX-License-Identifier: MIT
2
3
4extern crate febug;
5
6use std::sync::atomic::{AtomicUsize, Ordering};
7use febug::{StaticWrappable, Wrapper};
8use std::time::Duration;
9use std::any::TypeId;
10use std::io::Write;
11use std::fs::File;
12use std::thread;
13
14
15static COMPARISONS: AtomicUsize = AtomicUsize::new(0);
16
17
18fn main() {
19    febug::start();
20    if febug::install_handler() {
21        // Normal registration by TypeId, variables use .wrap(...)
22        let mut fmt = febug::FORMATTERS.lock().unwrap();
23        fmt.insert(TypeId::of::<String>().into(), |of, vid| {
24            let data = unsafe { &*(vid as *const String) };
25
26            let _ = of.write_all(data.as_bytes());
27            let _ = of.write_all(b"\n");
28        });
29
30        // Custom registration with an explicit type number and Wrapper::new()
31        fmt.insert(0.into(), |of: &mut File, _| {
32            let _ = write!(of, "{}\n", COMPARISONS.load(Ordering::Relaxed));
33        });
34    }
35
36    let _comparisons_wrapper = Wrapper::new(0, &COMPARISONS, format_args!("comparisons"));
37
38
39    let threads = (0..10)
40        .map(|i| {
41            thread::spawn(move || {
42                let mut sorteing = "The quick red fox jumps over the lazy brown \
43                                    dog... tHE QUICK RED FOX JUMPS OVER THE \
44                                    LAZY BROWN DOG!!"
45                                       [0..(i + 1) * 10]
46                    .to_string();
47                let _sorteing_w = sorteing.wrap(format_args!("cool_data_{}", i));
48
49                unsafe { sorteing.as_bytes_mut() }.sort_unstable_by(|a, b| {
50                    thread::sleep(Duration::from_millis(250));
51                    COMPARISONS.fetch_add(1, Ordering::Relaxed);
52                    a.cmp(b)
53                });
54
55                thread::sleep(Duration::from_secs(2));
56            })
57        })
58        .collect::<Vec<_>>();
59    for t in threads {
60        let _ = t.join();
61    }
62}