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 base64Decode, 17 base64Encode, 18 binaryDecode, 19 binaryEncode, 20 sqliteString, 21 utf8Decode, 22 utf8Encode, 23} from './string_utils'; 24 25test('string_utils.stringToBase64', () => { 26 const bytes = [...'Hello, world'].map((c) => c.charCodeAt(0)); 27 const buffer = new Uint8Array(bytes); 28 const b64Encoded = base64Encode(buffer); 29 expect(b64Encoded).toEqual('SGVsbG8sIHdvcmxk'); 30 expect(base64Decode(b64Encoded)).toEqual(buffer); 31}); 32 33test('string_utils.bufferToBase64', () => { 34 const buffer = new Uint8Array([0xff, 0, 0, 0x81, 0x2a, 0xfe]); 35 const b64Encoded = base64Encode(buffer); 36 expect(b64Encoded).toEqual('/wAAgSr+'); 37 expect(base64Decode(b64Encoded)).toEqual(buffer); 38}); 39 40test('string_utils.utf8EncodeAndDecode', () => { 41 const testString = '¡HéllØ wörld!'; 42 const buffer = utf8Encode(testString); 43 expect(buffer).toEqual( 44 new Uint8Array([ 45 194, 161, 72, 195, 169, 108, 108, 195, 152, 32, 119, 195, 182, 114, 108, 46 100, 33, 47 ]), 48 ); 49 expect(utf8Decode(buffer)).toEqual(testString); 50}); 51 52test('string_utils.binaryEncodeAndDecode', () => { 53 const buf = new Uint8Array(256 + 4); 54 for (let i = 0; i < 256; i++) { 55 buf[i] = i; 56 } 57 buf.set([0xf0, 0x28, 0x8c, 0xbc], 256); 58 const encodedStr = binaryEncode(buf); 59 expect(encodedStr.length).toEqual(buf.length); 60 const encodedThroughJson = JSON.parse(JSON.stringify(encodedStr)); 61 expect(binaryDecode(encodedStr)).toEqual(buf); 62 expect(binaryDecode(encodedThroughJson)).toEqual(buf); 63}); 64 65test('string_utils.sqliteString', () => { 66 expect(sqliteString("that's it")).toEqual("'that''s it'"); 67 expect(sqliteString('no quotes')).toEqual("'no quotes'"); 68 expect(sqliteString(`foo ' bar '`)).toEqual(`'foo '' bar '''`); 69}); 70