-
Notifications
You must be signed in to change notification settings - Fork 32
/
NativeIntPtr.cs
385 lines (355 loc) · 9.5 KB
/
NativeIntPtr.cs
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//-----------------------------------------------------------------------
// <copyright file="NativeIntPtr.cs" company="Jackson Dunstan">
// Copyright (c) Jackson Dunstan. See LICENSE.md.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace JacksonDunstan.NativeCollections
{
/// <summary>
/// A pointer to an int stored in native (i.e. unmanaged) memory
/// </summary>
[NativeContainer]
[NativeContainerSupportsDeallocateOnJobCompletion]
[DebuggerTypeProxy(typeof(NativeIntPtrDebugView))]
[DebuggerDisplay("Value = {Value}")]
[StructLayout(LayoutKind.Sequential)]
public unsafe struct NativeIntPtr : IDisposable
{
/// <summary>
/// An atomic write-only version of the object suitable for use in a
/// ParallelFor job
/// </summary>
[NativeContainer]
[NativeContainerIsAtomicWriteOnly]
public struct Parallel
{
/// <summary>
/// Pointer to the value in native memory
/// </summary>
[NativeDisableUnsafePtrRestriction]
internal readonly int* m_Buffer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
/// <summary>
/// A handle to information about what operations can be safely
/// performed on the object at any given time.
/// </summary>
internal AtomicSafetyHandle m_Safety;
/// <summary>
/// Create a parallel version of the object
/// </summary>
///
/// <param name="value">
/// Pointer to the value
/// </param>
///
/// <param name="safety">
/// Atomic safety handle for the object
/// </param>
internal Parallel(int* value, AtomicSafetyHandle safety)
{
m_Buffer = value;
m_Safety = safety;
}
#else
/// <summary>
/// Create a parallel version of the object
/// </summary>
///
/// <param name="value">
/// Pointer to the value
/// </param>
internal Parallel(int* value)
{
m_Buffer = value;
}
#endif
/// <summary>
/// Increment the stored value
/// </summary>
///
/// <returns>
/// This object
/// </returns>
[WriteAccessRequired]
public void Increment()
{
RequireWriteAccess();
Interlocked.Increment(ref *m_Buffer);
}
/// <summary>
/// Decrement the stored value
/// </summary>
///
/// <returns>
/// This object
/// </returns>
[WriteAccessRequired]
public void Decrement()
{
RequireWriteAccess();
Interlocked.Decrement(ref *m_Buffer);
}
/// <summary>
/// Add to the stored value
/// </summary>
///
/// <param name="value">
/// Value to add. Use negative values for subtraction.
/// </param>
///
/// <returns>
/// This object
/// </returns>
[WriteAccessRequired]
public void Add(int value)
{
RequireWriteAccess();
Interlocked.Add(ref *m_Buffer, value);
}
/// <summary>
/// Throw an exception if the object isn't writable
/// </summary>
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private void RequireWriteAccess()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
}
}
/// <summary>
/// Pointer to the value in native memory. Must be named exactly this
/// way to allow for [NativeContainerSupportsDeallocateOnJobCompletion]
/// </summary>
[NativeDisableUnsafePtrRestriction]
internal int* m_Buffer;
/// <summary>
/// Allocator used to create the backing memory
///
/// This field must be named this way to comply with
/// [NativeContainerSupportsDeallocateOnJobCompletion]
/// </summary>
internal readonly Allocator m_AllocatorLabel;
// These fields are all required when safety checks are enabled
#if ENABLE_UNITY_COLLECTIONS_CHECKS
/// <summary>
/// A handle to information about what operations can be safely
/// performed on the object at any given time.
/// </summary>
private AtomicSafetyHandle m_Safety;
/// <summary>
/// A handle that can be used to tell if the object has been disposed
/// yet or not, which allows for error-checking double disposal.
/// </summary>
[NativeSetClassTypeToNullOnSchedule]
private DisposeSentinel m_DisposeSentinel;
#endif
/// <summary>
/// Allocate memory and set the initial value
/// </summary>
///
/// <param name="allocator">
/// Allocator to allocate and deallocate with. Must be valid.
/// </param>
///
/// <param name="initialValue">
/// Initial value of the allocated memory
/// </param>
public NativeIntPtr(Allocator allocator, int initialValue = 0)
{
// Require a valid allocator
if (allocator <= Allocator.None)
{
throw new ArgumentException(
"Allocator must be Temp, TempJob or Persistent",
"allocator");
}
// Allocate the memory for the value
m_Buffer = (int*)UnsafeUtility.Malloc(
sizeof(int),
UnsafeUtility.AlignOf<int>(),
allocator);
// Store the allocator to use when deallocating
m_AllocatorLabel = allocator;
// Create the dispose sentinel
#if ENABLE_UNITY_COLLECTIONS_CHECKS
#if UNITY_2018_3_OR_NEWER
DisposeSentinel.Create(out m_Safety, out m_DisposeSentinel, 0, allocator);
#else
DisposeSentinel.Create(out m_Safety, out m_DisposeSentinel, 0);
#endif
#endif
// Set the initial value
*m_Buffer = initialValue;
}
/// <summary>
/// Get or set the contained value
///
/// This operation requires read access to the node for 'get' and write
/// access to the node for 'set'.
/// </summary>
///
/// <value>
/// The contained value
/// </value>
public int Value
{
get
{
RequireReadAccess();
return *m_Buffer;
}
[WriteAccessRequired]
set
{
RequireWriteAccess();
*m_Buffer = value;
}
}
/// <summary>
/// Get a version of this object suitable for use in a ParallelFor job
/// </summary>
///
/// <returns>
/// A version of this object suitable for use in a ParallelFor job
/// </returns>
public Parallel GetParallel()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
Parallel parallel = new Parallel(m_Buffer, m_Safety);
AtomicSafetyHandle.UseSecondaryVersion(ref parallel.m_Safety);
#else
Parallel parallel = new Parallel(m_Buffer);
#endif
return parallel;
}
/// <summary>
/// Check if the underlying unmanaged memory has been created and not
/// freed via a call to <see cref="Dispose"/>.
///
/// This operation has no access requirements.
///
/// This operation is O(1).
/// </summary>
///
/// <value>
/// Initially true when a non-default constructor is called but
/// initially false when the default constructor is used. After
/// <see cref="Dispose"/> is called, this becomes false. Note that
/// calling <see cref="Dispose"/> on one copy of this object doesn't
/// result in this becoming false for all copies if it was true before.
/// This property should <i>not</i> be used to check whether the object
/// is usable, only to check whether it was <i>ever</i> usable.
/// </value>
public bool IsCreated
{
get
{
return m_Buffer != null;
}
}
/// <summary>
/// Release the object's unmanaged memory. Do not use it after this. Do
/// not call <see cref="Dispose"/> on copies of the object either.
///
/// This operation requires write access.
///
/// This complexity of this operation is O(1) plus the allocator's
/// deallocation complexity.
/// </summary>
[WriteAccessRequired]
public void Dispose()
{
RequireWriteAccess();
// Make sure we're not double-disposing
#if ENABLE_UNITY_COLLECTIONS_CHECKS
#if UNITY_2018_3_OR_NEWER
DisposeSentinel.Dispose(ref m_Safety, ref m_DisposeSentinel);
#else
DisposeSentinel.Dispose(m_Safety, ref m_DisposeSentinel);
#endif
#endif
UnsafeUtility.Free(m_Buffer, m_AllocatorLabel);
m_Buffer = null;
}
/// <summary>
/// Set whether both read and write access should be allowed. This is
/// used for automated testing purposes only.
/// </summary>
///
/// <param name="allowReadOrWriteAccess">
/// If both read and write access should be allowed
/// </param>
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
public void TestUseOnlySetAllowReadAndWriteAccess(
bool allowReadOrWriteAccess)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.SetAllowReadOrWriteAccess(
m_Safety,
allowReadOrWriteAccess);
#endif
}
/// <summary>
/// Throw an exception if the object isn't readable
/// </summary>
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private void RequireReadAccess()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
/// <summary>
/// Throw an exception if the object isn't writable
/// </summary>
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
private void RequireWriteAccess()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
}
}
/// <summary>
/// Provides a debugger view of <see cref="NativeIntPtr"/>.
/// </summary>
internal sealed class NativeIntPtrDebugView
{
/// <summary>
/// The object to provide a debugger view for
/// </summary>
private NativeIntPtr m_Ptr;
/// <summary>
/// Create the debugger view
/// </summary>
///
/// <param name="ptr">
/// The object to provide a debugger view for
/// </param>
public NativeIntPtrDebugView(NativeIntPtr ptr)
{
m_Ptr = ptr;
}
/// <summary>
/// Get the viewed object's value
/// </summary>
///
/// <value>
/// The viewed object's value
/// </value>
public int Value
{
get
{
return m_Ptr.Value;
}
}
}
}