flay-rs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,163 @@
1
+ //! Text formatting that matches Ruby's `to_s` for the values Flog prints.
2
+
3
+ /// Formats a float exactly as Ruby's `Float#to_s` does.
4
+ ///
5
+ /// Ruby prints the shortest digit string that round-trips. It uses fixed
6
+ /// notation when `-4 < decpt <= 16` and the value has a fraction, or when
7
+ /// `0 < decpt <= 15` and the value is integral; otherwise `d.ddde+XX`.
8
+ pub fn float_to_s(value: f64) -> String {
9
+ if value.is_nan() {
10
+ return "NaN".to_string();
11
+ }
12
+ if value.is_infinite() {
13
+ return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
14
+ }
15
+ if value == 0.0 {
16
+ return if value.is_sign_negative() { "-0.0" } else { "0.0" }.to_string();
17
+ }
18
+
19
+ // Rust's `{:e}` gives the shortest round-trip digits, e.g. "1.2345e6".
20
+ let formatted = format!("{:e}", value.abs());
21
+ let (mantissa, exponent) = formatted.split_once('e').expect("exponent form");
22
+ let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
23
+ let exponent: i32 = exponent.parse().expect("exponent digits");
24
+ let decpt = exponent + 1;
25
+ let digit_count = digits.len() as i32;
26
+
27
+ let mut out = String::new();
28
+ if value < 0.0 {
29
+ out.push('-');
30
+ }
31
+
32
+ let fixed_with_fraction = decpt > 0 && decpt < digit_count && decpt <= 16;
33
+ let fixed_integral = decpt > 0 && decpt >= digit_count && decpt <= 15;
34
+
35
+ if fixed_with_fraction || fixed_integral {
36
+ if decpt >= digit_count {
37
+ out.push_str(&digits);
38
+ out.extend(std::iter::repeat_n('0', (decpt - digit_count) as usize));
39
+ out.push_str(".0");
40
+ } else {
41
+ out.push_str(&digits[..decpt as usize]);
42
+ out.push('.');
43
+ out.push_str(&digits[decpt as usize..]);
44
+ }
45
+ } else if decpt <= 0 && decpt > -4 {
46
+ out.push_str("0.");
47
+ out.extend(std::iter::repeat_n('0', (-decpt) as usize));
48
+ out.push_str(&digits);
49
+ } else {
50
+ out.push_str(&digits[..1]);
51
+ out.push('.');
52
+ if digit_count > 1 {
53
+ out.push_str(&digits[1..]);
54
+ } else {
55
+ out.push('0');
56
+ }
57
+ out.push_str(&format!("e{:+03}", decpt - 1));
58
+ }
59
+ out
60
+ }
61
+
62
+ /// Formats an arbitrary-size integer given as little-endian base 2**32 limbs,
63
+ /// as Ruby's `Integer#to_s` does.
64
+ pub fn integer_to_s(negative: bool, limbs: &[u32]) -> String {
65
+ let mut limbs: Vec<u32> = limbs.to_vec();
66
+ while limbs.len() > 1 && *limbs.last().unwrap() == 0 {
67
+ limbs.pop();
68
+ }
69
+ if limbs.iter().all(|limb| *limb == 0) {
70
+ return "0".to_string();
71
+ }
72
+
73
+ // Repeated division by 10**9, most significant limb first.
74
+ let mut chunks: Vec<u32> = Vec::new();
75
+ while !limbs.iter().all(|limb| *limb == 0) {
76
+ let mut remainder: u64 = 0;
77
+ for limb in limbs.iter_mut().rev() {
78
+ let current = (remainder << 32) | u64::from(*limb);
79
+ *limb = (current / 1_000_000_000) as u32;
80
+ remainder = current % 1_000_000_000;
81
+ }
82
+ chunks.push(remainder as u32);
83
+ while limbs.len() > 1 && *limbs.last().unwrap() == 0 {
84
+ limbs.pop();
85
+ }
86
+ }
87
+
88
+ let mut out = String::new();
89
+ if negative {
90
+ out.push('-');
91
+ }
92
+ out.push_str(&chunks.last().unwrap().to_string());
93
+ for chunk in chunks.iter().rev().skip(1) {
94
+ out.push_str(&format!("{chunk:09}"));
95
+ }
96
+ out
97
+ }
98
+
99
+ /// `String#inspect` for a UTF-8 String.
100
+ pub fn string_inspect(string: &str) -> String {
101
+ let mut inspected = String::from("\"");
102
+ let mut chars = string.chars().peekable();
103
+ while let Some(c) = chars.next() {
104
+ match c {
105
+ '"' => inspected.push_str("\\\""),
106
+ '\\' => inspected.push_str("\\\\"),
107
+ '\n' => inspected.push_str("\\n"),
108
+ '\r' => inspected.push_str("\\r"),
109
+ '\t' => inspected.push_str("\\t"),
110
+ '\u{c}' => inspected.push_str("\\f"),
111
+ '\u{b}' => inspected.push_str("\\v"),
112
+ '\u{8}' => inspected.push_str("\\b"),
113
+ '\u{7}' => inspected.push_str("\\a"),
114
+ '\u{1b}' => inspected.push_str("\\e"),
115
+ '#' if matches!(chars.peek(), Some('{' | '$' | '@')) => inspected.push_str("\\#"),
116
+ c if c.is_control() && (c as u32) < 0x80 => inspected.push_str(&format!("\\x{:02X}", c as u32)),
117
+ c if c.is_control() => inspected.push_str(&format!("\\u{:04X}", c as u32)),
118
+ c => inspected.push(c),
119
+ }
120
+ }
121
+ inspected.push('"');
122
+ inspected
123
+ }
124
+
125
+ #[cfg(test)]
126
+ mod tests {
127
+ use super::*;
128
+
129
+ #[test]
130
+ fn float_to_s_matches_ruby() {
131
+ assert_eq!(float_to_s(1.0), "1.0");
132
+ assert_eq!(float_to_s(1.1), "1.1");
133
+ assert_eq!(float_to_s(0.25), "0.25");
134
+ assert_eq!(float_to_s(1.2000000000000002), "1.2000000000000002");
135
+ assert_eq!(float_to_s(100.0), "100.0");
136
+ assert_eq!(float_to_s(1e15), "1.0e+15");
137
+ assert_eq!(float_to_s(1e14), "100000000000000.0");
138
+ assert_eq!(float_to_s(1234567890123456.8), "1234567890123456.8");
139
+ assert_eq!(float_to_s(0.00015000000000000001), "0.00015000000000000001");
140
+ assert_eq!(float_to_s(1e16), "1.0e+16");
141
+ assert_eq!(float_to_s(1.5e16), "1.5e+16");
142
+ assert_eq!(float_to_s(9999999999999998.0), "9.999999999999998e+15");
143
+ assert_eq!(float_to_s(0.0001), "0.0001");
144
+ assert_eq!(float_to_s(0.00001), "1.0e-05");
145
+ assert_eq!(float_to_s(0.000123), "0.000123");
146
+ assert_eq!(float_to_s(-2.5), "-2.5");
147
+ assert_eq!(float_to_s(0.0), "0.0");
148
+ }
149
+
150
+ #[test]
151
+ fn integer_to_s_handles_bignums() {
152
+ assert_eq!(integer_to_s(false, &[0]), "0");
153
+ assert_eq!(integer_to_s(true, &[1]), "-1");
154
+ assert_eq!(integer_to_s(false, &[0, 1]), "4294967296");
155
+ assert_eq!(integer_to_s(false, &[0x3B9A_CA00]), "1000000000");
156
+ }
157
+
158
+ #[test]
159
+ fn string_inspect_escapes_like_ruby() {
160
+ assert_eq!(string_inspect("a\"b\\c\n#{x}#y\u{1}\u{85}é"), "\"a\\\"b\\\\c\\n\\#{x}#y\\x01\\u0085é\"");
161
+ }
162
+
163
+ }
@@ -0,0 +1,246 @@
1
+ //! The order Ruby's `Enumerable#sort_by` gives. `sort_by` is not stable, so
2
+ //! elements with equal keys come out in the order Ruby's algorithm leaves
3
+ //! them:
4
+ //!
5
+ //! - When every key is a Float or an Integer, `sort_by` uses its own
6
+ //! introsort (`rb_uniform_intro_sort_2` in `enum.c`), the same in 3.3, 3.4
7
+ //! and 4.0. [`sort_by_numeric_keys`] ports it.
8
+ //! - Otherwise it calls `ruby_qsort`, which is the C library's `qsort_r` when
9
+ //! that is GNU's (`HAVE_GNU_QSORT_R`). [`ruby_qsort`] calls the same
10
+ //! function.
11
+
12
+ use std::cmp::Ordering;
13
+
14
+ /// One `sort_by` entry: the key and the element's index.
15
+ type Entry = (f64, usize);
16
+
17
+ /// The indexes of `keys` in the order `sort_by` yields the elements, for
18
+ /// keys that are all Floats or Integers (given here as `f64`).
19
+ pub fn sort_by_numeric_keys(keys: &[f64]) -> Vec<usize> {
20
+ let mut entries: Vec<Entry> = keys.iter().copied().zip(0..).collect();
21
+ // `if (RARRAY_LEN(ary) > 2)`: the buffer holds two VALUEs per element.
22
+ if entries.len() > 1 {
23
+ uniform_intro_sort(&mut entries);
24
+ }
25
+ entries.into_iter().map(|(_, index)| index).collect()
26
+ }
27
+
28
+ /// `rb_uniform_is_less`.
29
+ fn uniform_is_less(a: f64, b: f64) -> bool {
30
+ a < b
31
+ }
32
+
33
+ /// `rb_uniform_intro_sort_2`: returns at once when the keys are already in
34
+ /// order, then sorts with a depth limit of twice `floor(log2(n))`.
35
+ fn uniform_intro_sort(entries: &mut [Entry]) {
36
+ let n = entries.len();
37
+ let depth = (usize::BITS - 1 - n.leading_zeros()) as usize;
38
+ let sorted = entries.windows(2).all(|pair| !uniform_is_larger(pair[0].0, pair[1].0));
39
+ if sorted {
40
+ return;
41
+ }
42
+ uniform_quicksort_intro(entries, 0, n, depth << 1);
43
+ }
44
+
45
+ /// `rb_uniform_is_larger`.
46
+ fn uniform_is_larger(a: f64, b: f64) -> bool {
47
+ a > b
48
+ }
49
+
50
+ /// `rb_uniform_quicksort_intro_2` on `entries[begin..end]`. The two ranges
51
+ /// it recurses into can share one element (equal to the pivot), so this
52
+ /// works on index bounds as the C code does on pointers.
53
+ fn uniform_quicksort_intro(entries: &mut [Entry], begin: usize, end: usize, depth: usize) {
54
+ if end - begin <= 16 {
55
+ uniform_insertion_sort(&mut entries[begin..end]);
56
+ return;
57
+ }
58
+ if depth == 0 {
59
+ uniform_heapsort(&mut entries[begin..end]);
60
+ return;
61
+ }
62
+
63
+ let pivot = median_of_three(entries[begin].0, entries[begin + ((end - begin) >> 1)].0, entries[end - 1].0);
64
+ let mut i = begin as isize;
65
+ let mut j = end as isize - 1;
66
+ loop {
67
+ while uniform_is_less(entries[i as usize].0, pivot) {
68
+ i += 1;
69
+ }
70
+ while uniform_is_less(pivot, entries[j as usize].0) {
71
+ j -= 1;
72
+ }
73
+ if i <= j {
74
+ entries.swap(i as usize, j as usize);
75
+ i += 1;
76
+ j -= 1;
77
+ }
78
+ if i > j {
79
+ break;
80
+ }
81
+ }
82
+ let j = (j + 1) as usize;
83
+ let i = i as usize;
84
+ if end - j > 1 {
85
+ uniform_quicksort_intro(entries, j, end, depth - 1);
86
+ }
87
+ if i - begin > 1 {
88
+ uniform_quicksort_intro(entries, begin, i, depth - 1);
89
+ }
90
+ }
91
+
92
+ /// `med3_val`.
93
+ fn median_of_three(a: f64, b: f64, c: f64) -> f64 {
94
+ let less = uniform_is_less;
95
+ if less(a, b) {
96
+ if less(b, c) {
97
+ b
98
+ } else if less(c, a) {
99
+ a
100
+ } else {
101
+ c
102
+ }
103
+ } else if less(c, b) {
104
+ b
105
+ } else if less(a, c) {
106
+ a
107
+ } else {
108
+ c
109
+ }
110
+ }
111
+
112
+ /// `rb_uniform_insertionsort_2`: an element smaller than the first goes to
113
+ /// the front; any other moves left past every larger element.
114
+ fn uniform_insertion_sort(entries: &mut [Entry]) {
115
+ for index in 1..entries.len() {
116
+ let entry = entries[index];
117
+ let mut j = index;
118
+ if uniform_is_less(entry.0, entries[0].0) {
119
+ entries.copy_within(0..index, 1);
120
+ j = 0;
121
+ } else {
122
+ while uniform_is_less(entry.0, entries[j - 1].0) {
123
+ entries[j] = entries[j - 1];
124
+ j -= 1;
125
+ }
126
+ }
127
+ entries[j] = entry;
128
+ }
129
+ }
130
+
131
+ /// `rb_uniform_heapsort_2`.
132
+ fn uniform_heapsort(entries: &mut [Entry]) {
133
+ let n = entries.len();
134
+ if n < 2 {
135
+ return;
136
+ }
137
+ for offset in (0..n >> 1).rev() {
138
+ uniform_heap_down(entries, offset, n - 1);
139
+ }
140
+ for last in (1..n).rev() {
141
+ entries.swap(0, last);
142
+ uniform_heap_down(entries, 0, last - 1);
143
+ }
144
+ }
145
+
146
+ /// `rb_uniform_heap_down_2`: `last` is the index of the heap's last entry.
147
+ fn uniform_heap_down(entries: &mut [Entry], mut offset: usize, last: usize) {
148
+ let entry = entries[offset];
149
+ loop {
150
+ let mut child = (offset << 1) + 1;
151
+ if child > last {
152
+ break;
153
+ }
154
+ if child < last && uniform_is_less(entries[child].0, entries[child + 1].0) {
155
+ child += 1;
156
+ }
157
+ if !uniform_is_less(entry.0, entries[child].0) {
158
+ break;
159
+ }
160
+ entries[offset] = entries[child];
161
+ offset = child;
162
+ }
163
+ entries[offset] = entry;
164
+ }
165
+
166
+ /// `ruby_qsort`, which Ruby defines as the C library's `qsort_r` on glibc.
167
+ #[cfg(all(target_os = "linux", target_env = "gnu"))]
168
+ pub fn ruby_qsort<T, F: FnMut(&T, &T) -> Ordering>(elements: &mut [T], mut compare: F) {
169
+ use std::ffi::{c_int, c_void};
170
+
171
+ extern "C" {
172
+ fn qsort_r(
173
+ base: *mut c_void,
174
+ count: usize,
175
+ size: usize,
176
+ compare: unsafe extern "C" fn(*const c_void, *const c_void, *mut c_void) -> c_int,
177
+ argument: *mut c_void,
178
+ );
179
+ }
180
+
181
+ unsafe extern "C" fn trampoline<T, F: FnMut(&T, &T) -> Ordering>(
182
+ a: *const c_void,
183
+ b: *const c_void,
184
+ argument: *mut c_void,
185
+ ) -> c_int {
186
+ // SAFETY: qsort_r passes pointers to elements of the slice and the
187
+ // closure given below.
188
+ let (compare, a, b) = unsafe { (&mut *(argument as *mut F), &*(a as *const T), &*(b as *const T)) };
189
+ compare(a, b) as c_int
190
+ }
191
+
192
+ // SAFETY: the pointer and length describe the slice; qsort_r only
193
+ // moves whole elements, which are plain data here.
194
+ unsafe {
195
+ qsort_r(
196
+ elements.as_mut_ptr() as *mut c_void,
197
+ elements.len(),
198
+ std::mem::size_of::<T>(),
199
+ trampoline::<T, F>,
200
+ &mut compare as *mut F as *mut c_void,
201
+ );
202
+ }
203
+ }
204
+
205
+ /// `ruby_qsort` on platforms without glibc: a stable sort, which gives
206
+ /// glibc's order (its `qsort_r` is a merge sort) but may not give the
207
+ /// platform's.
208
+ #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
209
+ pub fn ruby_qsort<T>(elements: &mut [T], compare: impl FnMut(&T, &T) -> Ordering) {
210
+ elements.sort_by(compare);
211
+ }
212
+
213
+ #[cfg(test)]
214
+ mod tests {
215
+ use super::*;
216
+
217
+ /// `(1..40).map { |i| -(i % 3).to_f }`, sorted with `sort_by` on Ruby
218
+ /// 3.3.14 (x86_64 Linux): the 1-based positions.
219
+ const KEYS_40: fn() -> Vec<f64> = || (1..=40).map(|i| -f64::from(i % 3)).collect();
220
+
221
+ fn one_based(order: Vec<usize>) -> Vec<usize> {
222
+ order.into_iter().map(|index| index + 1).collect()
223
+ }
224
+
225
+ #[test]
226
+ fn ruby_3_3_order_for_ties() {
227
+ let expected = [
228
+ 20, 23, 17, 26, 14, 29, 11, 32, 8, 35, 5, 38, 2, 31, 34, 28, 37, 25, 22, 40, 1, 4, 7, 10, 13, 16, 19, 15,
229
+ 27, 12, 30, 24, 9, 33, 18, 6, 36, 3, 39, 21,
230
+ ];
231
+ assert_eq!(one_based(sort_by_numeric_keys(&KEYS_40())), expected);
232
+ }
233
+
234
+ #[test]
235
+ fn sorted_keys_keep_their_order() {
236
+ assert_eq!(sort_by_numeric_keys(&[1.0, 1.0, 2.0]), vec![0, 1, 2]);
237
+ assert_eq!(sort_by_numeric_keys(&[]), Vec::<usize>::new());
238
+ }
239
+
240
+ #[test]
241
+ fn deep_inputs_use_heapsort_and_stay_sorted() {
242
+ let keys: Vec<f64> = (0..5000).map(|i| f64::from((i * 7919) % 101)).collect();
243
+ let order = sort_by_numeric_keys(&keys);
244
+ assert!(order.windows(2).all(|pair| keys[pair[0]] <= keys[pair[1]]));
245
+ }
246
+ }