1// Copyright (c) 2021 Huawei Device Co., Ltd.
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6//     http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from './utils/QueryEnum';
15import { threadPool } from '../SqlLite';
16import { TraceRow } from '../../component/trace/base/TraceRow';
17import { VirtualMemoryStruct } from '../ui-worker/ProcedureWorkerVirtualMemory';
18
19export function virtualMemoryDataSender(
20  filterId: number,
21  row: TraceRow<VirtualMemoryStruct>
22): Promise<VirtualMemoryStruct[]> {
23  let trafic: number = TraficEnum.Memory;
24  let width = row.clientWidth - CHART_OFFSET_LEFT;
25  if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) {
26    row.sharedArrayBuffers = {
27      filterID: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT),
28      value: new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * MAX_COUNT),
29      startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
30    };
31  }
32  return new Promise((resolve, reject) => {
33    threadPool.submitProto(
34      QueryEnum.VirtualMemoryData,
35      {
36        startNS: TraceRow.range?.startNS || 0,
37        endNS: TraceRow.range?.endNS || 0,
38        recordStartNS: window.recordStartNS,
39        recordEndNS: window.recordEndNS,
40        t: Date.now(),
41        width: width,
42        trafic: trafic,
43        filterId: filterId,
44        sharedArrayBuffers: row.sharedArrayBuffers,
45      },
46      (res: unknown, len: number, transfer: boolean) => {
47        resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len));
48      }
49    );
50  });
51}
52
53function arrayBufferHandler(buffers: unknown, len: number): VirtualMemoryStruct[] {
54  // @ts-ignore
55  let filterID = new Uint8Array(buffers.filterID); // @ts-ignore
56  let value = new Int32Array(buffers.value); // @ts-ignore
57  let startTime = new Float64Array(buffers.startTime);
58  let outArr: VirtualMemoryStruct[] = [];
59  for (let i = 0; i < len; i++) {
60    outArr.push({
61      filterID: filterID[i],
62      value: value[i],
63      startTime: startTime[i],
64    } as unknown as VirtualMemoryStruct);
65  }
66  return outArr;
67}
68