Skip to content

Commit c3fc7f0

Browse files
committed
allow comparing BorrowedReference to null
1 parent c4f2ad7 commit c3fc7f0

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

src/runtime/BorrowedReference.cs

+8
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ public BorrowedReference(IntPtr pointer)
2828
=> a.pointer == b.pointer;
2929
public static bool operator !=(BorrowedReference a, BorrowedReference b)
3030
=> a.pointer != b.pointer;
31+
public static bool operator ==(BorrowedReference reference, NullOnly @null)
32+
=> reference.IsNull;
33+
public static bool operator !=(BorrowedReference reference, NullOnly @null)
34+
=> !reference.IsNull;
35+
public static bool operator ==(NullOnly @null, BorrowedReference reference)
36+
=> reference.IsNull;
37+
public static bool operator !=(NullOnly @null, BorrowedReference reference)
38+
=> !reference.IsNull;
3139

3240
public override bool Equals(object obj) {
3341
if (obj is IntPtr ptr)

src/runtime/importhook.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ public static unsafe NewReference GetCLRModule(BorrowedReference fromList = defa
155155

156156
// find any items from the from list and get them from the root if they're not
157157
// already in the module dictionary
158-
if (fromList != null && fromList != default)
158+
if (fromList != null)
159159
{
160160
if (Runtime.PyTuple_Check(fromList))
161161
{
@@ -224,7 +224,7 @@ public static IntPtr __import__(IntPtr self, IntPtr argsRaw, IntPtr kw)
224224
if (num_args >= 4)
225225
{
226226
fromList = Runtime.PyTuple_GetItem(args, 3);
227-
if (fromList != default &&
227+
if (fromList != null &&
228228
Runtime.PyObject_IsTrue(fromList) == 1)
229229
{
230230
fromlist = true;
@@ -297,7 +297,7 @@ public static IntPtr __import__(IntPtr self, IntPtr argsRaw, IntPtr kw)
297297
BorrowedReference modules = Runtime.PyImport_GetModuleDict();
298298
BorrowedReference module = Runtime.PyDict_GetItem(modules, py_mod_name);
299299

300-
if (module != default)
300+
if (module != null)
301301
{
302302
if (fromlist)
303303
{

src/runtime/tricks/NullOnly.cs

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
namespace Python.Runtime
2+
{
3+
/// <summary>
4+
/// An utility class, that can only have one value: <c>null</c>.
5+
/// <para>Useful for overloading operators on structs,
6+
/// that have meaningful concept of <c>null</c> value (e.g. pointers and references).</para>
7+
/// </summary>
8+
class NullOnly
9+
{
10+
private NullOnly() { }
11+
}
12+
}

0 commit comments

Comments
 (0)