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