/
UnmanagedMemoryAccessor.cs
659 lines (567 loc) · 21.8 KB
/
UnmanagedMemoryAccessor.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================
**
**
**
**
** Purpose: Provides a fast, AV free, cross-language way of
** accessing unmanaged memory in a random fashion.
**
**
===========================================================*/
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.IO
{
/// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the
/// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because
/// this gives better throughput; benchmarks showed about 12-15% better.
public class UnmanagedMemoryAccessor : IDisposable
{
private SafeBuffer _buffer = null!; // initialized in helper called by ctor, but also not initialized by protected ctor
private long _offset;
private long _capacity;
private FileAccess _access;
private bool _isOpen;
private bool _canRead;
private bool _canWrite;
protected UnmanagedMemoryAccessor()
{
}
public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity)
{
Initialize(buffer, offset, capacity, FileAccess.Read);
}
public UnmanagedMemoryAccessor(SafeBuffer buffer, long offset, long capacity, FileAccess access)
{
Initialize(buffer, offset, capacity, access);
}
protected void Initialize(SafeBuffer buffer, long offset, long capacity, FileAccess access)
{
ArgumentNullException.ThrowIfNull(buffer);
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.ByteLength < (ulong)(offset + capacity))
{
throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds);
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (_isOpen)
{
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
unsafe
{
byte* pointer = null;
try
{
buffer.AcquirePointer(ref pointer);
if (((byte*)((long)pointer + offset + capacity)) < pointer)
{
throw new ArgumentException(SR.Argument_UnmanagedMemAccessorWrapAround);
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_capacity = capacity;
_access = access;
_isOpen = true;
_canRead = (_access & FileAccess.Read) != 0;
_canWrite = (_access & FileAccess.Write) != 0;
}
public long Capacity => _capacity;
public bool CanRead => _isOpen && _canRead;
public bool CanWrite => _isOpen && _canWrite;
protected virtual void Dispose(bool disposing)
{
_isOpen = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected bool IsOpen => _isOpen;
// ************** Read Methods ****************/
public bool ReadBoolean(long position) => ReadByte(position) != 0;
public byte ReadByte(long position)
{
EnsureSafeToRead(position, sizeof(byte));
byte result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = *((byte*)(pointer + _offset + position));
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public char ReadChar(long position) => unchecked((char)ReadInt16(position));
public short ReadInt16(long position)
{
EnsureSafeToRead(position, sizeof(short));
short result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<short>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public int ReadInt32(long position)
{
EnsureSafeToRead(position, sizeof(int));
int result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<int>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public long ReadInt64(long position)
{
EnsureSafeToRead(position, sizeof(long));
long result;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<long>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public decimal ReadDecimal(long position)
{
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
EnsureSafeToRead(position, sizeof(decimal));
int lo, mid, hi, flags;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
lo = Unsafe.ReadUnaligned<int>(pointer);
mid = Unsafe.ReadUnaligned<int>(pointer + 4);
hi = Unsafe.ReadUnaligned<int>(pointer + 8);
flags = Unsafe.ReadUnaligned<int>(pointer + 12);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
// Check for invalid Decimal values
if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
{
throw new ArgumentException(SR.Arg_BadDecimal); // Throw same Exception type as Decimal(int[]) ctor for compat
}
bool isNegative = (flags & SignMask) != 0;
byte scale = (byte)(flags >> 16);
return new decimal(lo, mid, hi, isNegative, scale);
}
public float ReadSingle(long position) => BitConverter.Int32BitsToSingle(ReadInt32(position));
public double ReadDouble(long position) => BitConverter.Int64BitsToDouble(ReadInt64(position));
[CLSCompliant(false)]
public sbyte ReadSByte(long position) => unchecked((sbyte)ReadByte(position));
[CLSCompliant(false)]
public ushort ReadUInt16(long position) => unchecked((ushort)ReadInt16(position));
[CLSCompliant(false)]
public uint ReadUInt32(long position) => unchecked((uint)ReadInt32(position));
[CLSCompliant(false)]
public ulong ReadUInt64(long position) => unchecked((ulong)ReadInt64(position));
// Reads a struct of type T from unmanaged memory, into the reference pointed to by ref value.
// Note: this method is not safe, since it overwrites the contents of a structure, it can be
// used to modify the private members of a struct.
// This method is most performant when used with medium to large sized structs
// (larger than 8 bytes -- though this is number is JIT and architecture dependent). As
// such, it is best to use the ReadXXX methods for small standard types such as ints, longs,
// bools, etc.
public void Read<T>(long position, out T structure) where T : struct
{
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
uint sizeOfT = SafeBuffer.SizeOf<T>();
if (position > _capacity - sizeOfT)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position));
}
}
structure = _buffer.Read<T>((ulong)(_offset + position));
}
// Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'.
// Note: this method is not safe, since it overwrites the contents of structures, it can
// be used to modify the private members of a struct.
public int ReadArray<T>(long position, T[] array, int offset, int count) where T : struct
{
ArgumentNullException.ThrowIfNull(array);
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
uint sizeOfT = SafeBuffer.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
int n = count;
long spaceLeft = _capacity - position;
if (spaceLeft < 0)
{
n = 0;
}
else
{
ulong spaceNeeded = (ulong)(sizeOfT * count);
if ((ulong)spaceLeft < spaceNeeded)
{
n = (int)(spaceLeft / sizeOfT);
}
}
_buffer.ReadArray<T>((ulong)(_offset + position), array, offset, n);
return n;
}
// ************** Write Methods ****************/
public void Write(long position, bool value) => Write(position, (byte)(value ? 1 : 0));
public void Write(long position, byte value)
{
EnsureSafeToWrite(position, sizeof(byte));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
*((byte*)(pointer + _offset + position)) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, char value) => Write(position, unchecked((short)value));
public void Write(long position, short value)
{
EnsureSafeToWrite(position, sizeof(short));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<short>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, int value)
{
EnsureSafeToWrite(position, sizeof(int));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<int>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, long value)
{
EnsureSafeToWrite(position, sizeof(long));
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<long>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, decimal value)
{
EnsureSafeToWrite(position, sizeof(decimal));
Span<int> bits = stackalloc int[4];
decimal.TryGetBits(value, bits, out int intsWritten);
Debug.Assert(intsWritten == 4);
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
Unsafe.WriteUnaligned<int>(pointer, bits[0]);
Unsafe.WriteUnaligned<int>(pointer + 4, bits[1]);
Unsafe.WriteUnaligned<int>(pointer + 8, bits[2]);
Unsafe.WriteUnaligned<int>(pointer + 12, bits[3]);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(long position, float value) => Write(position, BitConverter.SingleToInt32Bits(value));
public void Write(long position, double value) => Write(position, BitConverter.DoubleToInt64Bits(value));
[CLSCompliant(false)]
public void Write(long position, sbyte value) => Write(position, unchecked((byte)value));
[CLSCompliant(false)]
public void Write(long position, ushort value) => Write(position, unchecked((short)value));
[CLSCompliant(false)]
public void Write(long position, uint value) => Write(position, unchecked((int)value));
[CLSCompliant(false)]
public void Write(long position, ulong value) => Write(position, unchecked((long)value));
// Writes the struct pointed to by ref value into unmanaged memory. Note that this method
// is most performant when used with medium to large sized structs (larger than 8 bytes
// though this is number is JIT and architecture dependent). As such, it is best to use
// the WriteX methods for small standard types such as ints, longs, bools, etc.
public void Write<T>(long position, ref T structure) where T : struct
{
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
uint sizeOfT = SafeBuffer.SizeOf<T>();
if (position > _capacity - sizeOfT)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToWrite, nameof(position));
}
}
_buffer.Write<T>((ulong)(_offset + position), structure);
}
// Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory.
public void WriteArray<T>(long position, T[] array, int offset, int count) where T : struct
{
ArgumentNullException.ThrowIfNull(array);
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position >= Capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
_buffer.WriteArray<T>((ulong)(_offset + position), array, offset, count);
}
private void EnsureSafeToRead(long position, int sizeOfType)
{
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position));
}
}
}
private void EnsureSafeToWrite(long position, int sizeOfType)
{
if (!_isOpen)
{
throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed);
}
if (!_canWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToWrite, nameof(position));
}
}
}
}
}