forked from zzzprojects/System.Linq.Dynamic.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstantExpressionHelper.cs
More file actions
60 lines (47 loc) · 1.84 KB
/
ConstantExpressionHelper.cs
File metadata and controls
60 lines (47 loc) · 1.84 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
using System.Linq.Dynamic.Core.Util.Cache;
using System.Linq.Expressions;
namespace System.Linq.Dynamic.Core.Parser;
internal class ConstantExpressionHelper
{
private readonly ParsingConfig _config;
// Static shared instance to prevent duplications of the same objects
private static ThreadSafeSlidingCache<object, Expression>? _expressions;
private static ThreadSafeSlidingCache<Expression, string>? _literals;
public ConstantExpressionHelper(ParsingConfig config)
{
_config = config;
}
private ThreadSafeSlidingCache<Expression, string> GetLiterals()
{
_literals ??= new ThreadSafeSlidingCache<Expression, string>(
_config.ConstantExpressionSlidingCacheTimeToLive,
_config.ConstantExpressionSlidingCacheCleanupFrequency,
_config.ConstantExpressionSlidingCacheMinItemsTrigger
);
return _literals;
}
private ThreadSafeSlidingCache<object, Expression> GetExpression()
{
_expressions ??= new ThreadSafeSlidingCache<object, Expression>(
_config.ConstantExpressionSlidingCacheTimeToLive,
_config.ConstantExpressionSlidingCacheCleanupFrequency,
_config.ConstantExpressionSlidingCacheMinItemsTrigger
);
return _expressions;
}
public bool TryGetText(Expression expression, out string? text)
{
return GetLiterals().TryGetValue(expression, out text);
}
public Expression CreateLiteral(object value, string text)
{
if (GetExpression().TryGetValue(value, out var outputValue))
{
return outputValue;
}
var constantExpression = Expression.Constant(value);
GetExpression().AddOrUpdate(value, constantExpression);
GetLiterals().AddOrUpdate(constantExpression, text);
return constantExpression;
}
}