-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathJsonModuleManager.cs
More file actions
110 lines (88 loc) · 3.27 KB
/
JsonModuleManager.cs
File metadata and controls
110 lines (88 loc) · 3.27 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ClearScript.Util;
namespace Microsoft.ClearScript.JavaScript
{
internal sealed class JsonModuleManager
{
private readonly ScriptEngine engine;
private readonly List<Module> moduleCache = new();
public JsonModuleManager(ScriptEngine engine)
{
this.engine = engine;
}
public int ModuleCacheSize => moduleCache.Count;
public Module GetOrCreateModule(UniqueDocumentInfo documentInfo, string json)
{
var jsonDigest = json.GetDigest();
var cachedModule = GetCachedModule(documentInfo, jsonDigest);
if (cachedModule is not null)
{
return cachedModule;
}
return CacheModule(new Module(engine, documentInfo, jsonDigest, json));
}
private Module GetCachedModule(UniqueDocumentInfo documentInfo, UIntPtr jsonDigest)
{
for (var index = 0; index < moduleCache.Count; index++)
{
var cachedModule = moduleCache[index];
if ((cachedModule.DocumentInfo.UniqueId == documentInfo.UniqueId) && (cachedModule.JsonDigest == jsonDigest))
{
moduleCache.RemoveAt(index);
moduleCache.Insert(0, cachedModule);
return cachedModule;
}
}
return null;
}
private Module CacheModule(Module module)
{
var cachedModule = moduleCache.FirstOrDefault(testModule => (testModule.DocumentInfo.UniqueId == module.DocumentInfo.UniqueId) && (testModule.JsonDigest == module.JsonDigest));
if (cachedModule is not null)
{
return cachedModule;
}
var maxModuleCacheSize = Math.Max(16, Convert.ToInt32(Math.Min(DocumentCategory.Json.MaxCacheSize, int.MaxValue)));
while (moduleCache.Count >= maxModuleCacheSize)
{
moduleCache.RemoveAt(moduleCache.Count - 1);
}
moduleCache.Insert(0, module);
return module;
}
#region Nested type: Module
public sealed class Module
{
private readonly ScriptEngine engine;
private readonly string json;
private bool parsed;
private object result;
public Module(ScriptEngine engine, UniqueDocumentInfo documentInfo, UIntPtr jsonDigest, string json)
{
this.engine = engine;
this.json = json;
DocumentInfo = documentInfo;
JsonDigest = jsonDigest;
}
public UniqueDocumentInfo DocumentInfo { get; }
public UIntPtr JsonDigest { get; }
public object Result
{
get
{
if (!parsed)
{
parsed = true;
result = engine.EngineInternal.InvokeMethod("parseJson", json);
}
return result;
}
}
}
#endregion
}
}