lenstr3.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>WASM test</title>
  6. </head>
  7. <body>
  8. <script type="module">
  9. // allow use of async/await
  10. (async () => {
  11. // Build the WebAssembly instance.
  12. const memory = new WebAssembly.Memory({ initial: 2 });
  13. const response = await fetch('lenstr.wasm');
  14. const bytes = await response.arrayBuffer();
  15. const { instance } = await WebAssembly.instantiate(bytes, {
  16. env: { memory }
  17. });
  18. // Text to copy.
  19. const text = 'Hello from wasm sfg.c!';
  20. // Configure shared memory.
  21. const view = new Uint8Array(memory.buffer);
  22. const pInput = instance.exports.__heap_base;
  23. const pOutput = pInput + 1024;
  24. encode(view, pInput, text);
  25. // run our own strlen()
  26. const bytesCopied = instance.exports.lenstr(pInput);
  27. console.log('text.length is ', text.length);
  28. console.log('lenstr() length is ', bytesCopied);
  29. console.log('input string is ', decode(view, pInput));
  30. })();
  31. // Encode string into memory starting at address base.
  32. const encode = (memory, base, string) => {
  33. for (let i = 0; i < string.length; i++) {
  34. memory[base + i] = string.charCodeAt(i);
  35. }
  36. memory[base + string.length] = 0;
  37. };
  38. // Decode a string from memory starting at address base.
  39. const decode = (memory, base) => {
  40. let cursor = base;
  41. let result = '';
  42. while (memory[cursor] !== 0) {
  43. result += String.fromCharCode(memory[cursor++]);
  44. }
  45. return result;
  46. };
  47. </script>
  48. </body>
  49. </html>