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.
- checksums.yaml +7 -0
- data/Cargo.lock +495 -0
- data/Cargo.toml +23 -0
- data/DIVERGENCES.md +23 -0
- data/LICENSE +22 -0
- data/README.md +111 -0
- data/THIRD_PARTY_NOTICES.md +70 -0
- data/crates/flay-cli/Cargo.toml +22 -0
- data/crates/flay-cli/src/bin/flay-matcher-parity.rs +195 -0
- data/crates/flay-cli/src/main.rs +202 -0
- data/crates/flay-core/Cargo.toml +20 -0
- data/crates/flay-core/src/attach_comments.rs +353 -0
- data/crates/flay-core/src/erb.rs +418 -0
- data/crates/flay-core/src/lib.rs +488 -0
- data/crates/flay-core/src/matcher/parser.rs +345 -0
- data/crates/flay-core/src/matcher/regexp.rs +1243 -0
- data/crates/flay-core/src/matcher/ruby_text.rs +413 -0
- data/crates/flay-core/src/matcher/serialized.rs +340 -0
- data/crates/flay-core/src/matcher.rs +487 -0
- data/crates/flay-core/src/process.rs +312 -0
- data/crates/flay-core/src/report.rs +567 -0
- data/crates/flay-core/src/ruby2ruby.rs +3291 -0
- data/crates/flay-core/src/ruby_format.rs +163 -0
- data/crates/flay-core/src/ruby_sort.rs +246 -0
- data/crates/flay-core/src/sexp.rs +639 -0
- data/crates/flay-core/src/translate.rs +2290 -0
- data/crates/flay-core/tests/ruby2ruby_parity.rs +101 -0
- data/ext/flay_rs/Cargo.toml +17 -0
- data/ext/flay_rs/extconf.rb +6 -0
- data/ext/flay_rs/src/filters.rs +186 -0
- data/ext/flay_rs/src/lib.rs +544 -0
- data/lib/flay_rs/version.rb +8 -0
- data/lib/flay_rs.rb +18 -0
- metadata +94 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
//! Flay's report: the items `Flay#analyze` returns, `Flay#summary` and the
|
|
2
|
+
//! lines `Flay#report` prints, including the `--diff` output
|
|
3
|
+
//! (`Flay#n_way_diff`).
|
|
4
|
+
|
|
5
|
+
use std::cmp::Ordering;
|
|
6
|
+
|
|
7
|
+
use indexmap::IndexMap;
|
|
8
|
+
|
|
9
|
+
use crate::ruby_sort::ruby_qsort;
|
|
10
|
+
use crate::sexp::{RubyString, SexpId, Tree, Value, ASCII_8BIT, UTF_8};
|
|
11
|
+
use crate::{Flay, NodeRef, RubyException};
|
|
12
|
+
|
|
13
|
+
/// `Flay::Item`: one bucket in the report.
|
|
14
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
15
|
+
pub struct Item {
|
|
16
|
+
pub structural_hash: u32,
|
|
17
|
+
/// `name`: the first node's `sexp_type`, a Symbol's bytes.
|
|
18
|
+
pub name: Vec<u8>,
|
|
19
|
+
/// `bonus`: `"*N"` for N identical nodes, `None` otherwise
|
|
20
|
+
/// (`identical?` is `bonus`).
|
|
21
|
+
pub bonus: Option<String>,
|
|
22
|
+
pub mass: u64,
|
|
23
|
+
pub locations: Vec<Location>,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// `Flay::Location`.
|
|
27
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
28
|
+
pub struct Location {
|
|
29
|
+
pub file: String,
|
|
30
|
+
pub line: i32,
|
|
31
|
+
/// `fuzzy`: `:fuzzy` for a node the `fuzzy` option made.
|
|
32
|
+
pub fuzzy: bool,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// The `filter` argument of `Flay#analyze`: the items whose first node's
|
|
36
|
+
/// `sexp_type` equals it.
|
|
37
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
38
|
+
pub enum TypeFilter {
|
|
39
|
+
/// `nil` or `false`: every item.
|
|
40
|
+
All,
|
|
41
|
+
/// A Symbol: the items of that type.
|
|
42
|
+
Only(Vec<u8>),
|
|
43
|
+
/// Any other value, which no `sexp_type` equals: no items.
|
|
44
|
+
Nothing,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// The options `Flay#report` reads.
|
|
48
|
+
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
49
|
+
pub struct ReportOptions {
|
|
50
|
+
/// `option[:only]`.
|
|
51
|
+
pub only: TypeFilter,
|
|
52
|
+
/// `option[:summary]`: print each file's score instead of the items.
|
|
53
|
+
pub summary: bool,
|
|
54
|
+
/// `option[:number]`: number the items.
|
|
55
|
+
pub number: bool,
|
|
56
|
+
/// `option[:diff]`: print an n-way diff of each item's nodes.
|
|
57
|
+
pub diff: bool,
|
|
58
|
+
/// `option[:liberal]`, which `analyze` prunes with.
|
|
59
|
+
pub liberal: bool,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
impl Flay {
|
|
63
|
+
/// `Flay#analyze(filter)`: prunes, checks for identical nodes, updates
|
|
64
|
+
/// masses, then returns the items from the highest mass down (then by
|
|
65
|
+
/// the first node's file, line and type), each with its nodes' locations
|
|
66
|
+
/// sorted by file and line.
|
|
67
|
+
pub fn analyze_items(&mut self, liberal: bool, filter: &TypeFilter) -> Vec<Item> {
|
|
68
|
+
self.analyze(liberal);
|
|
69
|
+
|
|
70
|
+
let mut sorted: Vec<(u32, u64)> = self.masses.iter().map(|(hash, mass)| (*hash, *mass)).collect();
|
|
71
|
+
ruby_qsort(&mut sorted, |(hash_a, mass_a), (hash_b, mass_b)| {
|
|
72
|
+
let (a, b) = (self.node(self.hashes[hash_a][0]), self.node(self.hashes[hash_b][0]));
|
|
73
|
+
mass_b
|
|
74
|
+
.cmp(mass_a)
|
|
75
|
+
.then_with(|| a.file.as_bytes().cmp(b.file.as_bytes()))
|
|
76
|
+
.then_with(|| a.line.cmp(&b.line))
|
|
77
|
+
.then_with(|| a.sexp_type.cmp(b.sexp_type))
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
sorted
|
|
81
|
+
.into_iter()
|
|
82
|
+
.filter_map(|(hash, mass)| {
|
|
83
|
+
let nodes = &self.hashes[&hash];
|
|
84
|
+
let first = self.node(nodes[0]);
|
|
85
|
+
let wanted = match filter {
|
|
86
|
+
TypeFilter::All => true,
|
|
87
|
+
TypeFilter::Only(sexp_type) => first.sexp_type == sexp_type.as_slice(),
|
|
88
|
+
TypeFilter::Nothing => false,
|
|
89
|
+
};
|
|
90
|
+
if !wanted {
|
|
91
|
+
return None;
|
|
92
|
+
}
|
|
93
|
+
let identical = self.identical.get(&hash).copied().unwrap_or(false);
|
|
94
|
+
Some(Item {
|
|
95
|
+
structural_hash: hash,
|
|
96
|
+
name: first.sexp_type.to_vec(),
|
|
97
|
+
bonus: identical.then(|| format!("*{}", nodes.len())),
|
|
98
|
+
mass,
|
|
99
|
+
locations: self.locations(nodes),
|
|
100
|
+
})
|
|
101
|
+
})
|
|
102
|
+
.collect()
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/// The nodes' locations, sorted with `sort_by { |x| [x.file, x.line] }`.
|
|
106
|
+
fn locations(&self, nodes: &[NodeRef]) -> Vec<Location> {
|
|
107
|
+
let mut locations: Vec<Location> = nodes
|
|
108
|
+
.iter()
|
|
109
|
+
.map(|node| {
|
|
110
|
+
let info = self.node(*node);
|
|
111
|
+
Location { file: info.file.to_string(), line: info.line, fuzzy: info.modified }
|
|
112
|
+
})
|
|
113
|
+
.collect();
|
|
114
|
+
// Sort indexes: Ruby sorts 16-byte `[key, value]` entries.
|
|
115
|
+
let mut order: Vec<(usize, usize)> = (0..locations.len()).map(|index| (index, 0)).collect();
|
|
116
|
+
ruby_qsort(&mut order, |(a, _), (b, _)| {
|
|
117
|
+
let (a, b) = (&locations[*a], &locations[*b]);
|
|
118
|
+
a.file.as_bytes().cmp(b.file.as_bytes()).then_with(|| a.line.cmp(&b.line))
|
|
119
|
+
});
|
|
120
|
+
let mut sorted = Vec::with_capacity(locations.len());
|
|
121
|
+
for (index, _) in order {
|
|
122
|
+
sorted.push(std::mem::replace(&mut locations[index], Location { file: String::new(), line: 0, fuzzy: false }));
|
|
123
|
+
}
|
|
124
|
+
sorted
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// `Flay#summary`: each file's share of every bucket's mass, the mass
|
|
128
|
+
/// split evenly between the bucket's nodes.
|
|
129
|
+
pub fn summary(&self) -> IndexMap<String, f64> {
|
|
130
|
+
let mut score: IndexMap<String, f64> = IndexMap::new();
|
|
131
|
+
for (hash, mass) in &self.masses {
|
|
132
|
+
let nodes = &self.hashes[hash];
|
|
133
|
+
let mass_per_file = *mass as f64 / nodes.len() as f64;
|
|
134
|
+
for node in nodes {
|
|
135
|
+
*score.entry(self.node(*node).file.to_string()).or_insert(0.0) += mass_per_file;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
score
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/// `Flay#report`: pushes onto `lines` the Strings Flay prints, one per
|
|
142
|
+
/// `io.puts`, up to the exception Flay raises, if any. Calls `analyze`
|
|
143
|
+
/// first. `sexp_to_rb` is `Flay#sexp_to_rb`, which turns a node back
|
|
144
|
+
/// into Ruby for the `diff` option; it gets the node's file, tree, sexp
|
|
145
|
+
/// (the original of a fuzzy node) and elements. File names are taken to
|
|
146
|
+
/// be UTF-8.
|
|
147
|
+
pub fn report(
|
|
148
|
+
&mut self,
|
|
149
|
+
options: &ReportOptions,
|
|
150
|
+
mut sexp_to_rb: impl FnMut(&str, &Tree, SexpId, &[Value]) -> Result<RubyString, RubyException>,
|
|
151
|
+
lines: &mut Vec<RubyString>,
|
|
152
|
+
) -> Result<(), RubyException> {
|
|
153
|
+
let data = self.analyze_items(options.liberal, &options.only);
|
|
154
|
+
lines.push(utf8(format!("Total score (lower is better) = {}", self.total)));
|
|
155
|
+
|
|
156
|
+
if options.summary {
|
|
157
|
+
lines.push(utf8(String::new()));
|
|
158
|
+
let mut summary: Vec<(String, f64)> = self.summary().into_iter().collect();
|
|
159
|
+
ruby_qsort(&mut summary, |(file_a, score_a), (file_b, score_b)| {
|
|
160
|
+
score_b.partial_cmp(score_a).unwrap_or(Ordering::Equal).then_with(|| file_a.as_bytes().cmp(file_b.as_bytes()))
|
|
161
|
+
});
|
|
162
|
+
for (file, score) in summary {
|
|
163
|
+
lines.push(utf8(format!("{:>8}: {}", format_fixed(score, 2), file)));
|
|
164
|
+
}
|
|
165
|
+
return Ok(());
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
for (count, item) in data.iter().enumerate() {
|
|
169
|
+
let prefix = if options.number { format!("{}) ", count + 1) } else { String::new() };
|
|
170
|
+
let matched = if item.bonus.is_some() { "IDENTICAL" } else { "Similar" };
|
|
171
|
+
lines.push(utf8(String::new()));
|
|
172
|
+
lines.push(utf8(format!(
|
|
173
|
+
"{prefix}{matched} code found in {} (mass{} = {})",
|
|
174
|
+
symbol_inspect(&item.name),
|
|
175
|
+
item.bonus.as_deref().unwrap_or(""),
|
|
176
|
+
item.mass
|
|
177
|
+
)));
|
|
178
|
+
|
|
179
|
+
for (index, location) in item.locations.iter().enumerate() {
|
|
180
|
+
// `" %s%s:%d%s" % [loc_prefix, loc.file, loc.line, extra]`
|
|
181
|
+
let mut line = utf8(" ".to_string());
|
|
182
|
+
if options.diff {
|
|
183
|
+
// `"%s: " % (?A.ord + i).chr`
|
|
184
|
+
let mut location_prefix = utf8(String::new());
|
|
185
|
+
append(&mut location_prefix, &group_letter(index)?)?;
|
|
186
|
+
append(&mut location_prefix, &utf8(": ".to_string()))?;
|
|
187
|
+
append(&mut line, &location_prefix)?;
|
|
188
|
+
}
|
|
189
|
+
append(&mut line, &utf8(location.file.clone()))?;
|
|
190
|
+
let extra = if location.fuzzy { " (FUZZY)" } else { "" };
|
|
191
|
+
append(&mut line, &utf8(format!(":{}{extra}", location.line)))?;
|
|
192
|
+
lines.push(line);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if options.diff {
|
|
196
|
+
lines.push(utf8(String::new()));
|
|
197
|
+
let mut sources = Vec::new();
|
|
198
|
+
for node in &self.hashes[&item.structural_hash] {
|
|
199
|
+
let (tree, elements) = self.node_sexp(*node);
|
|
200
|
+
sources.push(sexp_to_rb(self.node(*node).file, tree, node.sexp, elements)?);
|
|
201
|
+
}
|
|
202
|
+
lines.push(n_way_diff(&sources)?);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
Ok(())
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/// A UTF-8 String.
|
|
210
|
+
fn utf8(text: String) -> RubyString {
|
|
211
|
+
RubyString::new(text, UTF_8)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/// `string << other` (and `"#{string}#{other}"`, `format` and
|
|
215
|
+
/// `Array#join`, which append the same way): the bytes joined. Two Strings
|
|
216
|
+
/// in different encodings, both with non-ASCII bytes, raise
|
|
217
|
+
/// `Encoding::CompatibilityError`; otherwise the result is in the encoding
|
|
218
|
+
/// of the one with non-ASCII bytes, or `string`'s.
|
|
219
|
+
fn append(string: &mut RubyString, other: &RubyString) -> Result<(), RubyException> {
|
|
220
|
+
if string.encoding != other.encoding && !other.bytes.is_ascii() {
|
|
221
|
+
if !string.bytes.is_ascii() {
|
|
222
|
+
return Err(RubyException {
|
|
223
|
+
class: "Encoding::CompatibilityError",
|
|
224
|
+
message: format!("incompatible character encodings: {} and {}", string.encoding, other.encoding),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
string.encoding = other.encoding;
|
|
228
|
+
}
|
|
229
|
+
string.bytes.extend_from_slice(&other.bytes);
|
|
230
|
+
Ok(())
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// `(?A.ord + index).chr`: the character that labels a node in the diff,
|
|
234
|
+
/// "A" to "Z" and on through the ASCII table. From the 64th node it is a
|
|
235
|
+
/// single byte above 127, in ASCII-8BIT; from the 192nd, `Integer#chr`
|
|
236
|
+
/// raises RangeError.
|
|
237
|
+
fn group_letter(index: usize) -> Result<RubyString, RubyException> {
|
|
238
|
+
let code = 'A' as usize + index;
|
|
239
|
+
match u8::try_from(code) {
|
|
240
|
+
Ok(byte) if byte.is_ascii() => Ok(RubyString::new([byte], "US-ASCII")),
|
|
241
|
+
Ok(byte) => Ok(RubyString::new([byte], ASCII_8BIT)),
|
|
242
|
+
Err(_) => Err(RubyException { class: "RangeError", message: format!("{code} out of char range") }),
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// `Flay#n_way_diff(*data)`: each source split into lines, leading comment
|
|
247
|
+
/// lines and code compared separately; lines all sources share are printed
|
|
248
|
+
/// once, indented, and the others once per source, labeled with its
|
|
249
|
+
/// letter.
|
|
250
|
+
pub fn n_way_diff(sources: &[RubyString]) -> Result<RubyString, RubyException> {
|
|
251
|
+
let mut comments = Vec::new();
|
|
252
|
+
let mut codes = Vec::new();
|
|
253
|
+
for lines in split_and_group(sources)? {
|
|
254
|
+
let Some(code_start) = lines.iter().position(|(_, line)| !line.bytes.starts_with(b"#")) else {
|
|
255
|
+
// `subdata[0..n-1]` with `n` nil.
|
|
256
|
+
return Err(RubyException { class: "NoMethodError", message: "undefined method `-' for nil".into() });
|
|
257
|
+
};
|
|
258
|
+
let (comment, code) = lines.split_at(code_start);
|
|
259
|
+
comments.push(comment.to_vec());
|
|
260
|
+
codes.push(code.to_vec());
|
|
261
|
+
}
|
|
262
|
+
let mut output = collapse_and_label(pad_with_empty_strings(comments))?;
|
|
263
|
+
output.extend(collapse_and_label(pad_with_empty_strings(codes))?);
|
|
264
|
+
// `(comments + codes).flatten.join("\n")`
|
|
265
|
+
let Some(first) = output.first() else {
|
|
266
|
+
return Ok(RubyString::new("", "US-ASCII"));
|
|
267
|
+
};
|
|
268
|
+
let mut joined = RubyString::new("", first.encoding);
|
|
269
|
+
for (index, line) in output.iter().enumerate() {
|
|
270
|
+
if index > 0 {
|
|
271
|
+
append(&mut joined, &utf8("\n".to_string()))?;
|
|
272
|
+
}
|
|
273
|
+
append(&mut joined, line)?;
|
|
274
|
+
}
|
|
275
|
+
Ok(joined)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/// A line of one source, with that source's letter (`String#group`); the
|
|
279
|
+
/// padding lines have none.
|
|
280
|
+
type GroupedLine = (Option<RubyString>, RubyString);
|
|
281
|
+
|
|
282
|
+
/// `Flay#split_and_group`: each source's lines (`s.scan(/^.*/)`), labeled
|
|
283
|
+
/// A, B, C... by source.
|
|
284
|
+
fn split_and_group(sources: &[RubyString]) -> Result<Vec<Vec<GroupedLine>>, RubyException> {
|
|
285
|
+
let mut groups = Vec::with_capacity(sources.len());
|
|
286
|
+
for (index, source) in sources.iter().enumerate() {
|
|
287
|
+
let group = group_letter(index)?;
|
|
288
|
+
// `scan(/^.*/)` finds no line after a final newline.
|
|
289
|
+
let bytes = source.bytes.strip_suffix(b"\n").unwrap_or(&source.bytes);
|
|
290
|
+
let lines = bytes
|
|
291
|
+
.split(|byte| *byte == b'\n')
|
|
292
|
+
.map(|line| (Some(group.clone()), RubyString::new(line, source.encoding)))
|
|
293
|
+
.collect();
|
|
294
|
+
groups.push(lines);
|
|
295
|
+
}
|
|
296
|
+
Ok(groups)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/// `Flay#pad_with_empty_strings`: every list as long as the longest.
|
|
300
|
+
fn pad_with_empty_strings(mut lists: Vec<Vec<GroupedLine>>) -> Vec<Vec<GroupedLine>> {
|
|
301
|
+
let max = lists.iter().map(Vec::len).max().unwrap_or(0);
|
|
302
|
+
for list in &mut lists {
|
|
303
|
+
list.resize(max, (None, utf8(String::new())));
|
|
304
|
+
}
|
|
305
|
+
lists
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/// `Flay#collapse_and_label`: for each line number, the line indented by
|
|
309
|
+
/// three spaces when every source has the same line (`lines.uniq.size ==
|
|
310
|
+
/// 1`), otherwise each non-empty line prefixed with its source's letter.
|
|
311
|
+
fn collapse_and_label(lists: Vec<Vec<GroupedLine>>) -> Result<Vec<RubyString>, RubyException> {
|
|
312
|
+
let length = lists.first().map_or(0, Vec::len);
|
|
313
|
+
let mut output = Vec::new();
|
|
314
|
+
for index in 0..length {
|
|
315
|
+
let lines: Vec<&GroupedLine> = lists.iter().map(|list| &list[index]).collect();
|
|
316
|
+
if lines.iter().all(|(_, line)| line.ruby_eq(&lines[0].1)) {
|
|
317
|
+
// `" #{lines.first}"`
|
|
318
|
+
let mut collapsed = utf8(" ".to_string());
|
|
319
|
+
append(&mut collapsed, &lines[0].1)?;
|
|
320
|
+
output.push(collapsed);
|
|
321
|
+
} else {
|
|
322
|
+
for (group, line) in lines.into_iter().filter(|(_, line)| !line.bytes.is_empty()) {
|
|
323
|
+
// `"#{l.group}: #{l}"`
|
|
324
|
+
let mut labeled = utf8(String::new());
|
|
325
|
+
if let Some(group) = group {
|
|
326
|
+
append(&mut labeled, group)?;
|
|
327
|
+
}
|
|
328
|
+
append(&mut labeled, &utf8(": ".to_string()))?;
|
|
329
|
+
append(&mut labeled, line)?;
|
|
330
|
+
output.push(labeled);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
Ok(output)
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/// `Symbol#inspect` for a sexp type: `:name` for a plain identifier,
|
|
338
|
+
/// otherwise the name quoted.
|
|
339
|
+
fn symbol_inspect(name: &[u8]) -> String {
|
|
340
|
+
let text = String::from_utf8_lossy(name);
|
|
341
|
+
let mut chars = text.chars();
|
|
342
|
+
let plain = chars.next().is_some_and(|first| first == '_' || first.is_ascii_alphabetic())
|
|
343
|
+
&& text.trim_end_matches(['?', '!']).chars().all(|c| c == '_' || c.is_ascii_alphanumeric())
|
|
344
|
+
&& text.matches(['?', '!']).count() <= 1;
|
|
345
|
+
if plain {
|
|
346
|
+
format!(":{text}")
|
|
347
|
+
} else {
|
|
348
|
+
format!(":{:?}", text)
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/// `format("%.<precision>f", value)` as Ruby prints it. Ruby's `BSD__dtoa`
|
|
353
|
+
/// (mode 3, `missing/dtoa.c`) first estimates the digits with
|
|
354
|
+
/// floating-point arithmetic; when that estimate cannot tell whether the
|
|
355
|
+
/// rest is above or below half a unit in the last place, Ruby rounds half
|
|
356
|
+
/// to even on the estimated digits (its `half` flag), so 2.675 prints as
|
|
357
|
+
/// "2.68" though it is below 2.675. Otherwise the result is the correctly
|
|
358
|
+
/// rounded one.
|
|
359
|
+
pub fn format_fixed(value: f64, precision: usize) -> String {
|
|
360
|
+
if !value.is_finite() {
|
|
361
|
+
return if value.is_nan() { "NaN".into() } else if value > 0.0 { "Inf".into() } else { "-Inf".into() };
|
|
362
|
+
}
|
|
363
|
+
let sign = if value.is_sign_negative() { "-" } else { "" };
|
|
364
|
+
let value = value.abs();
|
|
365
|
+
if !in_half_band(value, precision as i32) {
|
|
366
|
+
return format!("{sign}{value:.precision$}");
|
|
367
|
+
}
|
|
368
|
+
// Truncate (the exact expansion has at most 1074 fraction digits), then
|
|
369
|
+
// round up when the last digit is odd.
|
|
370
|
+
let exact = format!("{value:.1100}");
|
|
371
|
+
let (integer, fraction) = exact.split_once('.').expect("fixed notation has a point");
|
|
372
|
+
let mut digits: Vec<u8> = integer.bytes().chain(fraction.bytes().take(precision)).map(|b| b - b'0').collect();
|
|
373
|
+
if digits.last().is_some_and(|digit| digit % 2 == 1) {
|
|
374
|
+
round_up(&mut digits);
|
|
375
|
+
}
|
|
376
|
+
let point = digits.len() - precision;
|
|
377
|
+
let text = |digits: &[u8]| digits.iter().map(|digit| char::from(b'0' + digit)).collect::<String>();
|
|
378
|
+
let integer = text(&digits[..point]);
|
|
379
|
+
if precision == 0 {
|
|
380
|
+
format!("{sign}{integer}")
|
|
381
|
+
} else {
|
|
382
|
+
format!("{sign}{integer}.{}", text(&digits[point..]))
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/// Adds one unit in the last place of `digits`, carrying left.
|
|
387
|
+
fn round_up(digits: &mut Vec<u8>) {
|
|
388
|
+
for digit in digits.iter_mut().rev() {
|
|
389
|
+
if *digit == 9 {
|
|
390
|
+
*digit = 0;
|
|
391
|
+
} else {
|
|
392
|
+
*digit += 1;
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
digits.insert(0, 1);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/// `tens` in `missing/dtoa.c`: 1e0 to 1e22.
|
|
400
|
+
const TENS: [f64; 23] = [
|
|
401
|
+
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
|
|
402
|
+
1e20, 1e21, 1e22,
|
|
403
|
+
];
|
|
404
|
+
|
|
405
|
+
/// `bigtens` in `missing/dtoa.c`.
|
|
406
|
+
const BIG_TENS: [f64; 5] = [1e16, 1e32, 1e64, 1e128, 1e256];
|
|
407
|
+
|
|
408
|
+
/// Whether `BSD__dtoa(value, 3, ndigits)` (value positive) ends its
|
|
409
|
+
/// floating-point estimate with the rest within `eps` of one half and sets
|
|
410
|
+
/// `half`: the "Try to get by with floating-point arithmetic" block, with
|
|
411
|
+
/// the decimal exponent `k` estimated as `BSD__dtoa` does.
|
|
412
|
+
fn in_half_band(value: f64, ndigits: i32) -> bool {
|
|
413
|
+
let bits = value.to_bits();
|
|
414
|
+
let exponent_field = ((bits >> 52) & 0x7ff) as i32;
|
|
415
|
+
if value == 0.0 || exponent_field == 0 {
|
|
416
|
+
// Zero and subnormal numbers have no digits at two places.
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
let mantissa = f64::from_bits((bits & ((1 << 52) - 1)) | (1023 << 52));
|
|
420
|
+
// dtoa.c's own constants: log10(2) and its series for log10(1.5).
|
|
421
|
+
#[allow(clippy::approx_constant)]
|
|
422
|
+
let estimate = (mantissa - 1.5) * 0.289529654602168 + 0.1760912590558 + f64::from(exponent_field - 1023) * 0.301029995663981;
|
|
423
|
+
let mut k = estimate as i32;
|
|
424
|
+
if estimate < 0.0 && estimate != f64::from(k) {
|
|
425
|
+
k -= 1;
|
|
426
|
+
}
|
|
427
|
+
let mut k_check = true;
|
|
428
|
+
if (0..=22).contains(&k) {
|
|
429
|
+
if value < TENS[k as usize] {
|
|
430
|
+
k -= 1;
|
|
431
|
+
}
|
|
432
|
+
k_check = false;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Mode 3: `i = ndigits + k + 1; ilim = i; ilim1 = i - 1`; Quick_max is 14.
|
|
436
|
+
let mut ilim = ndigits + k + 1;
|
|
437
|
+
let ilim1 = ilim - 1;
|
|
438
|
+
if !(0..=14).contains(&ilim) {
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
let mut d = value;
|
|
443
|
+
let mut ieps = 2;
|
|
444
|
+
let mut big = 0;
|
|
445
|
+
if k > 0 {
|
|
446
|
+
let mut ds = TENS[(k & 0xf) as usize];
|
|
447
|
+
let mut j = k >> 4;
|
|
448
|
+
if j & 0x10 != 0 {
|
|
449
|
+
j &= 0x10 - 1;
|
|
450
|
+
d /= BIG_TENS[4];
|
|
451
|
+
ieps += 1;
|
|
452
|
+
}
|
|
453
|
+
while j != 0 {
|
|
454
|
+
if j & 1 != 0 {
|
|
455
|
+
ieps += 1;
|
|
456
|
+
ds *= BIG_TENS[big];
|
|
457
|
+
}
|
|
458
|
+
j >>= 1;
|
|
459
|
+
big += 1;
|
|
460
|
+
}
|
|
461
|
+
d /= ds;
|
|
462
|
+
} else if k < 0 {
|
|
463
|
+
let j1 = -k;
|
|
464
|
+
d *= TENS[(j1 & 0xf) as usize];
|
|
465
|
+
let mut j = j1 >> 4;
|
|
466
|
+
while j != 0 {
|
|
467
|
+
if j & 1 != 0 {
|
|
468
|
+
ieps += 1;
|
|
469
|
+
d *= BIG_TENS[big];
|
|
470
|
+
}
|
|
471
|
+
j >>= 1;
|
|
472
|
+
big += 1;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if k_check && d < 1.0 && ilim > 0 {
|
|
476
|
+
if ilim1 <= 0 {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
ilim = ilim1;
|
|
480
|
+
d *= 10.0;
|
|
481
|
+
ieps += 1;
|
|
482
|
+
}
|
|
483
|
+
// `eps = ieps*d + 7`, then `word0(eps) -= (P-1)*Exp_msk1`: divided by 2**52.
|
|
484
|
+
let mut eps = f64::from(ieps) * d + 7.0;
|
|
485
|
+
eps = f64::from_bits(eps.to_bits() - (52 << 52));
|
|
486
|
+
if ilim == 0 {
|
|
487
|
+
// Undecided here goes to the exact path without `half`.
|
|
488
|
+
return false;
|
|
489
|
+
}
|
|
490
|
+
eps *= TENS[(ilim - 1) as usize];
|
|
491
|
+
let mut i = 1;
|
|
492
|
+
loop {
|
|
493
|
+
let digit = d as i64;
|
|
494
|
+
d -= digit as f64;
|
|
495
|
+
if d == 0.0 {
|
|
496
|
+
ilim = i;
|
|
497
|
+
}
|
|
498
|
+
if i == ilim {
|
|
499
|
+
// Neither `d > 0.5 + eps` (bump up) nor `d < 0.5 - eps` (round
|
|
500
|
+
// down); `d` is never NaN.
|
|
501
|
+
return d <= 0.5 + eps && d >= 0.5 - eps;
|
|
502
|
+
}
|
|
503
|
+
i += 1;
|
|
504
|
+
d *= 10.0;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
#[cfg(test)]
|
|
509
|
+
mod tests {
|
|
510
|
+
use super::*;
|
|
511
|
+
|
|
512
|
+
#[test]
|
|
513
|
+
fn format_fixed_rounds_as_ruby() {
|
|
514
|
+
// `"%.2f" % v` in Ruby 3.3.
|
|
515
|
+
let cases = [
|
|
516
|
+
(0.125, "0.12"),
|
|
517
|
+
(0.375, "0.38"),
|
|
518
|
+
(2.675, "2.68"),
|
|
519
|
+
(1.005, "1.00"),
|
|
520
|
+
(123456.785, "123456.78"),
|
|
521
|
+
(0.5, "0.50"),
|
|
522
|
+
(99.995, "100.00"),
|
|
523
|
+
(0.004, "0.00"),
|
|
524
|
+
(0.005, "0.01"),
|
|
525
|
+
(0.0051, "0.01"),
|
|
526
|
+
(1e22, "10000000000000000000000.00"),
|
|
527
|
+
(32.0 / 3.0, "10.67"),
|
|
528
|
+
(0.0, "0.00"),
|
|
529
|
+
];
|
|
530
|
+
for (value, expected) in cases {
|
|
531
|
+
assert_eq!(format_fixed(value, 2), expected, "{value}");
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
#[test]
|
|
536
|
+
fn n_way_diff_collapses_shared_lines() {
|
|
537
|
+
let sources = [utf8("# a\ndef x\n 1\nend\n".to_string()), utf8("def x\n 2\nend".to_string())];
|
|
538
|
+
let diff = n_way_diff(&sources).unwrap();
|
|
539
|
+
assert_eq!(diff.bytes, b"A: # a\n def x\nA: 1\nB: 2\n end");
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
#[test]
|
|
543
|
+
fn group_letters_follow_integer_chr() {
|
|
544
|
+
assert_eq!(group_letter(0).unwrap().bytes, b"A");
|
|
545
|
+
let byte = group_letter(63).unwrap();
|
|
546
|
+
assert_eq!((byte.bytes.as_slice(), byte.encoding), (&[128u8][..], ASCII_8BIT));
|
|
547
|
+
assert_eq!(group_letter(191).unwrap_err().message, "256 out of char range");
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
#[test]
|
|
551
|
+
fn appending_follows_ruby_encoding_compatibility() {
|
|
552
|
+
let mut binary = RubyString::new([200u8], ASCII_8BIT);
|
|
553
|
+
append(&mut binary, &utf8("ascii".to_string())).unwrap();
|
|
554
|
+
assert_eq!(binary.encoding, ASCII_8BIT);
|
|
555
|
+
let error = append(&mut binary, &utf8("é".to_string())).unwrap_err();
|
|
556
|
+
assert_eq!(error.message, "incompatible character encodings: ASCII-8BIT and UTF-8");
|
|
557
|
+
let mut ascii = utf8("a".to_string());
|
|
558
|
+
append(&mut ascii, &RubyString::new([200u8], ASCII_8BIT)).unwrap();
|
|
559
|
+
assert_eq!(ascii.encoding, ASCII_8BIT);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
#[test]
|
|
563
|
+
fn symbols_inspect_as_ruby() {
|
|
564
|
+
assert_eq!(symbol_inspect(b"defn"), ":defn");
|
|
565
|
+
assert_eq!(symbol_inspect(b"op_asgn1"), ":op_asgn1");
|
|
566
|
+
}
|
|
567
|
+
}
|