Path: blob/main/src/vs/editor/browser/widget/multiDiffEditor/objectPool.ts
3296 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/4import { IDisposable, IReference } from '../../../../base/common/lifecycle.js';56export class ObjectPool<TData extends IObjectData, T extends IPooledObject<TData>> implements IDisposable {7private readonly _unused = new Set<T>();8private readonly _used = new Set<T>();9private readonly _itemData = new Map<T, TData>();1011constructor(12private readonly _create: (data: TData) => T,13) { }1415public getUnusedObj(data: TData): IReference<T> {16let obj: T;1718if (this._unused.size === 0) {19obj = this._create(data);20this._itemData.set(obj, data);21} else {22const values = [...this._unused.values()];23obj = values.find(obj => this._itemData.get(obj)!.getId() === data.getId()) ?? values[0];24this._unused.delete(obj);25this._itemData.set(obj, data);26obj.setData(data);27}28this._used.add(obj);29return {30object: obj,31dispose: () => {32this._used.delete(obj);33if (this._unused.size > 5) {34obj.dispose();35} else {36this._unused.add(obj);37}38}39};40}4142dispose(): void {43for (const obj of this._used) {44obj.dispose();45}46for (const obj of this._unused) {47obj.dispose();48}49this._used.clear();50this._unused.clear();51}52}5354export interface IObjectData {55getId(): unknown;56}5758export interface IPooledObject<TData> extends IDisposable {59setData(data: TData): void;60}616263