1// @ts-check 2/** 3 * @param {string} message 4 * @returns {never} 5 */ 6function fail(message) { 7 throw new Error(message); 8} 9 10/** 11 * @param {number} value 12 */ 13function base64FormatEncode(value) { 14 return value < 0 ? fail("Invalid value") : 15 value < 26 ? 0x41 /*A*/ + value : 16 value < 52 ? 0x61 /*a*/ + value - 26 : 17 value < 62 ? 0x30 /*0*/ + value - 52 : 18 value === 62 ? 0x2B /*+*/ : 19 value === 63 ? 0x2F /*/*/ : 20 fail("Invalid value"); 21} 22 23/** 24 * @param {number} value 25 */ 26function base64VLQFormatEncode(value) { 27 if (value < 0) { 28 value = ((-value) << 1) + 1; 29 } 30 else { 31 value = value << 1; 32 } 33 34 // Encode 5 bits at a time starting from least significant bits 35 let result = ""; 36 do { 37 let currentDigit = value & 31; // 11111 38 value = value >> 5; 39 if (value > 0) { 40 // There are still more digits to decode, set the msb (6th bit) 41 currentDigit = currentDigit | 32; 42 } 43 result += String.fromCharCode(base64FormatEncode(currentDigit)); 44 } while (value > 0); 45 46 return result; 47} 48exports.base64VLQFormatEncode = base64VLQFormatEncode;