@@ -15,6 +15,20 @@ ref struct NewReference
1515 public static implicit operator BorrowedReference ( in NewReference reference )
1616 => new BorrowedReference ( reference . pointer ) ;
1717
18+ /// <summary>
19+ /// Creates <see cref="NewReference"/> from a nullable <see cref="BorrowedReference"/>.
20+ /// Increments the reference count accordingly.
21+ /// </summary>
22+ [ Pure ]
23+ public static NewReference FromNullable ( BorrowedReference reference )
24+ {
25+ if ( reference . IsNull ) return default ;
26+
27+ IntPtr address = reference . DangerousGetAddress ( ) ;
28+ Runtime . XIncref ( address ) ;
29+ return DangerousFromPointer ( address ) ;
30+ }
31+
1832 /// <summary>
1933 /// Returns <see cref="PyObject"/> wrapper around this reference, which now owns
2034 /// the pointer. Sets the original reference to <c>null</c>, as it no longer owns it.
@@ -44,6 +58,18 @@ public void Dispose()
4458 public static NewReference DangerousFromPointer ( IntPtr pointer )
4559 => new NewReference { pointer = pointer } ;
4660
61+ /// <summary>
62+ /// Creates <see cref="NewReference"/> from a raw pointer
63+ /// and writes <c>null</c> to the original location.
64+ /// </summary>
65+ [ Pure ]
66+ public static NewReference DangerousMoveFromPointer ( ref IntPtr pointer )
67+ {
68+ var pointerValue = pointer ;
69+ pointer = IntPtr . Zero ;
70+ return DangerousFromPointer ( pointerValue ) ;
71+ }
72+
4773 public IntPtr DangerousMoveToPointer ( )
4874 {
4975 if ( this . IsNull ( ) ) throw new NullReferenceException ( ) ;
@@ -61,11 +87,11 @@ internal static bool IsNull(in NewReference reference)
6187 => reference . pointer == IntPtr . Zero ;
6288
6389 // TODO: return some static type
64- internal IntPtr Steal ( )
90+ internal StealingReference Steal ( )
6591 {
6692 var result = this . pointer ;
6793 this . pointer = IntPtr . Zero ;
68- return result ;
94+ return StealingReference . DangerousFromPointer ( result ) ;
6995 }
7096 }
7197
0 commit comments