Skip to content
Merged
Show file tree
Hide file tree
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: 3 additions & 19 deletions apps/oxfmt/src/cli/service.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::{fs, io, path::Path, sync::mpsc, time::Instant};
use std::{fs, path::Path, sync::mpsc, time::Instant};

use cow_utils::CowUtils;
use rayon::prelude::*;

use oxc_diagnostics::{DiagnosticSender, DiagnosticService};

use super::command::OutputOptions;
use crate::core::{FormatFileSource, FormatResult, SourceFormatter};
use crate::core::{FormatFileSource, FormatResult, SourceFormatter, utils};

pub enum SuccessResult {
Changed(String),
Expand Down Expand Up @@ -38,7 +38,7 @@ impl FormatService {
let start_time = Instant::now();

let path = entry.path();
let Ok(source_text) = read_to_string(path) else {
let Ok(source_text) = utils::read_to_string(path) else {
// This happens if binary file is attempted to be formatted
// e.g. `.ts` for MPEG-TS video file
let diagnostics = DiagnosticService::wrap_diagnostics(
Expand Down Expand Up @@ -105,19 +105,3 @@ impl FormatService {
});
}
}

// ---

fn read_to_string(path: &Path) -> io::Result<String> {
// `simdutf8` is faster than `std::str::from_utf8` which `fs::read_to_string` uses internally
let bytes = fs::read(path)?;
if simdutf8::basic::from_utf8(&bytes).is_err() {
// Same error as `fs::read_to_string` produces (using `io::ErrorKind::InvalidData`)
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
));
}
// SAFETY: `simdutf8` has ensured it's a valid UTF-8 string
Ok(unsafe { String::from_utf8_unchecked(bytes) })
}
1 change: 1 addition & 0 deletions apps/oxfmt/src/core/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod format;
mod support;
pub mod utils;

#[cfg(feature = "napi")]
mod external_formatter;
Expand Down
15 changes: 15 additions & 0 deletions apps/oxfmt/src/core/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use std::{fs, io, path::Path};

pub fn read_to_string(path: &Path) -> io::Result<String> {
// `simdutf8` is faster than `std::str::from_utf8` which `fs::read_to_string` uses internally
let bytes = fs::read(path)?;
if simdutf8::basic::from_utf8(&bytes).is_err() {
// Same error as `fs::read_to_string` produces (using `io::ErrorKind::InvalidData`)
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
));
}
// SAFETY: `simdutf8` has ensured it's a valid UTF-8 string
Ok(unsafe { String::from_utf8_unchecked(bytes) })
}
Loading