arraybuffer.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { converse } from '@converse/headless';
  2. const { u } = converse.env;
  3. export function appendArrayBuffer (buffer1, buffer2) {
  4. const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
  5. tmp.set(new Uint8Array(buffer1), 0);
  6. tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
  7. return tmp.buffer;
  8. }
  9. export function arrayBufferToHex (ab) {
  10. // https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex#40031979
  11. return Array.prototype.map.call(new Uint8Array(ab), x => ('00' + x.toString(16)).slice(-2)).join('');
  12. }
  13. export function arrayBufferToString (ab) {
  14. return new TextDecoder("utf-8").decode(ab);
  15. }
  16. export function stringToArrayBuffer (string) {
  17. const bytes = new TextEncoder("utf-8").encode(string);
  18. return bytes.buffer;
  19. }
  20. export function arrayBufferToBase64 (ab) {
  21. return btoa((new Uint8Array(ab)).reduce((data, byte) => data + String.fromCharCode(byte), ''));
  22. }
  23. export function base64ToArrayBuffer (b64) {
  24. const binary_string = window.atob(b64),
  25. len = binary_string.length,
  26. bytes = new Uint8Array(len);
  27. for (let i = 0; i < len; i++) {
  28. bytes[i] = binary_string.charCodeAt(i)
  29. }
  30. return bytes.buffer
  31. }
  32. export function hexToArrayBuffer (hex) {
  33. const typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)))
  34. return typedArray.buffer
  35. }
  36. Object.assign(u, { arrayBufferToHex, arrayBufferToString, stringToArrayBuffer, arrayBufferToBase64, base64ToArrayBuffer });