Bzip2Compress.mjs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @author Matt C [me@mitt.dev]
  3. * @copyright Crown Copyright 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import OperationError from "../errors/OperationError.mjs";
  8. import Bzip2 from "libbzip2-wasm";
  9. import { isWorkerEnvironment } from "../Utils.mjs";
  10. /**
  11. * Bzip2 Compress operation
  12. */
  13. class Bzip2Compress extends Operation {
  14. /**
  15. * Bzip2Compress constructor
  16. */
  17. constructor() {
  18. super();
  19. this.name = "Bzip2 Compress";
  20. this.module = "Compression";
  21. this.description = "Bzip2 is a compression library developed by Julian Seward (of GHC fame) that uses the Burrows-Wheeler algorithm. It only supports compressing single files and its compression is slow, however is more effective than Deflate (.gz & .zip).";
  22. this.infoURL = "https://wikipedia.org/wiki/Bzip2";
  23. this.inputType = "ArrayBuffer";
  24. this.outputType = "ArrayBuffer";
  25. this.args = [
  26. {
  27. name: "Block size (100s of kb)",
  28. type: "number",
  29. value: 9,
  30. min: 1,
  31. max: 9
  32. },
  33. {
  34. name: "Work factor",
  35. type: "number",
  36. value: 30
  37. }
  38. ];
  39. }
  40. /**
  41. * @param {ArrayBuffer} input
  42. * @param {Object[]} args
  43. * @returns {File}
  44. */
  45. run(input, args) {
  46. const [blockSize, workFactor] = args;
  47. if (input.byteLength <= 0) {
  48. throw new OperationError("Please provide an input.");
  49. }
  50. if (isWorkerEnvironment()) self.sendStatusMessage("Loading Bzip2...");
  51. return new Promise((resolve, reject) => {
  52. Bzip2().then(bzip2 => {
  53. if (isWorkerEnvironment()) self.sendStatusMessage("Compressing data...");
  54. const inpArray = new Uint8Array(input);
  55. const bzip2cc = bzip2.compressBZ2(inpArray, blockSize, workFactor);
  56. if (bzip2cc.error !== 0) {
  57. reject(new OperationError(bzip2cc.error_msg));
  58. } else {
  59. const output = bzip2cc.output;
  60. resolve(output.buffer.slice(output.byteOffset, output.byteLength + output.byteOffset));
  61. }
  62. });
  63. });
  64. }
  65. }
  66. export default Bzip2Compress;