1// Copyright (C) 2019 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import { 16 decode as b64Decode, 17 encode as b64Encode, 18 length as b64Len, 19} from '@protobufjs/base64'; 20import { 21 length as utf8Len, 22 read as utf8Read, 23 write as utf8Write, 24} from '@protobufjs/utf8'; 25 26import {assertTrue} from './logging'; 27 28// TextDecoder/Decoder requires the full DOM and isn't available in all types 29// of tests. Use fallback implementation from protbufjs. 30let Utf8Decoder: {decode: (buf: Uint8Array) => string;}; 31let Utf8Encoder: {encode: (str: string) => Uint8Array;}; 32try { 33 Utf8Decoder = new TextDecoder('utf-8'); 34 Utf8Encoder = new TextEncoder(); 35} catch (_) { 36 if (typeof process === 'undefined') { 37 // Silence the warning when we know we are running under NodeJS. 38 console.warn( 39 'Using fallback UTF8 Encoder/Decoder, This should happen only in ' + 40 'tests and NodeJS-based environments, not in browsers.'); 41 } 42 Utf8Decoder = {decode: (buf: Uint8Array) => utf8Read(buf, 0, buf.length)}; 43 Utf8Encoder = { 44 encode: (str: string) => { 45 const arr = new Uint8Array(utf8Len(str)); 46 const written = utf8Write(str, arr, 0); 47 assertTrue(written === arr.length); 48 return arr; 49 }, 50 }; 51} 52 53export function base64Encode(buffer: Uint8Array): string { 54 return b64Encode(buffer, 0, buffer.length); 55} 56 57export function base64Decode(str: string): Uint8Array { 58 // if the string is in base64url format, convert to base64 59 const b64 = str.replace(/-/g, '+').replace(/_/g, '/'); 60 const arr = new Uint8Array(b64Len(b64)); 61 const written = b64Decode(b64, arr, 0); 62 assertTrue(written === arr.length); 63 return arr; 64} 65 66// encode binary array to hex string 67export function hexEncode(bytes: Uint8Array): string { 68 return bytes.reduce( 69 (prev, cur) => prev + ('0' + cur.toString(16)).slice(-2), ''); 70} 71 72export function utf8Encode(str: string): Uint8Array { 73 return Utf8Encoder.encode(str); 74} 75 76// Note: not all byte sequences can be converted to<>from UTF8. This can be 77// used only with valid unicode strings, not arbitrary byte buffers. 78export function utf8Decode(buffer: Uint8Array): string { 79 return Utf8Decoder.decode(buffer); 80} 81 82// The binaryEncode/Decode functions below allow to encode an arbitrary binary 83// buffer into a string that can be JSON-encoded. binaryEncode() applies 84// UTF-16 encoding to each byte individually. 85// Unlike utf8Encode/Decode, any arbitrary byte sequence can be converted into a 86// valid string, and viceversa. 87// This should be only used when a byte array needs to be transmitted over an 88// interface that supports only JSON serialization (e.g., postmessage to a 89// chrome extension). 90 91export function binaryEncode(buf: Uint8Array): string { 92 let str = ''; 93 for (let i = 0; i < buf.length; i++) { 94 str += String.fromCharCode(buf[i]); 95 } 96 return str; 97} 98 99export function binaryDecode(str: string): Uint8Array { 100 const buf = new Uint8Array(str.length); 101 const strLen = str.length; 102 for (let i = 0; i < strLen; i++) { 103 buf[i] = str.charCodeAt(i); 104 } 105 return buf; 106} 107 108// A function used to interpolate strings into SQL query. The only replacement 109// is done is that single quote replaced with two single quotes, according to 110// SQLite documentation: 111// https://www.sqlite.org/lang_expr.html#literal_values_constants_ 112// 113// The purpose of this function is to use in simple comparisons, to escape 114// strings used in GLOB clauses see escapeQuery function. 115export function sqliteString(str: string): string { 116 return `'${str.replace(/'/g, '\'\'')}'`; 117} 118