-
Notifications
You must be signed in to change notification settings - Fork 774
Expand file tree
/
Copy pathStolenReference.cs
More file actions
82 lines (73 loc) · 2.58 KB
/
StolenReference.cs
File metadata and controls
82 lines (73 loc) · 2.58 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
namespace Python.Runtime
{
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
/// <summary>
/// Should only be used for the arguments of Python C API functions, that steal references,
/// and internal <see cref="PyObject"/> constructors.
/// </summary>
[NonCopyable]
readonly ref struct StolenReference
{
internal readonly IntPtr Pointer;
[DebuggerHidden]
StolenReference(IntPtr pointer)
{
Pointer = pointer;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static StolenReference Take(ref IntPtr ptr)
{
if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr));
return TakeNullable(ref ptr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[DebuggerHidden]
public static StolenReference TakeNullable(ref IntPtr ptr)
{
var stolenAddr = ptr;
ptr = IntPtr.Zero;
return new StolenReference(stolenAddr);
}
[Pure]
public static bool operator ==(in StolenReference reference, NullOnly? @null)
=> reference.Pointer == IntPtr.Zero;
[Pure]
public static bool operator !=(in StolenReference reference, NullOnly? @null)
=> reference.Pointer != IntPtr.Zero;
[Pure]
public override bool Equals(object obj)
{
if (obj is IntPtr ptr)
return ptr == Pointer;
return false;
}
[Pure]
public override int GetHashCode() => Pointer.GetHashCode();
[Pure]
public static StolenReference DangerousFromPointer(IntPtr ptr)
{
if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr));
return new StolenReference(ptr);
}
}
static class StolenReferenceExtensions
{
[Pure]
[DebuggerHidden]
public static IntPtr DangerousGetAddressOrNull(this in StolenReference reference)
=> reference.Pointer;
[Pure]
[DebuggerHidden]
public static IntPtr DangerousGetAddress(this in StolenReference reference)
=> reference.Pointer == IntPtr.Zero ? throw new NullReferenceException() : reference.Pointer;
[DebuggerHidden]
public static StolenReference AnalyzerWorkaround(this in StolenReference reference)
{
IntPtr ptr = reference.DangerousGetAddressOrNull();
return StolenReference.TakeNullable(ref ptr);
}
}
}