-
Notifications
You must be signed in to change notification settings - Fork 104
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor to add abstraction around the JS source (#407)
* Add abstraction around the JS source * Add module documentation
- Loading branch information
1 parent
a5e14ce
commit bcbed2d
Showing
4 changed files
with
74 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
/// Higher-level representation of JavaScript. | ||
/// | ||
/// This is intended to be used to derive different representations of source | ||
/// code. For example, as a byte array, a string, QuickJS bytecode, compressed | ||
/// bytes, or attributes of the source code like what it exports. | ||
use anyhow::{Context, Result}; | ||
use brotli::enc::{self, BrotliEncoderParams}; | ||
use std::{ | ||
fs::File, | ||
io::{Cursor, Read}, | ||
path::Path, | ||
}; | ||
|
||
use crate::bytecode; | ||
|
||
pub struct JS { | ||
source_code: Vec<u8>, | ||
} | ||
|
||
impl JS { | ||
pub fn from_file(path: &Path) -> Result<JS> { | ||
let mut input_file = File::open(path) | ||
.with_context(|| format!("Failed to open input file {}", path.display()))?; | ||
let mut contents: Vec<u8> = vec![]; | ||
input_file.read_to_end(&mut contents)?; | ||
Ok(JS { | ||
source_code: contents, | ||
}) | ||
} | ||
|
||
pub fn as_bytes(&self) -> &[u8] { | ||
&self.source_code | ||
} | ||
|
||
pub fn compile(&self) -> Result<Vec<u8>> { | ||
bytecode::compile_source(&self.source_code) | ||
} | ||
|
||
pub fn compress(&self) -> Result<Vec<u8>> { | ||
let mut compressed_source_code: Vec<u8> = vec![]; | ||
enc::BrotliCompress( | ||
&mut Cursor::new(&self.source_code), | ||
&mut compressed_source_code, | ||
&BrotliEncoderParams { | ||
quality: 11, | ||
..Default::default() | ||
}, | ||
)?; | ||
Ok(compressed_source_code) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters