diff --git a/apps/oxfmt/src/cli/service.rs b/apps/oxfmt/src/cli/service.rs index ec2b51ef993fd..dea3651a88e70 100644 --- a/apps/oxfmt/src/cli/service.rs +++ b/apps/oxfmt/src/cli/service.rs @@ -1,4 +1,4 @@ -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::*; @@ -6,7 +6,7 @@ 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), @@ -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( @@ -105,19 +105,3 @@ impl FormatService { }); } } - -// --- - -fn read_to_string(path: &Path) -> io::Result { - // `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) }) -} diff --git a/apps/oxfmt/src/core/mod.rs b/apps/oxfmt/src/core/mod.rs index 684f60dea0abf..006f61abb5a90 100644 --- a/apps/oxfmt/src/core/mod.rs +++ b/apps/oxfmt/src/core/mod.rs @@ -1,5 +1,6 @@ mod format; mod support; +pub mod utils; #[cfg(feature = "napi")] mod external_formatter; diff --git a/apps/oxfmt/src/core/utils.rs b/apps/oxfmt/src/core/utils.rs new file mode 100644 index 0000000000000..72d23021af147 --- /dev/null +++ b/apps/oxfmt/src/core/utils.rs @@ -0,0 +1,15 @@ +use std::{fs, io, path::Path}; + +pub fn read_to_string(path: &Path) -> io::Result { + // `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) }) +}