/ src / Ryujinx.Common / Memory / Ptr.cs
Ptr.cs
 1  using System;
 2  using System.Diagnostics.CodeAnalysis;
 3  using System.Runtime.CompilerServices;
 4  
 5  namespace Ryujinx.Common.Memory
 6  {
 7      /// <summary>
 8      /// Represents a pointer to an unmanaged resource.
 9      /// </summary>
10      /// <typeparam name="T">Type of the unmanaged resource</typeparam>
11      public unsafe struct Ptr<T> : IEquatable<Ptr<T>> where T : unmanaged
12      {
13          private IntPtr _ptr;
14  
15          /// <summary>
16          /// Null pointer.
17          /// </summary>
18          public static Ptr<T> Null => new() { _ptr = IntPtr.Zero };
19  
20          /// <summary>
21          /// True if the pointer is null, false otherwise.
22          /// </summary>
23          public readonly bool IsNull => _ptr == IntPtr.Zero;
24  
25          /// <summary>
26          /// Gets a reference to the value.
27          /// </summary>
28          public readonly ref T Value => ref Unsafe.AsRef<T>((void*)_ptr);
29  
30          /// <summary>
31          /// Creates a new pointer to an unmanaged resource.
32          /// </summary>
33          /// <remarks>
34          /// For data on the heap, proper pinning is necessary during
35          /// use. Failure to do so will result in memory corruption and crashes.
36          /// </remarks>
37          /// <param name="value">Reference to the unmanaged resource</param>
38          public Ptr(ref T value)
39          {
40              _ptr = (IntPtr)Unsafe.AsPointer(ref value);
41          }
42  
43          public readonly override bool Equals(object obj)
44          {
45              return obj is Ptr<T> other && Equals(other);
46          }
47  
48          public readonly bool Equals([AllowNull] Ptr<T> other)
49          {
50              return _ptr == other._ptr;
51          }
52  
53          public readonly override int GetHashCode()
54          {
55              return _ptr.GetHashCode();
56          }
57  
58          public static bool operator ==(Ptr<T> left, Ptr<T> right)
59          {
60              return left.Equals(right);
61          }
62  
63          public static bool operator !=(Ptr<T> left, Ptr<T> right)
64          {
65              return !(left == right);
66          }
67      }
68  }