Skip to content

Commit d691701

Browse files
committedApr 4, 2025·
fix(various): unwrap Result of write! macro (#10228)
#10196 replaced the anti-pattern of `str.push_str(&format!("..."));` with `let _ = write!(str, "...");`. However, this ignores the `Result` returned by `write!` macro. It's unspecified what happens when the `String` reaches capacity - it may return `Result::Err`, or may panic. Ensure we get a panic, rather than silently generating incorrect output by calling `unwrap()` on the `Result`. This problem could never arise in practice on 64-bit systems because max capacity of `String` is enormous, but it's not impossible on 32-bit systems (e.g. WASM).
1 parent 5995349 commit d691701

File tree

7 files changed

+27
-24
lines changed

7 files changed

+27
-24
lines changed
 

Diff for: ‎apps/oxlint/src/output_formatter/stylish.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ fn format_stylish(diagnostics: &[Error]) -> String {
7272
.max()
7373
.unwrap_or(0);
7474

75-
let _ = write!(output, "\n\u{1b}[4m{filename}\u{1b}[0m\n");
75+
writeln!(output, "\n\u{1b}[4m{filename}\u{1b}[0m").unwrap();
7676

7777
for diagnostic in diagnostics {
7878
match diagnostic.severity() {
@@ -89,23 +89,23 @@ fn format_stylish(diagnostics: &[Error]) -> String {
8989
let info = Info::new(diagnostic);
9090
let rule = diagnostic.code().map_or_else(String::new, |code| code.to_string());
9191
let position = format!("{}:{}", info.start.line, info.start.column);
92-
let _ = writeln!(
92+
writeln!(
9393
output,
9494
" \u{1b}[2m{position:max_len_width$}\u{1b}[0m {severity_str} {diagnostic} \u{1b}[2m{rule}\u{1b}[0m"
95-
);
95+
).unwrap();
9696
}
9797
}
9898

9999
let total = total_errors + total_warnings;
100100
if total > 0 {
101101
let summary_color = if total_errors > 0 { "\u{1b}[31m" } else { "\u{1b}[33m" };
102-
let _ = writeln!(
102+
writeln!(
103103
output,
104104
"\n{summary_color}✖ {total} problem{} ({total_errors} error{}, {total_warnings} warning{})\u{1b}[0m",
105105
if total == 1 { "" } else { "s" },
106106
if total_errors == 1 { "" } else { "s" },
107107
if total_warnings == 1 { "" } else { "s" }
108-
);
108+
).unwrap();
109109
}
110110

111111
output

Diff for: ‎crates/oxc_isolated_declarations/tests/mod.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,11 @@ fn transform(path: &Path, source_text: &str) -> String {
2828
.map(|d| d.clone().with_source_code(Arc::clone(&source)))
2929
.fold(String::new(), |s, error| s + &format!("{error:?}"));
3030

31-
let _ = write!(
31+
write!(
3232
snapshot,
3333
"==================== Errors ====================\n{error_messages}\n\n```"
34-
);
34+
)
35+
.unwrap();
3536
}
3637

3738
snapshot

Diff for: ‎crates/oxc_language_server/src/linter/tester.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ fn get_snapshot_from_report(report: &DiagnosticReport) -> String {
3131
.enumerate()
3232
.map(|(i, info)| {
3333
let mut result = String::new();
34-
let _ =
35-
write!(result, "related_information[{}].message: {:?}", i, info.message);
34+
write!(result, "related_information[{}].message: {:?}", i, info.message)
35+
.unwrap();
3636
// replace everything between `file://` and `oxc_language_server` with `<variable>`, to avoid
3737
// the absolute path causing snapshot test failures in different environments
3838
let mut location = info.location.uri.to_string();
@@ -46,13 +46,14 @@ fn get_snapshot_from_report(report: &DiagnosticReport) -> String {
4646
"<variable>",
4747
);
4848

49-
let _ =
50-
write!(result, "\nrelated_information[{i}].location.uri: {location:?}",);
51-
let _ = write!(
49+
write!(result, "\nrelated_information[{i}].location.uri: {location:?}",)
50+
.unwrap();
51+
write!(
5252
result,
5353
"\nrelated_information[{}].location.range: {:?}",
5454
i, info.location.range
55-
);
55+
)
56+
.unwrap();
5657
result
5758
})
5859
.collect::<Vec<_>>()

Diff for: ‎crates/oxc_linter/src/rules/typescript/consistent_type_imports.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -285,9 +285,9 @@ fn format_word_list<'a>(words: &[Cow<'a, str>]) -> Cow<'a, str> {
285285
let mut result = String::with_capacity(words.len() * 2);
286286
for (i, word) in words.iter().enumerate() {
287287
if i == words.len() - 1 {
288-
let _ = write!(result, "and {word}");
288+
write!(result, "and {word}").unwrap();
289289
} else {
290-
let _ = write!(result, "{word}, ");
290+
write!(result, "{word}, ").unwrap();
291291
}
292292
}
293293
Cow::Owned(result)

Diff for: ‎tasks/minsize/src/lib.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub fn run() -> Result<(), io::Error> {
6868
let mut out = String::new();
6969

7070
let width = 10;
71-
let _ = writeln!(
71+
writeln!(
7272
out,
7373
"{:width$} | {:width$} | {:width$} | {:width$} | {:width$} |",
7474
"",
@@ -77,8 +77,9 @@ pub fn run() -> Result<(), io::Error> {
7777
"Oxc",
7878
"ESBuild",
7979
width = width,
80-
);
81-
let _ = writeln!(
80+
)
81+
.unwrap();
82+
writeln!(
8283
out,
8384
"{:width$} | {:width$} | {:width$} | {:width$} | {:width$} | Fixture",
8485
"Original",
@@ -87,7 +88,8 @@ pub fn run() -> Result<(), io::Error> {
8788
"gzip",
8889
"gzip",
8990
width = width,
90-
);
91+
)
92+
.unwrap();
9193

9294
let fixture_width = files
9395
.files()

Diff for: ‎tasks/prettier_conformance/src/lib.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -89,14 +89,15 @@ impl TestRunner {
8989
total_failed_file_count += failed_test_files.len();
9090

9191
for (path, (failed, passed, ratio)) in failed_test_files {
92-
let _ = writeln!(
92+
writeln!(
9393
failed_reports,
9494
"| {} | {}{} | {:.2}% |",
9595
path.strip_prefix(fixtures_root()).unwrap().to_string_lossy(),
9696
"💥".repeat(failed),
9797
"✨".repeat(passed),
9898
ratio * 100.0
99-
);
99+
)
100+
.unwrap();
100101
}
101102
}
102103

Diff for: ‎tasks/transform_conformance/src/lib.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,7 @@ impl TestRunner {
155155
if failed.is_empty() {
156156
all_passed.push(case);
157157
} else {
158-
snapshot.push_str("# ");
159-
snapshot.push_str(&case);
160-
let _ = writeln!(snapshot, " ({}/{})", passed.len(), num_of_tests);
158+
writeln!(snapshot, "# {case} ({}/{})", passed.len(), num_of_tests).unwrap();
161159
for test_case in failed {
162160
if self.options.r#override {
163161
test_case.write_override_output();

0 commit comments

Comments
 (0)
Please sign in to comment.