1/* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17'use strict'; 18 19function rootCanalCalculateMessageSize(name, args) { 20 let result = 0; 21 22 result += 1 + name.length; // length of name + it's data 23 result += 1; // count of args 24 25 for (let i = 0; i < args.length; i++) { 26 result += 1; // length of args[i] 27 result += args[i].length; // data of args[i] 28 } 29 30 return result; 31} 32 33function rootCanalAddU8(array, pos, val) { 34 array[pos] = val & 0xff; 35 36 return pos + 1; 37} 38 39function rootCanalAddPayload(array, pos, payload) { 40 array.set(payload, pos); 41 42 return pos + payload.length; 43} 44 45function rootCanalAddString(array, pos, val) { 46 let curPos = pos; 47 48 curPos = rootCanalAddU8(array, curPos, val.length); 49 50 return rootCanalAddPayload(array, curPos, utf8Encoder.encode(val)); 51} 52 53function createRootcanalMessage(command, args) { 54 let messageSize = rootCanalCalculateMessageSize(command, args); 55 let arrayBuffer = new ArrayBuffer(messageSize); 56 let array = new Uint8Array(arrayBuffer); 57 let pos = 0; 58 59 pos = rootCanalAddString(array, pos, command); 60 pos = rootCanalAddU8(array, pos, args.length); 61 62 for (let i = 0; i < args.length; i++) { 63 pos = rootCanalAddString(array, pos, args[i]); 64 } 65 66 return array; 67} 68 69function decodeRootcanalMessage(array) { 70 let size = array[0]; 71 let message = array.slice(1); 72 73 return utf8Decoder.decode(message); 74} 75