Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/editor/common/model/fixedArray.ts
3294 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
6
import { arrayInsert } from '../../../base/common/arrays.js';
7
8
/**
9
* An array that avoids being sparse by always
10
* filling up unused indices with a default value.
11
*/
12
export class FixedArray<T> {
13
private _store: T[] = [];
14
15
constructor(
16
private readonly _default: T
17
) { }
18
19
public get(index: number): T {
20
if (index < this._store.length) {
21
return this._store[index];
22
}
23
return this._default;
24
}
25
26
public set(index: number, value: T): void {
27
while (index >= this._store.length) {
28
this._store[this._store.length] = this._default;
29
}
30
this._store[index] = value;
31
}
32
33
public replace(index: number, oldLength: number, newLength: number): void {
34
if (index >= this._store.length) {
35
return;
36
}
37
38
if (oldLength === 0) {
39
this.insert(index, newLength);
40
return;
41
} else if (newLength === 0) {
42
this.delete(index, oldLength);
43
return;
44
}
45
46
const before = this._store.slice(0, index);
47
const after = this._store.slice(index + oldLength);
48
const insertArr = arrayFill(newLength, this._default);
49
this._store = before.concat(insertArr, after);
50
}
51
52
public delete(deleteIndex: number, deleteCount: number): void {
53
if (deleteCount === 0 || deleteIndex >= this._store.length) {
54
return;
55
}
56
this._store.splice(deleteIndex, deleteCount);
57
}
58
59
public insert(insertIndex: number, insertCount: number): void {
60
if (insertCount === 0 || insertIndex >= this._store.length) {
61
return;
62
}
63
const arr: T[] = [];
64
for (let i = 0; i < insertCount; i++) {
65
arr[i] = this._default;
66
}
67
this._store = arrayInsert(this._store, insertIndex, arr);
68
}
69
}
70
71
function arrayFill<T>(length: number, value: T): T[] {
72
const arr: T[] = [];
73
for (let i = 0; i < length; i++) {
74
arr[i] = value;
75
}
76
return arr;
77
}
78
79