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(new Uint8Array([ 44 194, 45 161, 46 72, 47 195, 48 169, 49 108, 50 108, 51 195, 52 152, 53 32, 54 119, 55 195, 56 182, 57 114, 58 108, 59 100, 60 33 61 ])); 62 expect(utf8Decode(buffer)).toEqual(testString); 63}); 64 65test('string_utils.binaryEncodeAndDecode', () => { 66 const buf = new Uint8Array(256 + 4); 67 for (let i = 0; i < 256; i++) { 68 buf[i] = i; 69 } 70 buf.set([0xf0, 0x28, 0x8c, 0xbc], 256); 71 const encodedStr = binaryEncode(buf); 72 expect(encodedStr.length).toEqual(buf.length); 73 const encodedThroughJson = JSON.parse(JSON.stringify(encodedStr)); 74 expect(binaryDecode(encodedStr)).toEqual(buf); 75 expect(binaryDecode(encodedThroughJson)).toEqual(buf); 76}); 77 78test('string_utils.sqliteString', () => { 79 expect(sqliteString('that\'s it')).toEqual('\'that\'\'s it\''); 80 expect(sqliteString('no quotes')).toEqual('\'no quotes\''); 81}); 82