Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/base/common/controlFlow.ts
3291 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 { BugIndicatingError } from './errors.js';
6
7
/*
8
* This file contains helper classes to manage control flow.
9
*/
10
11
/**
12
* Prevents code from being re-entrant.
13
*/
14
export class ReentrancyBarrier {
15
private _isOccupied = false;
16
17
/**
18
* Calls `runner` if the barrier is not occupied.
19
* During the call, the barrier becomes occupied.
20
*/
21
public runExclusivelyOrSkip(runner: () => void): void {
22
if (this._isOccupied) {
23
return;
24
}
25
this._isOccupied = true;
26
try {
27
runner();
28
} finally {
29
this._isOccupied = false;
30
}
31
}
32
33
/**
34
* Calls `runner`. If the barrier is occupied, throws an error.
35
* During the call, the barrier becomes active.
36
*/
37
public runExclusivelyOrThrow(runner: () => void): void {
38
if (this._isOccupied) {
39
throw new BugIndicatingError(`ReentrancyBarrier: reentrant call detected!`);
40
}
41
this._isOccupied = true;
42
try {
43
runner();
44
} finally {
45
this._isOccupied = false;
46
}
47
}
48
49
/**
50
* Indicates if some runner occupies this barrier.
51
*/
52
public get isOccupied() {
53
return this._isOccupied;
54
}
55
56
public makeExclusiveOrSkip<TFunction extends Function>(fn: TFunction): TFunction {
57
return ((...args: any[]) => {
58
if (this._isOccupied) {
59
return;
60
}
61
this._isOccupied = true;
62
try {
63
return fn(...args);
64
} finally {
65
this._isOccupied = false;
66
}
67
}) as any;
68
}
69
}
70
71