Skip to content

Commit

Permalink
fix: remove duplication of code to load stdlib files (noir-lang#2868)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomAFrench authored and Sakapoi committed Oct 19, 2023
1 parent e1150e8 commit 3f8bc9f
Showing 1 changed file with 28 additions and 31 deletions.
59 changes: 28 additions & 31 deletions compiler/fm/src/file_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
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<String> {
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};
Expand All @@ -33,42 +55,17 @@ cfg_if::cfg_if! {

}

pub(crate) fn read_file_to_string(path_to_file: &Path) -> Result<String, Error> {
fn get_non_stdlib_asset(path_to_file: &Path) -> std::io::Result<String> {
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<String, Error> {

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<String> {
std::fs::read_to_string(path_to_file)
}
}
}

0 comments on commit 3f8bc9f

Please sign in to comment.