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