forked from ClearFoundry/ClearScript
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathValueScope.cs
More file actions
79 lines (67 loc) · 2.08 KB
/
Copy pathValueScope.cs
File metadata and controls
79 lines (67 loc) · 2.08 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
namespace Microsoft.ClearScript.Util
{
internal ref struct ValueScope
{
private readonly Action exitAction;
private bool disposed;
public ValueScope(Action exitAction)
{
this.exitAction = exitAction;
disposed = false;
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
exitAction?.Invoke();
}
}
}
internal ref struct ValueScope<TValue>
{
private readonly Action<TValue> exitAction;
private bool disposed;
public TValue Value { get; }
public ValueScope(TValue value, Action<TValue> exitAction)
{
this.exitAction = exitAction;
disposed = false;
Value = value;
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
exitAction?.Invoke(Value);
}
}
}
internal static class ScopeFactory
{
public static ValueScope Create(Action enterAction, Action exitAction)
{
enterAction?.Invoke();
return new ValueScope(exitAction);
}
public static ValueScope Create<TArg>(Action<TArg> enterAction, Action exitAction, in TArg arg)
{
enterAction?.Invoke(arg);
return new ValueScope(exitAction);
}
public static ValueScope<TValue> Create<TValue>(Func<TValue> enterFunc, Action<TValue> exitAction)
{
var value = (enterFunc is not null) ? enterFunc() : default;
return new ValueScope<TValue>(value, exitAction);
}
public static ValueScope<TValue> Create<TArg, TValue>(Func<TArg, TValue> enterFunc, Action<TValue> exitAction, in TArg arg)
{
var value = (enterFunc is not null) ? enterFunc(arg) : default;
return new ValueScope<TValue>(value, exitAction);
}
}
}