فهرست منبع

Fix Node <10 support

Arjun Barrett 4 سال پیش
والد
کامیت
88b9e689e5
5فایلهای تغییر یافته به همراه70 افزوده شده و 33 حذف شده
  1. 6 1
      package.json
  2. 20 11
      rs/fflate-wasm/src/lib.rs
  3. 26 15
      rs/fflate/src/lib.rs
  4. 4 2
      src/index.ts
  5. 14 4
      src/node-worker.ts

+ 6 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "fflate",
-  "version": "0.4.2",
+  "version": "0.4.3",
   "description": "High performance (de)compression in an 8kB package",
   "main": "./lib/index.js",
   "module": "./esm/index.mjs",
@@ -20,6 +20,10 @@
   "sideEffects": false,
   "homepage": "https://101arrowz.github.io/fflate",
   "repository": "https://github.com/101arrowz/fflate",
+  "bugs": {
+    "email": "[email protected]",
+    "url": "https://github.com/101arrowz/fflate/issues"
+  },
   "author": "Arjun Barrett",
   "license": "MIT",
   "keywords": [
@@ -35,6 +39,7 @@
     "browser",
     "node.js",
     "tiny",
+    "fast",
     "zip",
     "unzip",
     "non-blocking"

+ 20 - 11
rs/fflate-wasm/src/lib.rs

@@ -1,16 +1,25 @@
 use wasm_bindgen::prelude::*;
-use fflate::{inflate, InflateError};
+use fflate;
 
 #[wasm_bindgen]
-pub fn inflate_raw(buf: &[u8]) -> Result<Vec<u8>, JsValue> {
-    let mut out = Vec::new();
-    if let Err(e) = inflate(buf, &mut out) {
-        return Err(JsValue::from(match e {
-            InflateError::InvalidBlockType => "invalid block type",
-            InflateError::InvalidDistance => "invalid distance",
-            InflateError::InvalidLengthOrLiteral => "invalid length/literal",
-            InflateError::UnexpectedEOF => "unexpected EOF"
-        }));
+pub struct Inflate {
+    buf: &'static Vec<u8>,
+    inflator: fflate::Inflate<'static>
+}
+
+#[wasm_bindgen]
+impl Inflate {
+    #[wasm_bindgen(constructor)]
+    pub fn new() -> Inflate {
+        unsafe {
+            static mut buf: Vec<u8> = Vec::new();
+            Inflate {
+                buf: &buf,
+                inflator: fflate::Inflate::new(&mut buf)
+            }
+        }
+    }
+    pub fn push(&mut self, dat: &[u8], last: bool) -> Result<> {
+        self.inflator.write_all(dat);
     }
-    Ok(out)
 }

+ 26 - 15
rs/fflate/src/lib.rs

@@ -230,6 +230,21 @@ pub enum InflateError {
     InvalidDistance
 }
 
+#[cfg(feature = "std")]
+impl From<InflateError> for Error {
+    fn from(error: InflateError) -> Self {
+        Error::new(match error {
+            InflateError::UnexpectedEOF => ErrorKind::UnexpectedEof,
+            _ => ErrorKind::Other
+        }, match error {
+            InflateError::UnexpectedEOF => "unexpected EOF",
+            InflateError::InvalidBlockType => "invalid block type",
+            InflateError::InvalidLengthOrLiteral => "invalid length/literal",
+            InflateError::InvalidDistance => "invalid distance"
+        })
+    }
+}
+
 pub trait OutputBuffer {
     fn w(&mut self, value: u8);
     fn wall(&mut self, slice: &[u8]) {
@@ -490,18 +505,14 @@ impl<'a> Inflate<'a> {
     }
 }
 
-// #[cfg(feature = "std")]
-// impl<'a> Write for Inflate<'a> {
-//     #[inline(always)]
-//     fn write(&mut self, data: &[u8]) -> Result<usize, Error> {
-//         self.push(data)
-//     }
-//     #[inline(always)]
-//     fn flush(&mut self) -> Result<(), Error> {
-//         match self.end() {
-//             Err(InflateError::UnexpectedEOF) => Err(Error::new(ErrorKind::UnexpectedEof, InflateError::UnexpectedEOF)),
-//             Err(e) => Err(Error::new(ErrorKind::Other, &e)),
-//             Ok(()) => Ok(())
-//         }
-//     }
-// }
+#[cfg(feature = "std")]
+impl<'a> Write for Inflate<'a> {
+    #[inline(always)]
+    fn write(&mut self, data: &[u8]) -> Result<usize, Error> {
+        Ok(self.push(data)?)
+    }
+    #[inline(always)]
+    fn flush(&mut self) -> Result<(), Error> {
+        Ok(self.end()?)
+    }
+}

+ 4 - 2
src/index.ts

@@ -864,8 +864,10 @@ const wcln = (fn: () => unknown[], fnStr: string, td: Record<string, unknown>) =
       const st = v.toString();
       if (v.prototype) {
         // for global objects
-        if (st.indexOf('[native code]') != -1) fnStr += st.slice(9, st.indexOf('(', 11))
-        else {
+        if (st.indexOf('[native code]') != -1) {
+          const spInd = st.indexOf(' ', 8) + 1;
+          fnStr += st.slice(spInd, st.indexOf('(', spInd));
+        } else {
           fnStr += st;
           for (const t in v.prototype) fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString();
         }

+ 14 - 4
src/node-worker.ts

@@ -1,15 +1,18 @@
 // Mediocre shim
-import { Worker } from 'worker_threads';
-
+let Worker: typeof import('worker_threads').Worker;
 const workerAdd = ";var __w=require('worker_threads');__w.parentPort.on('message',function(m){onmessage({data:m})}),postMessage=function(m,t){__w.parentPort.postMessage(m,t)},close=process.exit;self=global";
 
-export default <T>(c: string, _: number, msg: unknown, transfer: ArrayBuffer[], cb: (err: Error, msg: T) => void) => {
+try {
+  Worker = require('worker_threads').Worker;
+} catch(e) {
+}
+export default Worker ? <T>(c: string, _: number, msg: unknown, transfer: ArrayBuffer[], cb: (err: Error, msg: T) => void) => {
   let done = false;
   const w = new Worker(c + workerAdd, { eval: true })
     .on('error', e => cb(e, null))
     .on('message', m => cb(null, m))
     .on('exit', c => {
-      if (c && !done) cb(new Error('Exited with code ' + c), null);
+      if (c && !done) cb(new Error('exited with code ' + c), null);
     });
   w.postMessage(msg, transfer);
   w.terminate = () => {
@@ -17,4 +20,11 @@ export default <T>(c: string, _: number, msg: unknown, transfer: ArrayBuffer[],
     return Worker.prototype.terminate.call(w);
   }
   return w;
+} : (_: string, __: number, ___: unknown, ____: ArrayBuffer[], cb: (err: Error, msg: null) => void) => {
+  setImmediate(() => cb(new Error('async operations unsupported - update to Node 12+ (or Node 10-11 with the --experimental-worker CLI flag)'), null));
+  const NOP = () => {};
+  return {
+    terminate: NOP,
+    postMessage: NOP
+  } as unknown as import('worker_threads').Worker;
 }