1/* 2 * Copyright (c) 2022-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 16import { int32 } from "@koalaui/common" 17 18export type ResourceId = int32 19 20interface ResourceInfo { 21 resource: object 22 holdersCount: int32 23} 24 25export class ResourceHolder { 26 private static nextResourceId: ResourceId = 100 27 private resources: Map<ResourceId, ResourceInfo> = new Map<ResourceId, ResourceInfo>() 28 private static _instance: ResourceHolder|undefined = undefined 29 static instance(): ResourceHolder { 30 if (ResourceHolder._instance == undefined) { 31 ResourceHolder._instance = new ResourceHolder() 32 } 33 return ResourceHolder._instance! 34 } 35 36 public hold(resourceId: ResourceId) { 37 if (!this.resources.has(resourceId)) 38 throw new Error(`Resource ${resourceId} does not exists, can not hold`) 39 this.resources.get(resourceId)!.holdersCount++ 40 } 41 42 public release(resourceId: ResourceId) { 43 if (!this.resources.has(resourceId)) 44 throw new Error(`Resource ${resourceId} does not exists, can not release`) 45 const resource = this.resources.get(resourceId)! 46 resource.holdersCount-- 47 if (resource.holdersCount <= 0) 48 this.resources.delete(resourceId) 49 } 50 51 public registerAndHold(resource: object): ResourceId { 52 const resourceId = ResourceHolder.nextResourceId++ 53 this.resources.set(resourceId, { 54 resource: resource, 55 holdersCount: 1, 56 }) 57 return resourceId 58 } 59 60 public get(resourceId: ResourceId): object { 61 if (!this.resources.has(resourceId)) 62 throw new Error(`Resource ${resourceId} does not exists`) 63 return this.resources.get(resourceId)!.resource 64 } 65 66 public has(resourceId: ResourceId): boolean { 67 return this.resources.has(resourceId) 68 } 69} 70