-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathRefBox.cs
More file actions
52 lines (46 loc) · 1.09 KB
/
Copy pathRefBox.cs
File metadata and controls
52 lines (46 loc) · 1.09 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
namespace Medallion.Threading.Internal;
/// <summary>
/// Wraps a value tuple to be a read/write reference
/// </summary>
#if DEBUG
public
#else
internal
#endif
sealed class RefBox<T> where T : struct
{
private readonly T _value;
internal RefBox(T value)
{
this._value = value;
}
public ref readonly T Value => ref this._value;
}
/// <summary>
/// Simplifies storing state in certain <see cref="IDisposable"/>s.
/// </summary>
#if DEBUG
public
#else
internal
#endif
sealed class RefBox
{
public static RefBox<T> Create<T>(T value) where T : struct => new(value);
/// <summary>
/// Thread-safely checks if <paramref name="boxRef"/> is non-null and if so sets it to null and outputs
/// the value as <paramref name="value"/>.
/// </summary>
public static bool TryConsume<T>(ref RefBox<T>? boxRef, out T value)
where T : struct
{
var box = Interlocked.Exchange(ref boxRef, null);
if (box != null)
{
value = box.Value;
return true;
}
value = default;
return false;
}
}