Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

85 строки
2.3 KiB

  1. import { decode } from "@webassemblyjs/wasm-parser";
  2. import { traverse } from "@webassemblyjs/ast";
  3. import { cloneNode } from "@webassemblyjs/ast/lib/clone";
  4. import { shrinkPaddedLEB128 } from "@webassemblyjs/wasm-opt";
  5. import { getSectionForNode } from "@webassemblyjs/helper-wasm-bytecode";
  6. import constants from "@webassemblyjs/helper-wasm-bytecode";
  7. import { applyOperations } from "./apply";
  8. function hashNode(node) {
  9. return JSON.stringify(node);
  10. }
  11. function preprocess(ab) {
  12. var optBin = shrinkPaddedLEB128(new Uint8Array(ab));
  13. return optBin.buffer;
  14. }
  15. function sortBySectionOrder(nodes) {
  16. nodes.sort(function (a, b) {
  17. var sectionA = getSectionForNode(a);
  18. var sectionB = getSectionForNode(b);
  19. var aId = constants.sections[sectionA];
  20. var bId = constants.sections[sectionB];
  21. if (typeof aId !== "number" || typeof bId !== "number") {
  22. throw new Error("Section id not found");
  23. } // $FlowIgnore ensured above
  24. return aId > bId;
  25. });
  26. }
  27. export function edit(ab, visitors) {
  28. ab = preprocess(ab);
  29. var ast = decode(ab);
  30. return editWithAST(ast, ab, visitors);
  31. }
  32. export function editWithAST(ast, ab, visitors) {
  33. var operations = [];
  34. var uint8Buffer = new Uint8Array(ab);
  35. var nodeBefore;
  36. function before(type, path) {
  37. nodeBefore = cloneNode(path.node);
  38. }
  39. function after(type, path) {
  40. if (path.node._deleted === true) {
  41. operations.push({
  42. kind: "delete",
  43. node: path.node
  44. }); // $FlowIgnore
  45. } else if (hashNode(nodeBefore) !== hashNode(path.node)) {
  46. operations.push({
  47. kind: "update",
  48. oldNode: nodeBefore,
  49. node: path.node
  50. });
  51. }
  52. }
  53. traverse(ast, visitors, before, after);
  54. uint8Buffer = applyOperations(ast, uint8Buffer, operations);
  55. return uint8Buffer.buffer;
  56. }
  57. export function add(ab, newNodes) {
  58. ab = preprocess(ab);
  59. var ast = decode(ab);
  60. return addWithAST(ast, ab, newNodes);
  61. }
  62. export function addWithAST(ast, ab, newNodes) {
  63. // Sort nodes by insertion order
  64. sortBySectionOrder(newNodes);
  65. var uint8Buffer = new Uint8Array(ab); // Map node into operations
  66. var operations = newNodes.map(function (n) {
  67. return {
  68. kind: "add",
  69. node: n
  70. };
  71. });
  72. uint8Buffer = applyOperations(ast, uint8Buffer, operations);
  73. return uint8Buffer.buffer;
  74. }