microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
playground/src/utils.ts
45lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | // Utility functions to convert source code to and from base64. |
| 5 | // |
| 6 | // The btoa function expects a string of bytes (i.e. in the range x00 - xFF), however |
| 7 | // as the code may contain UTF-16 code units outside this range, it needs to be converted |
| 8 | // first. If you just encodeUriComponent the whole string, it will blow up considerably as |
| 9 | // all spaces and newlines (common chars in code) become %20 and %0A (so 4 spaces and a newline |
| 10 | // and up being 15 chars) whereas base64 encoding those 5 chars in ASCII is just 'ICAgIAo' (i.e. |
| 11 | // 7 bytes, or less then half the size). |
| 12 | // |
| 13 | // The below functions simply convert the source to utf-8 bytes first (and as most source code |
| 14 | // is ASCII this is usually a one-to-one mapping), and then base64 encodes/decodes the utf-8 |
| 15 | // bytes. In testing this results in an encoding about half the size of other methods. |
| 16 | |
| 17 | export function codeToBase64(code: string): string { |
| 18 | // Convert to utf=8 |
| 19 | const myencoder = new TextEncoder(); |
| 20 | const buff = myencoder.encode(code); |
| 21 | |
| 22 | // Create a string of the utf-8 code units (so each will be <= 0xFF) |
| 23 | let binStr = ""; |
| 24 | for (const unit of buff) { |
| 25 | binStr += String.fromCharCode(unit); |
| 26 | } |
| 27 | |
| 28 | // Convert that to base64 |
| 29 | const base64String = window.btoa(binStr); |
| 30 | return base64String; |
| 31 | } |
| 32 | |
| 33 | export function base64ToCode(b64: string): string { |
| 34 | // Get the binary string of utf-8 code units |
| 35 | const binStr = window.atob(b64); |
| 36 | |
| 37 | // Create the Uint8Array from it |
| 38 | const byteArray = new Uint8Array(binStr.length); |
| 39 | for (let i = 0; i < binStr.length; ++i) byteArray[i] = binStr.charCodeAt(i); |
| 40 | |
| 41 | // Decode the utf-8 bytes into a JavaScript string |
| 42 | const decoder = new TextDecoder(); |
| 43 | const code = decoder.decode(byteArray); |
| 44 | return code; |
| 45 | } |
| 46 | |