From 3f8bc9f37a22e2c3e2536136943ced2e5239bc18 Mon Sep 17 00:00:00 2001 From: Tom French <15848336+TomAFrench@users.noreply.github.com> Date: Wed, 27 Sep 2023 17:36:44 +0100 Subject: [PATCH] fix: remove duplication of code to load stdlib files (#2868) --- compiler/fm/src/file_reader.rs | 59 ++++++++++++++++------------------ 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/compiler/fm/src/file_reader.rs b/compiler/fm/src/file_reader.rs index 08df5abc349..6cf90734e18 100644 --- a/compiler/fm/src/file_reader.rs +++ b/compiler/fm/src/file_reader.rs @@ -21,6 +21,28 @@ pub(super) fn is_stdlib_asset(path: &Path) -> bool { path.starts_with("std/") } +fn get_stdlib_asset(path: &Path) -> std::io::Result { + if !is_stdlib_asset(path) { + return Err(Error::new(ErrorKind::InvalidInput, "requested a non-stdlib asset")); + } + + match StdLibAssets::get(path.to_str().unwrap()) { + Some(std_lib_asset) => { + Ok(std::str::from_utf8(std_lib_asset.data.as_ref()).unwrap().to_string()) + } + + None => Err(Error::new(ErrorKind::NotFound, "invalid stdlib path")), + } +} + +pub(crate) fn read_file_to_string(path_to_file: &Path) -> std::io::Result { + if is_stdlib_asset(path_to_file) { + get_stdlib_asset(path_to_file) + } else { + get_non_stdlib_asset(path_to_file) + } +} + cfg_if::cfg_if! { if #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] { use wasm_bindgen::{prelude::*, JsValue}; @@ -33,42 +55,17 @@ cfg_if::cfg_if! { } - pub(crate) fn read_file_to_string(path_to_file: &Path) -> Result { + fn get_non_stdlib_asset(path_to_file: &Path) -> std::io::Result { let path_str = path_to_file.to_str().unwrap(); - match StdLibAssets::get(path_str) { - - Some(std_lib_asset) => { - Ok(std::str::from_utf8(std_lib_asset.data.as_ref()).unwrap().to_string()) - }, - - None if is_stdlib_asset(path_to_file) => { - Err(Error::new(ErrorKind::NotFound, "invalid stdlib path")) - } - - None => match read_file(path_str) { - Ok(buffer) => Ok(buffer), - Err(_) => Err(Error::new(ErrorKind::Other, "could not read file using wasm")), - } - + match read_file(path_str) { + Ok(buffer) => Ok(buffer), + Err(_) => Err(Error::new(ErrorKind::Other, "could not read file using wasm")), } } } else { - pub(crate) fn read_file_to_string(path_to_file: &Path) -> Result { - - match StdLibAssets::get(path_to_file.to_str().unwrap()) { - - Some(std_lib_asset) => { - Ok(std::str::from_utf8(std_lib_asset.data.as_ref()).unwrap().to_string()) - }, - - None if is_stdlib_asset(path_to_file) => { - Err(Error::new(ErrorKind::NotFound, "invalid stdlib path")) - } - - None => std::fs::read_to_string(path_to_file) - - } + fn get_non_stdlib_asset(path_to_file: &Path) -> std::io::Result { + std::fs::read_to_string(path_to_file) } } }