idlize
76 строк · 2.3 Кб
1/*
2* Copyright (c) 2024 Huawei Device Co., Ltd.
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*/
15
16import { int32 } from "@koalaui/common"17
18export type CallbackType = (args: Uint8Array, length: int32) => int3219
20class CallbackRecord {21constructor(22public readonly callback: CallbackType,23public readonly autoDisposable: boolean24) { }25}
26
27class CallbackRegistry {28
29static INSTANCE = new CallbackRegistry()30
31private callbacks = new Map<int32, CallbackRecord>()32private id = 133
34constructor() {35this.callbacks.set(0, new CallbackRecord(36(args: Uint8Array, length: int32): int32 => {37console.log(`Callback 0 called with args = ${args} and length = ${length}`)38throw new Error(`Null callback called`)39}, false)40)41}42
43wrap(callback: CallbackType, autoDisposable: boolean): int32 {44const id = this.id++45this.callbacks.set(id, new CallbackRecord(callback, autoDisposable))46return id47}48
49call(id: int32, args: Uint8Array, length: int32): int32 {50const record = this.callbacks.get(id)51if (!record) {52console.log(`Callback ${id} is not known`)53throw new Error(`Disposed or unwrapped callback called (id = ${id})`)54}55if (record.autoDisposable) {56this.dispose(id)57}58return record.callback(args, length)59}60
61dispose(id: int32) {62this.callbacks.delete(id)63}64}
65
66export function wrapCallback(callback: CallbackType, autoDisposable: boolean = true): int32 {67return CallbackRegistry.INSTANCE.wrap(callback, autoDisposable)68}
69
70export function disposeCallback(id: int32) {71CallbackRegistry.INSTANCE.dispose(id)72}
73
74export function callCallback(id: int32, args: Uint8Array, length: int32): int32 {75return CallbackRegistry.INSTANCE.call(id, args, length)76}