forked from irinazheltisheva/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarshalling.ts
More file actions
78 lines (64 loc) · 1.79 KB
/
Copy pathmarshalling.ts
File metadata and controls
78 lines (64 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { VSBuffer } from 'vs/base/common/buffer';
import { regExpFlags } from 'vs/base/common/strings';
import { URI, UriComponents } from 'vs/base/common/uri';
export function stringify(obj: any): string {
return JSON.stringify(obj, replacer);
}
export function parse(text: string): any {
let data = JSON.parse(text);
data = revive(data);
return data;
}
export interface MarshalledObject {
$mid: number;
}
function replacer(key: string, value: any): any {
// URI is done via toJSON-member
if (value instanceof RegExp) {
return {
$mid: 2,
source: value.source,
flags: regExpFlags(value),
};
}
return value;
}
type Deserialize<T> = T extends UriComponents ? URI
: T extends object
? Revived<T>
: T;
export type Revived<T> = { [K in keyof T]: Deserialize<T[K]> };
export function revive<T = any>(obj: any, depth = 0): Revived<T> {
if (!obj || depth > 200) {
return obj;
}
if (typeof obj === 'object') {
switch ((<MarshalledObject>obj).$mid) {
case 1: return <any>URI.revive(obj);
case 2: return <any>new RegExp(obj.source, obj.flags);
}
if (
obj instanceof VSBuffer
|| obj instanceof Uint8Array
) {
return <any>obj;
}
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; ++i) {
obj[i] = revive(obj[i], depth + 1);
}
} else {
// walk object
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
obj[key] = revive(obj[key], depth + 1);
}
}
}
}
return obj;
}