Skip to content

Replace File::create and write_all with fs::write #82174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 17, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions compiler/rustc_driver/src/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ use rustc_span::symbol::Ident;
use rustc_span::FileName;

use std::cell::Cell;
use std::fs::File;
use std::io::Write;
use std::path::Path;

pub use self::PpMode::*;
Expand Down Expand Up @@ -375,13 +373,14 @@ fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
(src, src_name)
}

fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
fn write_or_print(out: &str, ofile: Option<&Path>) {
match ofile {
None => print!("{}", String::from_utf8(out).unwrap()),
Some(p) => match File::create(p) {
Ok(mut w) => w.write_all(&out).unwrap(),
Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
},
None => print!("{}", out),
Some(p) => {
if let Err(e) = std::fs::write(p, out) {
panic!("print-print failed to write {} due to {}", p.display(), e);
}
}
}
}

Expand Down Expand Up @@ -417,7 +416,7 @@ pub fn print_after_parsing(
unreachable!();
};

write_output(out.into_bytes(), ofile);
write_or_print(&out, ofile);
}

pub fn print_after_hir_lowering<'tcx>(
Expand Down Expand Up @@ -477,7 +476,7 @@ pub fn print_after_hir_lowering<'tcx>(
_ => unreachable!(),
}

write_output(out.into_bytes(), ofile);
write_or_print(&out, ofile);
}

// In an ideal world, this would be a public function called by the driver after
Expand All @@ -503,7 +502,8 @@ fn print_with_analysis(
}
.unwrap();

write_output(out, ofile);
let out = std::str::from_utf8(&out).unwrap();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just unwrap? Does this never fails? If that's they case why not just from_utf8_unchecked?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should never fail, but a future change may make it fail, in which case it is better to panic than to have silent UB.

write_or_print(out, ofile);

Ok(())
}