flog-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,307 @@
1
+ //! Flog 4.10.0's complexity scores, computed directly from Prism's syntax tree.
2
+ //!
3
+ //! [`score_source`] scores one file. [`Flog`] merges file results in input
4
+ //! order the way one `Flog` instance does when given several files, then
5
+ //! computes totals with the same floating-point operations in the same order.
6
+
7
+ mod attach_comments;
8
+ mod literal;
9
+ pub mod ruby_format;
10
+ pub mod ruby_sort;
11
+ mod scorer;
12
+ pub mod scores;
13
+ mod syntax_error;
14
+ mod translation;
15
+
16
+ use indexmap::IndexMap;
17
+
18
+ pub use scorer::FlogException;
19
+ pub use syntax_error::{handle_syntax_error, SyntaxErrorException, SyntaxErrorHandling};
20
+ use scorer::{Scorer, Tallies};
21
+
22
+ /// The Flog version whose numbers this crate reproduces.
23
+ pub const FLOG_COMPAT: &str = "4.10.0";
24
+
25
+ /// `Flog::DEFAULT_THRESHOLD`.
26
+ pub const DEFAULT_THRESHOLD: f64 = 0.60;
27
+
28
+ /// What happened to one file.
29
+ #[derive(Clone, Debug, PartialEq)]
30
+ pub enum FileOutcome {
31
+ /// The file was parsed and scored (an empty file scores nothing).
32
+ Scored,
33
+ /// The file could not be read; Flog skips it without a message
34
+ /// (`next unless File.readable? file`).
35
+ Unreadable,
36
+ /// Prism reported a parse error. Flog raises
37
+ /// `RubyParser::SyntaxError, "file:line :: message"`, then skips the file
38
+ /// when `continue` is set or the error looks like an ERB template.
39
+ SyntaxError { message: String, looks_like_erb: bool },
40
+ /// Flog raised an exception while scoring. Points added before the
41
+ /// exception are kept, as they are in Flog.
42
+ Raised(FlogException),
43
+ }
44
+
45
+ /// One file's scores, before merging.
46
+ #[derive(Clone, Debug)]
47
+ pub struct FileResult {
48
+ pub path: String,
49
+ pub outcome: FileOutcome,
50
+ calls: Tallies,
51
+ method_locations: IndexMap<String, String>,
52
+ }
53
+
54
+ impl FileResult {
55
+ /// Labels in first-seen order with their tallies, summed in Flog's order.
56
+ pub fn calls(&self) -> IndexMap<&str, IndexMap<&str, f64>> {
57
+ self.calls
58
+ .iter()
59
+ .map(|(label, tally)| {
60
+ let summed = tally
61
+ .iter()
62
+ .map(|(name, additions)| (name.as_str(), sum_additions(0.0, additions)))
63
+ .collect();
64
+ (label.as_str(), summed)
65
+ })
66
+ .collect()
67
+ }
68
+
69
+ pub fn method_locations(&self) -> &IndexMap<String, String> {
70
+ &self.method_locations
71
+ }
72
+
73
+ /// Each label's tally with every individual addition, in Flog's order.
74
+ /// Replaying these additions onto running sums merges files exactly as
75
+ /// one Flog instance would.
76
+ pub fn additions(&self) -> &IndexMap<String, IndexMap<String, Vec<f64>>> {
77
+ &self.calls
78
+ }
79
+ }
80
+
81
+ fn sum_additions(start: f64, additions: &[f64]) -> f64 {
82
+ additions.iter().fold(start, |sum, addition| sum + addition)
83
+ }
84
+
85
+ /// The Prism syntax version that `Prism.parse` uses by default under the
86
+ /// given Ruby version (`RUBY_VERSION`). Prism's default, "nearest", is the
87
+ /// running Ruby's own syntax, 3.3 for older Rubies, and the latest syntax for
88
+ /// Rubies newer than Prism knows. `"latest"` selects the latest syntax.
89
+ ///
90
+ /// Flog's scores depend on this: under Ruby 3.3, `it` in a block is a method
91
+ /// call (scored); under 3.4 it is a block parameter (not scored).
92
+ pub fn syntax_version_for_ruby(ruby_version: &str) -> ruby_prism::Version {
93
+ use ruby_prism::Version;
94
+ let mut parts = ruby_version.split('.');
95
+ let major_minor = (parts.next(), parts.next());
96
+ match major_minor {
97
+ (Some("3"), Some("3")) => Version::CRuby3_3,
98
+ (Some("3"), Some("4")) => Version::CRuby3_4,
99
+ (Some("3"), Some("5")) | (Some("4"), Some("0")) => Version::CRuby4_0,
100
+ (Some("4"), Some("1")) => Version::CRuby4_1,
101
+ _ if ruby_version != "latest" && ruby_version < "3.3" => Version::CRuby3_3,
102
+ _ => Version::Latest,
103
+ }
104
+ }
105
+
106
+ /// Scores Ruby source the way `Flog#flog_ruby` does. `path` is used for
107
+ /// method locations and `__FILE__`. `methods_only` is Flog's `methods`
108
+ /// option: points scored outside a method are dropped. `ruby_version` is the
109
+ /// `RUBY_VERSION` Flog would run under (see [`syntax_version_for_ruby`]).
110
+ pub fn score_source(source: &[u8], path: &str, methods_only: bool, ruby_version: &str) -> FileResult {
111
+ let options = ruby_prism::Options::default()
112
+ .filepath(path)
113
+ .partial_script(true)
114
+ .version(syntax_version_for_ruby(ruby_version))
115
+ .build();
116
+ let parse_result = ruby_prism::parse_with_options(source, &options);
117
+
118
+ if let Some(error) = parse_result.errors().next() {
119
+ // Prism::Translation::RubyParser#translate raises on the first error.
120
+ let message = format!(
121
+ "{}:{} :: {}",
122
+ path,
123
+ error.location().start_line(),
124
+ String::from_utf8_lossy(error.message())
125
+ );
126
+ let looks_like_erb = contains_erb_marker(message.as_bytes()) || contains_erb_marker(source);
127
+ return FileResult {
128
+ path: path.to_string(),
129
+ outcome: FileOutcome::SyntaxError { message, looks_like_erb },
130
+ calls: Tallies::new(),
131
+ method_locations: IndexMap::new(),
132
+ };
133
+ }
134
+
135
+ // Translation raises before Flog scores anything.
136
+ if let Some(exception) = attach_comments::attach_comments_exception(source, &parse_result) {
137
+ return FileResult {
138
+ path: path.to_string(),
139
+ outcome: FileOutcome::Raised(exception),
140
+ calls: Tallies::new(),
141
+ method_locations: IndexMap::new(),
142
+ };
143
+ }
144
+
145
+ let mut scorer = Scorer::new(path, methods_only);
146
+ scorer.score_program(&parse_result.node());
147
+ let outcome = match scorer.exception.take() {
148
+ Some(exception) => FileOutcome::Raised(exception),
149
+ None => FileOutcome::Scored,
150
+ };
151
+ FileResult { path: path.to_string(), outcome, calls: scorer.calls, method_locations: scorer.method_locations }
152
+ }
153
+
154
+ /// `e.inspect =~ /<\%|%\>/ or ruby =~ /<\%|%\>/` in `Flog#flog_ruby`.
155
+ fn contains_erb_marker(bytes: &[u8]) -> bool {
156
+ bytes.windows(2).any(|pair| pair == b"<%" || pair == b"%>")
157
+ }
158
+
159
+ /// Reads and scores a file. A file that can't be read is `Unreadable`.
160
+ pub fn score_file(path: &str, methods_only: bool, ruby_version: &str) -> FileResult {
161
+ match std::fs::read(path) {
162
+ Ok(source) => score_source(&source, path, methods_only, ruby_version),
163
+ Err(_) => FileResult {
164
+ path: path.to_string(),
165
+ outcome: FileOutcome::Unreadable,
166
+ calls: Tallies::new(),
167
+ method_locations: IndexMap::new(),
168
+ },
169
+ }
170
+ }
171
+
172
+ /// The results of one `Flog` instance across files, merged in input order.
173
+ #[derive(Clone, Debug, Default)]
174
+ pub struct Flog {
175
+ calls: IndexMap<String, IndexMap<String, f64>>,
176
+ method_locations: IndexMap<String, String>,
177
+ totals: Option<IndexMap<String, f64>>,
178
+ total_score: f64,
179
+ }
180
+
181
+ impl Flog {
182
+ pub fn new() -> Self {
183
+ Self::default()
184
+ }
185
+
186
+ /// `Flog#reset`.
187
+ pub fn reset(&mut self) {
188
+ *self = Self::default();
189
+ }
190
+
191
+ /// Adds one file's results as if Flog had processed the file next: each
192
+ /// addition is replayed onto the running sums, and the file's method
193
+ /// locations replace earlier ones with the same label.
194
+ pub fn merge(&mut self, result: &FileResult) {
195
+ for (label, tally) in &result.calls {
196
+ let merged = self.calls.entry(label.clone()).or_default();
197
+ for (name, additions) in tally {
198
+ let sum = merged.entry(name.clone()).or_insert(0.0);
199
+ *sum = sum_additions(*sum, additions);
200
+ }
201
+ }
202
+ for (label, location) in &result.method_locations {
203
+ self.method_locations.insert(label.clone(), location.clone());
204
+ }
205
+ }
206
+
207
+ /// `Flog#calculate_total_scores`. Like Flog, does nothing once totals
208
+ /// exist until `reset`.
209
+ pub fn calculate_total_scores(&mut self) {
210
+ if self.totals.is_some() {
211
+ return;
212
+ }
213
+ let mut totals = IndexMap::new();
214
+ let mut total_score = 0.0;
215
+ for (label, tally) in &self.calls {
216
+ let score = scores::score_method(tally.iter().map(|(name, value)| (name.as_str(), *value)));
217
+ totals.insert(label.clone(), score);
218
+ total_score += score;
219
+ }
220
+ self.totals = Some(totals);
221
+ self.total_score = total_score;
222
+ }
223
+
224
+ pub fn calls(&self) -> &IndexMap<String, IndexMap<String, f64>> {
225
+ &self.calls
226
+ }
227
+
228
+ pub fn method_locations(&self) -> &IndexMap<String, String> {
229
+ &self.method_locations
230
+ }
231
+
232
+ /// `Flog#totals`, or `None` before `calculate_total_scores`.
233
+ pub fn totals(&self) -> Option<&IndexMap<String, f64>> {
234
+ self.totals.as_ref()
235
+ }
236
+
237
+ /// `Flog#total_score`. Flog's value is the Integer 0 when there are no
238
+ /// methods; callers that need that distinction check `calls().is_empty()`.
239
+ pub fn total_score(&self) -> f64 {
240
+ self.total_score
241
+ }
242
+
243
+ /// The labels and scores `Flog#each_by_score(max)` yields: from the
244
+ /// highest score down, with equal scores in the order Ruby's `sort_by`
245
+ /// leaves them, ending with the label whose score brings the sum of
246
+ /// yielded scores to `max` (when `max` is given).
247
+ ///
248
+ /// Panics before `calculate_total_scores`, where Flog raises
249
+ /// `NoMethodError` on `nil`.
250
+ pub fn each_by_score(&self, max: Option<f64>) -> Vec<(&str, f64)> {
251
+ let totals = self.totals.as_ref().expect("each_by_score called before calculate_total_scores");
252
+ let scores: Vec<(&str, f64)> = self.calls.keys().map(|label| (label.as_str(), totals[label])).collect();
253
+ let keys: Vec<f64> = scores.iter().map(|(_, score)| -score).collect();
254
+
255
+ let mut yielded = Vec::with_capacity(scores.len());
256
+ let mut current = 0.0;
257
+ for index in ruby_sort::sort_by_numeric_keys(&keys) {
258
+ yielded.push(scores[index]);
259
+ current += scores[index].1;
260
+ if max.is_some_and(|max| current >= max) {
261
+ break;
262
+ }
263
+ }
264
+ yielded
265
+ }
266
+ }
267
+
268
+ #[cfg(test)]
269
+ mod tests {
270
+ use super::*;
271
+
272
+ const SOURCE: &[u8] = b"class A\n def one\n a\n end\n\n def three\n a; b; c\n end\n\n def two\n a; b\n end\nend\n";
273
+
274
+ fn flog() -> Flog {
275
+ let mut flog = Flog::new();
276
+ flog.merge(&score_source(SOURCE, "a.rb", true, "3.4.0"));
277
+ flog.calculate_total_scores();
278
+ flog
279
+ }
280
+
281
+ fn labels<'a>(yielded: &[(&'a str, f64)]) -> Vec<&'a str> {
282
+ yielded.iter().map(|(label, _)| *label).collect()
283
+ }
284
+
285
+ #[test]
286
+ fn each_by_score_yields_from_the_highest_score_down() {
287
+ let flog = flog();
288
+ let yielded = flog.each_by_score(None);
289
+ assert_eq!(labels(&yielded), ["A#three", "A#two", "A#one"]);
290
+ let totals = flog.totals().unwrap();
291
+ assert!(yielded.iter().all(|(label, score)| totals[*label] == *score));
292
+ }
293
+
294
+ #[test]
295
+ fn each_by_score_stops_once_the_yielded_scores_reach_max() {
296
+ let flog = flog();
297
+ let three = flog.totals().unwrap()["A#three"];
298
+ assert_eq!(labels(&flog.each_by_score(Some(three))), ["A#three"]);
299
+ assert_eq!(labels(&flog.each_by_score(Some(three + 0.1))), ["A#three", "A#two"]);
300
+ }
301
+
302
+ #[test]
303
+ #[should_panic(expected = "calculate_total_scores")]
304
+ fn each_by_score_panics_before_totals() {
305
+ Flog::new().each_by_score(None);
306
+ }
307
+ }
@@ -0,0 +1,217 @@
1
+ //! Literal values Flog reads: whether a number is 0 or -1 (`process_lit`), and
2
+ //! the text of a named block's first argument (`dsl_name?` and `in_method`).
3
+
4
+ use ruby_prism::Node;
5
+
6
+ use crate::ruby_format::{float_to_s, integer_to_s};
7
+ use crate::translation::{interpolated_string_value, range_is_literal, string_value, transparent_child};
8
+
9
+ /// `process_lit` skips numbers equal to 0 or -1 (`when 0, -1`), which also
10
+ /// matches 0.0, -1.0, 0r, -1r and 0i because the comparison is `==`.
11
+ pub fn is_zero_or_minus_one(node: &Node<'_>) -> bool {
12
+ match node {
13
+ Node::IntegerNode { .. } => {
14
+ let (negative, limbs) = integer_digits(node.as_integer_node().unwrap().value());
15
+ integer_is(negative, &limbs, 0) || integer_is(negative, &limbs, -1)
16
+ }
17
+ Node::FloatNode { .. } => {
18
+ let value = node.as_float_node().unwrap().value();
19
+ value == 0.0 || value == -1.0
20
+ }
21
+ Node::RationalNode { .. } => {
22
+ let rational = node.as_rational_node().unwrap();
23
+ let (numerator_negative, numerator) = integer_digits(rational.numerator());
24
+ let (_, denominator) = integer_digits(rational.denominator());
25
+ let numerator_is_zero = numerator.iter().all(|limb| *limb == 0);
26
+ let numerator_is_minus_denominator =
27
+ numerator_negative && trimmed(&numerator) == trimmed(&denominator);
28
+ numerator_is_zero || numerator_is_minus_denominator
29
+ }
30
+ // Complex(0, x) == 0 only when x == 0; it never equals -1.
31
+ Node::ImaginaryNode { .. } => {
32
+ let numeric = node.as_imaginary_node().unwrap().numeric();
33
+ numeric_is_zero(&numeric)
34
+ }
35
+ _ => false,
36
+ }
37
+ }
38
+
39
+ fn numeric_is_zero(node: &Node<'_>) -> bool {
40
+ match node {
41
+ Node::IntegerNode { .. } => {
42
+ let (negative, limbs) = integer_digits(node.as_integer_node().unwrap().value());
43
+ integer_is(negative, &limbs, 0)
44
+ }
45
+ Node::FloatNode { .. } => node.as_float_node().unwrap().value() == 0.0,
46
+ Node::RationalNode { .. } => {
47
+ let (_, numerator) = integer_digits(node.as_rational_node().unwrap().numerator());
48
+ numerator.iter().all(|limb| *limb == 0)
49
+ }
50
+ _ => false,
51
+ }
52
+ }
53
+
54
+ /// A Prism integer's sign and little-endian base 2**32 digits.
55
+ fn integer_digits(value: ruby_prism::Integer<'_>) -> (bool, Vec<u32>) {
56
+ let (negative, limbs) = value.to_u32_digits();
57
+ (negative, limbs.to_vec())
58
+ }
59
+
60
+ fn trimmed(limbs: &[u32]) -> &[u32] {
61
+ let mut end = limbs.len();
62
+ while end > 1 && limbs[end - 1] == 0 {
63
+ end -= 1;
64
+ }
65
+ &limbs[..end]
66
+ }
67
+
68
+ fn integer_is(negative: bool, limbs: &[u32], target: i64) -> bool {
69
+ let limbs = trimmed(limbs);
70
+ match target {
71
+ 0 => limbs.iter().all(|limb| *limb == 0),
72
+ -1 => negative && limbs == [1],
73
+ _ => unreachable!("only 0 and -1 are compared"),
74
+ }
75
+ }
76
+
77
+ /// The value `dsl_name?` returns for a block's first argument, as the text
78
+ /// `in_method` uses for the method name (`name.to_s`, or `inspect` for a
79
+ /// Regexp).
80
+ pub struct DslName {
81
+ pub text: String,
82
+ /// `process_iter` adds `(name)` to the class name only for String and
83
+ /// Symbol values.
84
+ pub is_string_or_symbol: bool,
85
+ }
86
+
87
+ /// `dsl_name?` for one argument: the value of a `:lit` or `:str` sexp, after
88
+ /// taking a hash's first key.
89
+ pub fn dsl_name(first_argument: &Node<'_>, in_pattern: bool) -> Option<DslName> {
90
+ match first_argument {
91
+ Node::HashNode { .. } | Node::KeywordHashNode { .. } => {
92
+ let elements = match first_argument {
93
+ Node::HashNode { .. } => first_argument.as_hash_node().unwrap().elements(),
94
+ _ => first_argument.as_keyword_hash_node().unwrap().elements(),
95
+ };
96
+ // `first_arg[1]` is the first key, or the kwsplat sexp for `**h`.
97
+ let assoc = elements.first()?.as_assoc_node()?;
98
+ literal_text(&assoc.key(), in_pattern)
99
+ }
100
+ _ => literal_text(first_argument, in_pattern),
101
+ }
102
+ }
103
+
104
+ fn literal_text(node: &Node<'_>, in_pattern: bool) -> Option<DslName> {
105
+ let string_or_symbol = |bytes: &[u8]| DslName {
106
+ text: String::from_utf8_lossy(bytes).into_owned(),
107
+ is_string_or_symbol: true,
108
+ };
109
+ let other = |text: String| DslName { text, is_string_or_symbol: false };
110
+
111
+ match node {
112
+ Node::SymbolNode { .. } => Some(string_or_symbol(node.as_symbol_node().unwrap().unescaped())),
113
+ Node::InterpolatedSymbolNode { .. } => {
114
+ let parts = node.as_interpolated_symbol_node().unwrap().parts();
115
+ interpolated_string_value(&parts).map(|bytes| string_or_symbol(&bytes))
116
+ }
117
+ Node::StringNode { .. } | Node::InterpolatedStringNode { .. } | Node::SourceFileNode { .. } => {
118
+ string_value(node).map(|bytes| string_or_symbol(&bytes))
119
+ }
120
+ Node::IntegerNode { .. } => {
121
+ let (negative, limbs) = integer_digits(node.as_integer_node().unwrap().value());
122
+ Some(other(integer_to_s(negative, &limbs)))
123
+ }
124
+ Node::FloatNode { .. } => Some(other(float_to_s(node.as_float_node().unwrap().value()))),
125
+ Node::RationalNode { .. } => {
126
+ let rational = node.as_rational_node().unwrap();
127
+ let (negative, numerator) = integer_digits(rational.numerator());
128
+ let (_, denominator) = integer_digits(rational.denominator());
129
+ Some(other(format!(
130
+ "{}/{}",
131
+ integer_to_s(negative, &numerator),
132
+ integer_to_s(false, &denominator)
133
+ )))
134
+ }
135
+ Node::ImaginaryNode { .. } => {
136
+ let numeric = node.as_imaginary_node().unwrap().numeric();
137
+ let imaginary = literal_text(&numeric, in_pattern)?.text;
138
+ Some(other(format!("0+{imaginary}i")))
139
+ }
140
+ Node::RegularExpressionNode { .. } => {
141
+ let regexp = node.as_regular_expression_node().unwrap();
142
+ Some(other(regexp_inspect(
143
+ regexp.unescaped(),
144
+ regexp.is_multi_line(),
145
+ regexp.is_ignore_case(),
146
+ regexp.is_extended(),
147
+ )))
148
+ }
149
+ Node::RangeNode { .. } => {
150
+ let range = node.as_range_node().unwrap();
151
+ if !range_is_literal(&range, in_pattern) {
152
+ return None;
153
+ }
154
+ let bound = |bound: Option<Node<'_>>| match bound {
155
+ Some(integer @ Node::IntegerNode { .. }) => literal_text(&integer, in_pattern)
156
+ .map(|name| name.text)
157
+ .unwrap_or_default(),
158
+ _ => String::new(),
159
+ };
160
+ let operator = if range.is_exclude_end() { "..." } else { ".." };
161
+ Some(other(format!("{}{}{}", bound(range.left()), operator, bound(range.right()))))
162
+ }
163
+ Node::SourceLineNode { .. } => Some(other(node.location().start_line().to_string())),
164
+ _ => transparent_child(node).and_then(|child| literal_text(&child, in_pattern)),
165
+ }
166
+ }
167
+
168
+ /// `Regexp#inspect` for the translator's `Regexp.new(node.unescaped,
169
+ /// node.options)`: `/source/` plus the `m`, `i` and `x` flags in that order.
170
+ fn regexp_inspect(unescaped: &[u8], multi_line: bool, ignore_case: bool, extended: bool) -> String {
171
+ let source = String::from_utf8_lossy(unescaped);
172
+ let mut text = String::from("/");
173
+ if source.bytes().any(|byte| byte == b'/' || (byte.is_ascii() && !is_ascii_print(byte))) {
174
+ push_escaped_regexp_source(&mut text, &source);
175
+ } else {
176
+ text.push_str(&source);
177
+ }
178
+ text.push('/');
179
+ if multi_line {
180
+ text.push('m');
181
+ }
182
+ if ignore_case {
183
+ text.push('i');
184
+ }
185
+ if extended {
186
+ text.push('x');
187
+ }
188
+ text
189
+ }
190
+
191
+ /// The escaping `Regexp#inspect` applies (`rb_reg_expr_str`) once the source
192
+ /// holds a `/` or a non-printable ASCII character: a backslash and the
193
+ /// character after it are kept, `/` becomes `\/`, other non-printable ASCII
194
+ /// characters except whitespace become `\xHH`, and non-ASCII characters
195
+ /// become `\uHHHH` or `\u{H...}`.
196
+ fn push_escaped_regexp_source(text: &mut String, source: &str) {
197
+ let mut chars = source.chars();
198
+ while let Some(c) = chars.next() {
199
+ match c {
200
+ '\\' => {
201
+ text.push(c);
202
+ if let Some(escaped) = chars.next() {
203
+ text.push(escaped);
204
+ }
205
+ }
206
+ '/' => text.push_str("\\/"),
207
+ ' '..='~' | '\t' | '\n' | '\u{0b}' | '\u{0c}' | '\r' => text.push(c),
208
+ '\0'..='\u{7f}' => text.push_str(&format!("\\x{:02X}", c as u32)),
209
+ '\u{80}'..='\u{ffff}' => text.push_str(&format!("\\u{:04X}", c as u32)),
210
+ _ => text.push_str(&format!("\\u{{{:X}}}", c as u32)),
211
+ }
212
+ }
213
+ }
214
+
215
+ fn is_ascii_print(byte: u8) -> bool {
216
+ (b' '..=b'~').contains(&byte)
217
+ }
@@ -0,0 +1,131 @@
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
+ #[cfg(test)]
100
+ mod tests {
101
+ use super::*;
102
+
103
+ #[test]
104
+ fn float_to_s_matches_ruby() {
105
+ assert_eq!(float_to_s(1.0), "1.0");
106
+ assert_eq!(float_to_s(1.1), "1.1");
107
+ assert_eq!(float_to_s(0.25), "0.25");
108
+ assert_eq!(float_to_s(1.2000000000000002), "1.2000000000000002");
109
+ assert_eq!(float_to_s(100.0), "100.0");
110
+ assert_eq!(float_to_s(1e15), "1.0e+15");
111
+ assert_eq!(float_to_s(1e14), "100000000000000.0");
112
+ assert_eq!(float_to_s(1234567890123456.8), "1234567890123456.8");
113
+ assert_eq!(float_to_s(0.00015000000000000001), "0.00015000000000000001");
114
+ assert_eq!(float_to_s(1e16), "1.0e+16");
115
+ assert_eq!(float_to_s(1.5e16), "1.5e+16");
116
+ assert_eq!(float_to_s(9999999999999998.0), "9.999999999999998e+15");
117
+ assert_eq!(float_to_s(0.0001), "0.0001");
118
+ assert_eq!(float_to_s(0.00001), "1.0e-05");
119
+ assert_eq!(float_to_s(0.000123), "0.000123");
120
+ assert_eq!(float_to_s(-2.5), "-2.5");
121
+ assert_eq!(float_to_s(0.0), "0.0");
122
+ }
123
+
124
+ #[test]
125
+ fn integer_to_s_handles_bignums() {
126
+ assert_eq!(integer_to_s(false, &[0]), "0");
127
+ assert_eq!(integer_to_s(true, &[1]), "-1");
128
+ assert_eq!(integer_to_s(false, &[0, 1]), "4294967296");
129
+ assert_eq!(integer_to_s(false, &[0x3B9A_CA00]), "1000000000");
130
+ }
131
+ }