Repository navigation
Expand file tree
/
Copy pathUnmanagedMemoryBlock`1.cs
More file actions
1386 lines (1200 loc) · 55.3 KB
/
Copy pathUnmanagedMemoryBlock`1.cs
File metadata and controls
1386 lines (1200 loc) · 55.3 KB
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using NumSharp.Backends.Unmanaged.Pooling;
using NumSharp.Unmanaged.Memory;
using NumSharp.Utilities;
namespace NumSharp.Backends.Unmanaged
{
public unsafe struct UnmanagedMemoryBlock<T> : IUnmanagedMemoryBlock, IMemoryBlock<T>, IEnumerable<T>, IEquatable<UnmanagedMemoryBlock<T>>, ICloneable where T : unmanaged
{
private readonly Disposer _disposer;
public readonly long Count;
public readonly T* Address;
public readonly long BytesCount;
/// <summary>
///
/// </summary>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
/// <remarks>
/// Does claim ownership since allocation is publicly. Routes through
/// <see cref="SizeBucketedBufferPool.Take"/> so recently-freed
/// buffers of matching size are reused — eliminates the
/// ~500 µs first-touch / kernel-mode page-fault cost for the
/// dominant element-wise binary-op output allocation pattern,
/// which lets routed binary ops cross from NumPy-parity into
/// NumPy-better territory.
/// </remarks>
[MethodImpl(Optimize)]
public UnmanagedMemoryBlock(long count)
{
// A wrapped byte count asks the allocator for a small (often zero) block and gets one,
// so the corruption is silent. See AllocationGuard.
AllocationGuard.CheckElementCount(count, InfoOf<T>.Size);
var bytes = BytesCount = count * InfoOf<T>.Size;
var ptr = SizeBucketedBufferPool.Take(bytes);
_disposer = new Disposer(ptr, bytes);
Address = (T*)ptr;
Count = count;
}
/// <summary>
/// Construct as a wrapper around pointer and given length without claiming ownership.
/// </summary>
/// <param name="ptr"></param>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
/// <remarks>
/// Does NOT claim ownership: wraps <paramref name="ptr"/> with the non-owning
/// <c>Disposer.Null</c> marker (<c>AllocationType.Wrap</c>), so disposing this block
/// never frees <paramref name="ptr"/>. The caller remains responsible for the
/// lifetime of the underlying memory.
/// </remarks>
[MethodImpl(Optimize)]
public UnmanagedMemoryBlock(T* ptr, long count)
{
_disposer = Disposer.Null;
Address = ptr;
Count = count;
BytesCount = count * InfoOf<T>.Size;
}
/// <summary>
/// Construct with externally allocated memory and a custom <paramref name="dispose"/> function.
/// </summary>
/// <param name="start">Pointer to externally allocated unmanaged memory.</param>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
/// <param name="dispose">Cleanup action called when memory is released.</param>
/// <remarks>
/// Claims ownership of the memory. Caller is responsible for GC.AddMemoryPressure
/// if the memory is unmanaged and large enough to warrant it.
/// </remarks>
[MethodImpl(OptimizeAndInline)]
public UnmanagedMemoryBlock(T* start, long count, Action dispose)
{
Count = count;
BytesCount = InfoOf<T>.Size * count;
_disposer = new Disposer(dispose); // Caller tracks pressure for their allocation
Address = start;
}
/// <summary>
/// Construct with externally allocated memory settings this memory block as owner.
/// </summary>
/// <param name="handle"></param>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
/// <remarks>Does claim ownership.</remarks>
[MethodImpl(OptimizeAndInline)]
public UnmanagedMemoryBlock(GCHandle handle, long count)
{
Count = count;
BytesCount = InfoOf<T>.Size * count;
Address = (T*)handle.AddrOfPinnedObject();
_disposer = new Disposer(handle);
}
/// <summary>
/// Construct with externally allocated memory and a custom <paramref name="dispose"/> function.
/// </summary>
/// <param name="handle"></param>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
/// <param name="dispose"></param>
/// <remarks>Does claim ownership.</remarks>
[MethodImpl(OptimizeAndInline)]
public UnmanagedMemoryBlock(GCHandle handle, long count, Action dispose)
{
Count = count;
BytesCount = InfoOf<T>.Size * count;
Address = (T*)handle.AddrOfPinnedObject();
_disposer = new Disposer(dispose);
}
/// <summary>
///
/// </summary>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
/// <param name="fill"></param>
[MethodImpl(OptimizeAndInline)]
public UnmanagedMemoryBlock(long count, T fill) : this(count)
{
Fill(fill, 0, count);
}
/// <summary>
/// Discriminator tag for the zero-initialized ctor. Keeps it from
/// colliding with the <c>(long count, T fill)</c> overload when
/// <typeparamref name="T"/> is a 1-byte type (e.g. <see cref="bool"/>),
/// where <c>(count, default(T))</c> would otherwise be ambiguous.
/// </summary>
private readonly struct Zeroed { }
/// <summary>
/// Allocate a zero-initialized block via
/// <see cref="SizeBucketedBufferPool.TakeZeroed"/> (calloc / OS
/// demand-zero pages) — no per-element fill loop. This is the
/// np.zeros / fill-with-default fast path: a 10M-element block is
/// zeroed in ~0.01 ms instead of ~14 ms.
///
/// Correct for every supported dtype because the all-zero bit
/// pattern equals <c>default(T)</c> for all 15 of them — including
/// <see cref="System.Half"/>, <see cref="float"/>, <see cref="double"/>,
/// <see cref="decimal"/> and <see cref="System.Numerics.Complex"/>
/// (each of whose "zero" value is represented by all-zero bytes).
/// </summary>
/// <param name="count">The length in objects of <typeparamref name="T"/> and not in bytes.</param>
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> AllocateZeroed(long count)
=> new UnmanagedMemoryBlock<T>(count, default(Zeroed));
/// <summary>
/// Zero-initialized ctor backing <see cref="AllocateZeroed"/>.
/// Claims ownership of a calloc'd buffer (Native disposer), so it
/// returns to <see cref="SizeBucketedBufferPool"/> on free just
/// like the noisy <see cref="UnmanagedMemoryBlock(long)"/> ctor.
/// </summary>
[MethodImpl(Optimize)]
private UnmanagedMemoryBlock(long count, Zeroed _)
{
AllocationGuard.CheckElementCount(count, InfoOf<T>.Size);
var bytes = BytesCount = count * InfoOf<T>.Size;
Count = count;
// Windows large-block fast path: VirtualAlloc returns lazy
// demand-zero pages, dodging the process heap's eager commit+memset
// for mid-size calloc. Small sizes and non-Windows fall through to
// calloc (already lazy via mmap there); so does a VirtualAlloc that
// unexpectedly fails.
if (!SizeBucketedBufferPool.GuardPagesEnabled && OsVirtualMemory.IsSupported && bytes >= OsVirtualMemory.ThresholdBytes)
{
var vptr = OsVirtualMemory.Alloc(bytes);
if (vptr != IntPtr.Zero)
{
_disposer = new Disposer(vptr, bytes, virtualAlloc: true);
Address = (T*)vptr;
return;
}
}
var ptr = SizeBucketedBufferPool.TakeZeroed(bytes);
_disposer = new Disposer(ptr, bytes);
Address = (T*)ptr;
}
#region Static
#region FromArray
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,,] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromArray(T[,,,,,,,,,,,,,,,] arr, bool copy)
{
if (!copy)
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length);
var ret = new UnmanagedMemoryBlock<T>(arr.Length);
fixed (T* arrptr = arr)
{
new UnmanagedMemoryBlock<T>(arrptr, arr.Length).CopyTo(ret);
}
return ret;
}
#endregion
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromBuffer(byte[] arr)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(arr, GCHandleType.Pinned), arr.Length / InfoOf<T>.Size);
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromBuffer(byte[] arr, bool copy)
{
return new UnmanagedMemoryBlock<T>(GCHandle.Alloc(copy ? arr.Clone() : arr, GCHandleType.Pinned), arr.Length / InfoOf<T>.Size);
}
/// <summary>
/// Create a memory block from a byte buffer with offset and count support.
/// </summary>
/// <param name="arr">The source byte array.</param>
/// <param name="byteOffset">Byte offset into the array.</param>
/// <param name="count">Number of elements of type T to include (-1 for all available).</param>
/// <param name="copy">If true, copies the data; if false, creates a view (pins the array).</param>
/// <returns>A memory block viewing or copying the specified region.</returns>
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromBuffer(byte[] arr, long byteOffset, long count, bool copy)
{
int itemSize = InfoOf<T>.Size;
long availableBytes = arr.Length - byteOffset;
long maxCount = availableBytes / itemSize;
long actualCount = count < 0 ? maxCount : count;
if (copy)
{
// Allocate new memory and copy
var ret = new UnmanagedMemoryBlock<T>(actualCount);
fixed (byte* src = &arr[byteOffset])
{
Buffer.MemoryCopy(src, ret.Address, ret.BytesCount, actualCount * itemSize);
}
return ret;
}
else
{
// Pin the array and return a view with offset
var handle = GCHandle.Alloc(arr, GCHandleType.Pinned);
var baseAddr = (byte*)handle.AddrOfPinnedObject();
return new UnmanagedMemoryBlock<T>((T*)(baseAddr + byteOffset), actualCount, () => handle.Free());
}
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> FromPool(StackedMemoryPool manager)
{
Debug.Assert(manager.SingleSize / InfoOf<T>.Size > 0);
var buffer = manager.Take();
return new UnmanagedMemoryBlock<T>((T*)buffer, 1, () => manager.Return(buffer));
}
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> Copy(UnmanagedMemoryBlock<T> source)
{
var itemCount = source.Count;
var len = itemCount * InfoOf<T>.Size;
var ret = new UnmanagedMemoryBlock<T>(itemCount);
source.CopyTo(ret);
//source.AsSpan().CopyTo(ret.AsSpan()); //TODO! Benchmark at netcore 3.0, it should be faster than buffer.memorycopy.
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="address">The address of the first <typeparamref name="T"/></param>
/// <param name="count">How many <typeparamref name="T"/> to copy, not how many bytes.</param>
/// <returns></returns>
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> Copy(void* address, long count)
{
var ret = new UnmanagedMemoryBlock<T>(count);
new UnmanagedMemoryBlock<T>((T*)address, count).CopyTo(ret);
//source.AsSpan().CopyTo(ret.AsSpan()); //TODO! Benchmark at netcore 3.0, it should be faster than buffer.memorycopy.
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="address"></param>
/// <param name="count">How many <typeparamref name="T"/> to copy, not how many bytes.</param>
/// <returns></returns>
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> Copy(IntPtr address, long count)
{
return Copy((void*)address, count);
}
/// <summary>
///
/// </summary>
/// <param name="address">The address of the first <typeparamref name="T"/></param>
/// <param name="count">How many <typeparamref name="T"/> to copy, not how many bytes.</param>
/// <returns></returns>
[MethodImpl(OptimizeAndInline)]
public static UnmanagedMemoryBlock<T> Copy(T* address, long count)
{
return Copy((void*)address, count);
}
#endregion
public T this[long index]
{
[MethodImpl(OptimizeAndInline)] get => *(Address + index);
[MethodImpl(OptimizeAndInline)] set => *(Address + index) = value;
}
/// <summary>
/// Backwards-compatible indexer accepting int index.
/// </summary>
public T this[int index]
{
[MethodImpl(OptimizeAndInline)] get => this[(long)index];
[MethodImpl(OptimizeAndInline)] set => this[(long)index] = value;
}
[MethodImpl(Optimize)]
public void Reallocate(long length, bool copyOldValues = false)
{
if (copyOldValues)
{
var @new = new UnmanagedMemoryBlock<T>(length);
var bytes = Math.Min(Count, length) * InfoOf<T>.Size;
Buffer.MemoryCopy(Address, @new.Address, bytes, bytes);
Free();
this = @new;
}
else
{
//we do not have to allocate first in we do not copy values.
Free();
this = new UnmanagedMemoryBlock<T>(length);
}
}
[MethodImpl(Optimize)]
public void Reallocate(long length, T fill, bool copyOldValues = false)
{
if (copyOldValues)
{
var @new = new UnmanagedMemoryBlock<T>(length);
var bytes = Math.Min(Count, length) * InfoOf<T>.Size;
Buffer.MemoryCopy(Address, @new.Address, bytes, bytes);
if (length > Count)
{
@new.Fill(fill, Count, length - Count);
}
Free();
this = @new;
}
else
{
//we do not have to allocate first in we do not copy values.
Free();
this = new UnmanagedMemoryBlock<T>(length, fill);
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public void Fill(T value)
{
if (Count == 0)
return;
if (Unsafe.SizeOf<T>() == 1 && Count < uint.MaxValue)
{
T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
Unsafe.InitBlockUnaligned(Address, Unsafe.As<T, byte>(ref tmp), (uint)Count);
}
else
{
// Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
UInt64 length = (uint)Count;
if (length == 0)
return;
T* addr = Address;
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
ulong i = 0;
for (; i < (length & ~7UL); i += 8)
{
*(addr + (i)) = value;
*(addr + (i + 1)) = value;
*(addr + (i + 2)) = value;
*(addr + (i + 3)) = value;
*(addr + (i + 4)) = value;
*(addr + (i + 5)) = value;
*(addr + (i + 6)) = value;
*(addr + (i + 7)) = value;
}
if (i < (length & ~3UL))
{
*(addr + (i)) = value;
*(addr + (i + 1)) = value;
*(addr + (i + 2)) = value;
*(addr + (i + 3)) = value;
i += 4;
}
for (; i < length; i++)
{
addr[i] = value;
}
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public void Fill(T value, long offset, long count)
{
if (Count == 0 || count == 0)
return;
if (Unsafe.SizeOf<T>() == 1 && Count < uint.MaxValue)
{
if (Count - offset <= 0)
return;
T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
Unsafe.InitBlockUnaligned(Address + offset, Unsafe.As<T, byte>(ref tmp), (uint)count);
}
else
{
// Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
if (Count - offset <= 0)
return;
ulong length = (ulong)count;
T* addr = Address + offset;
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
ulong i = 0;
for (; i < (length & ~7UL); i += 8)
{
*(addr + (i)) = value;
*(addr + (i + 1)) = value;
*(addr + (i + 2)) = value;
*(addr + (i + 3)) = value;
*(addr + (i + 4)) = value;
*(addr + (i + 5)) = value;
*(addr + (i + 6)) = value;
*(addr + (i + 7)) = value;
}
if (i < (length & ~3UL))
{
*(addr + (i)) = value;
*(addr + (i + 1)) = value;
*(addr + (i + 2)) = value;
*(addr + (i + 3)) = value;
i += 4;
}
for (; i < length; i++)
{
addr[i] = value;
}
}
}
/// <summary>
/// Backwards-compatible overload accepting int index.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public T GetIndex(int index) => GetIndex((long)index);
/// <summary>
/// Backwards-compatible overload accepting int index.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public ref T GetRefTo(int index) => ref GetRefTo((long)index);
/// <summary>
/// Backwards-compatible overload accepting int index.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public void SetIndex(int index, ref T value) => SetIndex((long)index, ref value);
/// <summary>
/// Backwards-compatible overload accepting int index.
/// </summary>
[MethodImpl(OptimizeAndInline)]
public void SetIndex(int index, T value) => SetIndex((long)index, value);
[MethodImpl(OptimizeAndInline)]
public T GetIndex(long index)
{
return *(Address + index);
}
[MethodImpl(OptimizeAndInline)]
public ref T GetRefTo(long index)
{
return ref *(Address + index);
}
[MethodImpl(OptimizeAndInline)]
public void SetIndex(long index, ref T value)
{
*(Address + index) = value;
}
[MethodImpl(OptimizeAndInline)]
public void SetIndex(long index, T value)
{
*(Address + index) = value;
}
[MethodImpl(OptimizeAndInline)]
public void Free()
{
// Backwards-compatible "force free, ignore refcount" — used by
// legacy callers (ArraySlice.DangerousFree). New ARC-aware code
// should call Release instead.
_disposer.Dispose();
}
// ---------------------------------------------------------------
// ARC plumbing — forwards to the inner Disposer.
// ---------------------------------------------------------------
[MethodImpl(OptimizeAndInline)]
public bool TryAddRef() => _disposer.TryAddRef();
[MethodImpl(OptimizeAndInline)]
public void Release() => _disposer.Release();
[MethodImpl(OptimizeAndInline)]
public void Abandon() => _disposer.Abandon();
public bool IsReleased => _disposer.IsReleased;
/// <summary>
/// <c>true</c> when this block is held by at most one logical reference.
/// Forwards to the inner <see cref="Disposer"/>.
/// </summary>
public bool IsUniquelyReferenced => _disposer.IsUniquelyReferenced;
[MethodImpl(OptimizeAndInline)]
public IEnumerator<T> GetEnumerator()
{
for (long i = 0; i < Count; i++) yield return GetIndex(i);
}
[MethodImpl(OptimizeAndInline)]
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[MethodImpl(OptimizeAndInline)]
public bool Contains(T item)
{
long len = Count;
for (long i = 0; i < len; i++)
{
if ((*(Address + i)).Equals(item)) return true;
}
return false;
}
[MethodImpl(Optimize)]
public void CopyTo(T[] array, int arrayIndex)
{
long len = Count;
for (long i = 0; i < len; i++)
{
array[i + arrayIndex] = *(Address + i);
}
}
[MethodImpl(Optimize)]
public void CopyTo(UnmanagedMemoryBlock<T> memoryBlock, long arrayIndex)
{
//TODO! at netcore 3, AsSpan.CopyTo might be faster.
if (memoryBlock == null)
throw new ArgumentNullException(nameof(memoryBlock));
if ((ulong)arrayIndex > (ulong)memoryBlock.Count || Count > memoryBlock.Count - arrayIndex)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
Buffer.MemoryCopy(Address, memoryBlock.Address + arrayIndex, InfoOf<T>.Size * (memoryBlock.Count - arrayIndex), InfoOf<T>.Size * Count);
}
[MethodImpl(Optimize)]
public void CopyTo(T* array, long arrayIndex, long lengthToCopy)
{
//TODO! at netcore 3, AsSpan.CopyTo might be faster.
var len = InfoOf<T>.Size * lengthToCopy;
Buffer.MemoryCopy(Address + arrayIndex, array, len, len);
}
/// <summary>Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.</summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing. </param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="array" /> is <see langword="null" />. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="arrayIndex" /> is less than zero. </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array" /> is multidimensional.-or- The number of elements in the source <see cref="T:System.Collections.ICollection" /> is greater than the available space from <paramref name="arrayIndex" /> to the end of the destination <paramref name="array" />.-or-The type of the source <see cref="T:System.Collections.ICollection" /> cannot be cast automatically to the type of the destination <paramref name="array" />.</exception>
[MethodImpl(Optimize)]
public void CopyTo(Array array, int arrayIndex)
{
if (!(array is T[] arr))
throw new InvalidCastException("Unable to CopyTo a type that is not " + typeof(T).Name + "[]");
CopyTo(arr, arrayIndex);
}
/// <summary>
/// Performs a copy to this memory block.
/// </summary>
/// <returns></returns>
public UnmanagedMemoryBlock<T> Clone()
{
var ret = new UnmanagedMemoryBlock<T>(Count);
this.CopyTo(ret);
return ret;
}
#region Explicit Implementations
/// <summary>
/// The size of a single item stored in <see cref="IMemoryBlock.Address"/>.
/// </summary>
int IMemoryBlock.ItemLength => InfoOf<T>.Size;
/// <summary>
/// The start address of this memory block.
/// </summary>
unsafe T* IMemoryBlock<T>.Address => Address;
/// <summary>
/// The start address of this memory block.
/// </summary>
unsafe void* IMemoryBlock.Address => Address;
/// <summary>
/// How many items are stored in <see cref="IMemoryBlock.Address"/>?
/// </summary>
/// <remarks></remarks>
long IMemoryBlock.Count => Count;
/// <summary>
/// The items with length of <see cref="IMemoryBlock.TypeCode"/> are present in <see cref="IMemoryBlock.Address"/>.
/// </summary>