1 /* 2 * Copyright (c) 2025 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 package org.koalaui.interop; 16 17 import java.util.Arrays; 18 import java.util.HashMap; 19 20 class CallbackRegistry { 21 22 private static HashMap<Integer, CallbackRecord> callbacks = new HashMap<Integer, CallbackRecord>(); 23 private static Integer id = 0; 24 25 static { CallbackRegistry.callbacks.put(id, new CallbackRecord( new CallbackType() { @Override public int apply(byte[] args, int length) { System.out.printf("Callback 0 called with args = %s and length = %d\\n", Arrays.toString(args), length); throw new Error("Null callback called"); } }, false) )26 CallbackRegistry.callbacks.put(id, new CallbackRecord( 27 new CallbackType() { 28 @Override 29 public int apply(byte[] args, int length) { 30 System.out.printf("Callback 0 called with args = %s and length = %d\n", Arrays.toString(args), length); 31 throw new Error("Null callback called"); 32 } 33 }, false) 34 ); 35 CallbackRegistry.id++; 36 } 37 CallbackRegistry()38 private CallbackRegistry() { 39 40 } 41 wrap(CallbackType callback)42 public static Integer wrap(CallbackType callback) { 43 Integer tmpId = CallbackRegistry.id++; 44 CallbackRegistry.callbacks.put(tmpId, new CallbackRecord(callback, true)); 45 return tmpId; 46 } 47 wrap(CallbackType callback, boolean autoDisposable)48 public static Integer wrap(CallbackType callback, boolean autoDisposable) { 49 Integer tmpId = CallbackRegistry.id++; 50 CallbackRegistry.callbacks.put(tmpId, new CallbackRecord(callback, autoDisposable)); 51 return tmpId; 52 } 53 call(Integer id, byte[] args, int length)54 public static int call(Integer id, byte[] args, int length) { 55 if (!CallbackRegistry.callbacks.containsKey(id)) { 56 System.out.printf("Callback %d is not known\n", id); 57 throw new Error(String.format("Disposed or unwrapped callback called (id = %d)", id)); 58 } 59 CallbackRecord record = CallbackRegistry.callbacks.get(id); 60 if (record.autoDisposable) { 61 CallbackRegistry.dispose(id); 62 } 63 return record.callback.apply(args, length); 64 } 65 dispose(Integer id)66 public static void dispose(Integer id) { 67 CallbackRegistry.callbacks.remove(id); 68 } 69 } 70