Repository navigation
Expand file tree
/
Copy pathUnmanagedStorage.cs
More file actions
1811 lines (1597 loc) · 72.3 KB
/
Copy pathUnmanagedStorage.cs
File metadata and controls
1811 lines (1597 loc) · 72.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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using NumSharp.Backends.Iteration;
using NumSharp.Backends.Unmanaged;
using NumSharp.Utilities;
// ReSharper disable once CheckNamespace
namespace NumSharp.Backends
{
/// <summary>
/// Serves as a typed storage for an array.
/// </summary>
/// <remarks>
/// Responsible for :<br></br>
/// - store data type, elements, Shape<br></br>
/// - offers methods for accessing elements depending on shape<br></br>
/// - offers methods for casting elements<br></br>
/// - offers methods for change tensor order<br></br>
/// - GetData always return reference object to the true storage<br></br>
/// - GetData{T} and SetData{T} change dtype and cast storage<br></br>
/// - CloneData always create a clone of storage and return this as reference object<br></br>
/// - CloneData{T} clone storage and cast this clone <br></br>
/// </remarks>
public partial class UnmanagedStorage : ICloneable
{
/// <summary>
/// The 15 per-dtype <see cref="ArraySlice{T}"/> lanes overlapped at offset 0 — exactly one
/// lane (the one matching <see cref="_typecode"/>) is ever written or read over a storage's
/// lifetime, so the union holds the single live typed slice in 64 B instead of 15 separate
/// 64 B fields (−896 B per storage instance). The overlap is CLR-legal because every lane
/// has the identical layout for any T (T occurs only behind pointers: T*/void*/long/bool)
/// and the single managed reference — the non-generic <c>Disposer</c> inside
/// <see cref="UnmanagedMemoryBlock{T}"/> — sits at the same offset with the same type in
/// all lanes, so the GC ref map is well-formed (the type loader rejects the layout
/// otherwise). See docs/UNMANAGED_STORAGE_UNION_DESIGN.md.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
private struct TypedSlices
{
// %foreach supported_dtypes,supported_dtypes_lowercase%
// [FieldOffset(0)] public ArraySlice<#2> #1;
[FieldOffset(0)] public ArraySlice<bool> Boolean;
[FieldOffset(0)] public ArraySlice<sbyte> SByte;
[FieldOffset(0)] public ArraySlice<byte> Byte;
[FieldOffset(0)] public ArraySlice<short> Int16;
[FieldOffset(0)] public ArraySlice<ushort> UInt16;
[FieldOffset(0)] public ArraySlice<int> Int32;
[FieldOffset(0)] public ArraySlice<uint> UInt32;
[FieldOffset(0)] public ArraySlice<long> Int64;
[FieldOffset(0)] public ArraySlice<ulong> UInt64;
[FieldOffset(0)] public ArraySlice<char> Char;
[FieldOffset(0)] public ArraySlice<Half> Half;
[FieldOffset(0)] public ArraySlice<double> Double;
[FieldOffset(0)] public ArraySlice<float> Single;
[FieldOffset(0)] public ArraySlice<decimal> Decimal;
[FieldOffset(0)] public ArraySlice<System.Numerics.Complex> Complex;
}
private TypedSlices _slices;
public IArraySlice InternalArray;
public unsafe byte* Address;
public long Count;
protected Type _dtype;
protected NPTypeCode _typecode;
/// <summary>
/// The dtype DESCRIPTOR of this storage (NumPy's <c>PyArrayObject.descr</c>) — see <see cref="Descr"/>.
/// Lazily resolved from <see cref="_typecode"/> for the storage-backed builtins (each has exactly one canonical
/// descriptor, the class singleton), and reset whenever the storage's lane changes (<see cref="_Allocate"/>,
/// <c>ReplaceData</c>). A parametric descriptor (a future <c>datetime64[ns]</c>, whose unit lives on the
/// instance rather than in the enum) is stored here explicitly and travels with aliases/clones.
/// </summary>
protected DType _descr;
protected Shape _shape;
/// <summary>
/// The original storage this is a view of, or <c>null</c> if this storage owns its data.
/// </summary>
/// <remarks>
/// <para>
/// <b>Memory Model:</b> All views chain to the ultimate owner (not intermediate views).
/// When storage B is a view of A, and C is a view of B, then both B._baseStorage and
/// C._baseStorage point to A (not C → B → A).
/// </para>
/// <para>
/// <b>Memory Safety:</b> The underlying memory is kept alive by the shared Disposer
/// class reference in the UnmanagedMemoryBlock. This field provides semantic tracking
/// for the NumPy-compatible <see cref="NDArray.@base"/> property, not GC safety.
/// </para>
/// <para>
/// <b>Set by:</b> All three <see cref="Alias()"/> overloads,
/// <see cref="CreateBroadcastedUnsafe(UnmanagedStorage, Shape)"/>,
/// and both <see cref="GetData(int[])"/> overloads when creating views.
/// </para>
/// </remarks>
/// <seealso cref="BaseStorage"/>
/// <seealso cref="IsView"/>
internal UnmanagedStorage? _baseStorage;
/// <summary>
/// Gets the original storage this is a view of, or <c>null</c> if this storage owns its data.
/// </summary>
/// <value>
/// The ultimate owner storage for views, or <c>null</c> for owned data.
/// </value>
/// <remarks>
/// <para>
/// NumPy-compatible: All views chain to the ultimate owner (not intermediate views).
/// </para>
/// <para>
/// <b>Example:</b>
/// <code>
/// var a = np.arange(10); // a.Storage.BaseStorage == null (owns data)
/// var b = a["2:5"]; // b.Storage.BaseStorage == a.Storage
/// var c = b["1:2"]; // c.Storage.BaseStorage == a.Storage (chains to original!)
/// </code>
/// </para>
/// <para>
/// <b>Note:</b> This property is read-only by design. Allowing external modification would
/// risk breaking the memory ownership chain and could lead to use-after-free bugs.
/// </para>
/// </remarks>
/// <seealso href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.base.html"/>
public UnmanagedStorage? BaseStorage => _baseStorage;
/// <summary>
/// Gets a value indicating whether this storage is a view of another storage.
/// </summary>
/// <value>
/// <c>true</c> if this storage shares memory with another storage (does not own its data);
/// <c>false</c> if this storage owns its data.
/// </value>
/// <remarks>
/// <para>
/// Equivalent to checking <c>BaseStorage != null</c>.
/// </para>
/// <para>
/// <b>Use cases:</b>
/// <list type="bullet">
/// <item>Determine if an array can be safely modified without affecting other arrays</item>
/// <item>Optimize copy-on-write patterns</item>
/// <item>Debug memory sharing issues</item>
/// </list>
/// </para>
/// </remarks>
public bool IsView => _baseStorage != null;
/// <summary>
/// Set when this storage wraps FOREIGN memory that must never become writeable — a read-only
/// memory-mapped file (<c>np.load(mmap_mode: "r")</c>), or a buffer whose exporter declared it
/// read-only (<c>np.frombuffer</c> over a read-only <see cref="MemoryView"/>). It is the gate
/// NumPy expresses through the buffer protocol (its <c>_IsWriteable</c> asks the non-array base
/// for a writable buffer and a read-only exporter refuses): without it,
/// <c>setflags(write: true)</c> on an <c>'r'</c> memmap would re-enable WRITEABLE and the next
/// write would reach PROT_READ pages — an access violation, not an exception.
/// </summary>
/// <remarks>
/// Ordinary owned allocations and ordinary views never set this; a cleared WRITEABLE flag alone
/// (e.g. <c>a.flags.writeable = false</c> on your own array) is reversible and does NOT imply it.
/// </remarks>
internal bool WriteProtected;
/// <summary>
/// Set when this storage's memory belongs to a FOREIGN owner even though no
/// <see cref="_baseStorage"/> exists — a memory-mapped file (every <c>mmap_mode</c>, the file
/// mapping is the real owner), or an external buffer wrap. It is the NumPy analog of a
/// non-array <c>base</c> object: such arrays report <c>flags.owndata == False</c> (NumPy's
/// memmap does, in every mode) and <c>np.require(…, "O")</c> copies them.
/// </summary>
/// <remarks>Orthogonal to <see cref="WriteProtected"/>: an <c>'r+'</c> memmap is externally based
/// yet writable; an <c>'r'</c> memmap is both.</remarks>
internal bool ExternalBase;
/// <summary>
/// Does this storage own the memory it addresses — NumPy's <c>OWNDATA</c>: no base storage
/// (<see cref="_baseStorage"/>) and no foreign owner (<see cref="ExternalBase"/>). Read by
/// <c>ndarray.flags.owndata</c> and <c>np.require("O")</c>.
/// </summary>
internal bool OwnsData => _baseStorage is null && !ExternalBase;
/// <summary>
/// Post-transition hook — run after this storage's <see cref="_shape"/> is (re)assigned or its
/// ownership links (<see cref="_baseStorage"/> / <see cref="ExternalBase"/>) change. Reconciles
/// the shape's <see cref="ArrayFlags.OWNDATA"/> bit with <see cref="OwnsData"/> — the NumSharp
/// analog of NumPy's <c>PyArray_NewFromDescr_int</c>
/// (<c>ctors.c</c>: <c>fa->flags |= NPY_ARRAY_OWNDATA</c> when it allocates,
/// <c>fa->flags &= ~NPY_ARRAY_OWNDATA</c> when data is passed in) plus the invariant
/// NumPy asserts in <c>_IsWriteable</c> (<c>common.c</c>): <c>base != NULL ⟹ !OWNDATA</c>.
/// </summary>
/// <remarks>
/// Must be called wherever ownership or <see cref="_shape"/> transitions: at the end of every
/// allocating constructor / <see cref="_Allocate"/>, after every <see cref="_baseStorage"/>
/// assignment (views borrow the parent's shape, which carries the parent's bit), after
/// <see cref="ExternalBase"/> is raised, and in <see cref="SetShapeUnsafe(ref Shape)"/> /
/// the <c>ReplaceData</c> family (freshly built shapes never carry the bit, which would
/// silently strip it from an owner).
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected internal void OnReshaped()
{
bool owns = _baseStorage is null && !ExternalBase;
if (((_shape._flags & (int)ArrayFlags.OWNDATA) != 0) != owns)
_shape = owns
? _shape.WithFlags(flagsToSet: ArrayFlags.OWNDATA)
: _shape.WithFlags(flagsToClear: ArrayFlags.OWNDATA);
}
/// <summary>
/// May this array's WRITEABLE flag be turned (back) on? The NumSharp analog of NumPy's
/// <c>_IsWriteable</c> (<c>numpy/_core/src/multiarray/common.c</c>), consulted by
/// <see cref="NDArray.setflags"/> / <c>flags.writeable = true</c>:
/// <list type="bullet">
/// <item>an array over foreign read-only memory (<see cref="WriteProtected"/>) — never
/// (NumPy: the non-array base refuses a writable buffer);</item>
/// <item>a view — iff its base is writeable (NumPy walks the collapsed base chain and
/// accepts if ANY base is writeable; NumSharp's <see cref="_baseStorage"/> is flattened to
/// the ultimate owner, which is that same answer);</item>
/// <item>an owner of ordinary memory — always (NumPy: <c>base == NULL || OWNDATA</c>).</item>
/// </list>
/// </summary>
internal bool CanEnableWriteable()
{
if (WriteProtected)
return false;
var b = _baseStorage;
if (b is not null)
return b.Shape.IsWriteable && !b.WriteProtected;
return true;
}
/// <summary>
/// The data type of internal storage array.
/// </summary>
/// <value>numpys equal dtype</value>
/// <remarks>Has to be compliant with <see cref="NPTypeCode"/>.</remarks>
public Type DType => _dtype;
/// <summary>
/// The <see cref="NPTypeCode"/> of <see cref="IStorage.DType"/>.
/// </summary>
public NPTypeCode TypeCode => _typecode;
/// <summary>
/// The dtype DESCRIPTOR of this storage — NumPy's <c>PyArrayObject.descr</c>, the object <c>ndarray.dtype</c>
/// returns. For the storage-backed builtins this is the class's canonical instance
/// (<c>np.dtype("int32")</c> for an <see cref="NPTypeCode.Int32"/> lane — the same object every time, so
/// <c>a.dtype == b.dtype</c> is a cheap structural compare); a parametric descriptor is carried explicitly.
/// <see cref="DType"/> (the CLR element <see cref="System.Type"/>) and <see cref="TypeCode"/> stay the kernel
/// currency — the descriptor is the identity, they are its storage keys.
/// </summary>
public DType Descr
{
get
{
var descr = _descr;
if (descr is null)
{
var meta = DTypeRegistry.FromTypeCode(_typecode);
if (meta is null)
return null;
_descr = descr = meta.Singleton;
}
return descr;
}
}
/// <summary>
/// The size in bytes of a single value of <see cref="DType"/>
/// as stored in the unmanaged buffer.
/// </summary>
/// <remarks>
/// Returns the in-memory element stride, not the marshaling size.
/// For bool that is 1, not <see cref="Marshal.SizeOf(object)"/>'s 4
/// (bool is marshaled to win32 BOOL = int). All pointer arithmetic
/// over <c>Address</c> uses this value, so the in-memory layout is
/// the only correct reference.
/// </remarks>
public int DTypeSize
{
get
{
if (_typecode == NPTypeCode.String)
{
return IntPtr.Size;
}
return _typecode.SizeOf();
}
}
/// <summary>
/// The shape representing the data in this storage.
/// </summary>
public Shape Shape
{
get
{
return _shape;
}
set
{
this.Reshape(ref value);
}
}
/// <summary>
/// The shape representing the data in this storage.
/// </summary>
/// <remarks>It is dangerous to set Shape by reference. use Reshape(Shape) instead.</remarks>
public ref Shape ShapeReference => ref _shape;
/// <summary>
/// Returns an UnmanagedSpan representing this storage's memory.
/// </summary>
/// <remarks>This ignores completely slicing. Supports long indexing for arrays > 2B elements.</remarks>
public unsafe Span<T> AsSpan<T>() where T : unmanaged
{
Debug.Assert(typeof(T) == _dtype, $"AsSpan<{typeof(T).Name}> called on {_dtype.Name} array.");
if (!_shape.IsContiguous)
throw new InvalidOperationException("Unable to span a non-contiguous storage.");
return new Span<T>(Address, (int)Count);
}
/// <summary>
/// Returns an UnmanagedSpan representing this storage's memory.
/// </summary>
/// <remarks>This ignores completely slicing. Supports long indexing for arrays > 2B elements.</remarks>
public unsafe UnmanagedSpan<T> AsUnmanagedSpan<T>() where T : unmanaged
{
Debug.Assert(typeof(T) == _dtype, $"AsUnmanagedSpan<{typeof(T).Name}> called on {_dtype.Name} array.");
if (!_shape.IsContiguous)
throw new InvalidOperationException("Unable to span a non-contiguous storage.");
return new UnmanagedSpan<T>(Address, Count);
}
/// <summary>
/// The engine that was used to create this <see cref="IStorage"/>.
/// </summary>
public TensorEngine Engine { get; protected internal set; }
public static UnmanagedStorage Scalar<T>(T value) where T : unmanaged => new UnmanagedStorage(ArraySlice.Scalar<T>(value));
public static UnmanagedStorage Scalar(object value) => new UnmanagedStorage(ArraySlice.Scalar(value));
public static UnmanagedStorage Scalar(object value, NPTypeCode typeCode) => new UnmanagedStorage(ArraySlice.Scalar(value, typeCode));
/// <summary>
/// Creates a new storage with a broadcasted shape from an array slice.
/// </summary>
/// <param name="arraySlice">The array slice to wrap.</param>
/// <param name="shape">The broadcasted shape to represent this storage.</param>
/// <returns>
/// A new <see cref="UnmanagedStorage"/> that owns the data (not a view).
/// The returned storage's <see cref="_baseStorage"/> is <c>null</c>.
/// </returns>
/// <remarks>
/// <para>
/// <b>Named "Unsafe":</b> This method does not validate that the shape is compatible
/// with the array slice size.
/// </para>
/// <para>
/// <b>Ownership:</b> This overload creates owned storage (not a view) because it
/// receives raw data without storage context. Compare with the
/// <see cref="CreateBroadcastedUnsafe(UnmanagedStorage, Shape)"/> overload which
/// preserves base tracking.
/// </para>
/// </remarks>
public static UnmanagedStorage CreateBroadcastedUnsafe(IArraySlice arraySlice, Shape shape)
{
var ret = new UnmanagedStorage();
ret._Allocate(shape, arraySlice);
return ret;
}
/// <summary>
/// Creates a broadcasted view of an existing storage with a new shape.
/// </summary>
/// <param name="storage">The source storage to take <see cref="InternalArray"/> from.</param>
/// <param name="shape">The broadcasted shape to represent this storage.</param>
/// <returns>
/// A new <see cref="UnmanagedStorage"/> that shares memory with the source storage.
/// The returned storage's <see cref="_baseStorage"/> points to the ultimate owner.
/// </returns>
/// <remarks>
/// <para>
/// <b>Named "Unsafe":</b> This method does not validate that the shape is compatible
/// with the storage size.
/// </para>
/// <para>
/// <b>Base Tracking:</b> Sets <c>_baseStorage</c> to chain to the ultimate owner:
/// <list type="bullet">
/// <item>If source storage owns its data: <c>result._baseStorage = storage</c></item>
/// <item>If source storage is a view: <c>result._baseStorage = storage._baseStorage</c></item>
/// </list>
/// </para>
/// <para>
/// <b>Used By:</b> <c>np.broadcast_to()</c>, <c>np.broadcast_arrays()</c>, and
/// internal broadcasting operations.
/// </para>
/// </remarks>
/// <seealso cref="Alias()"/>
public static UnmanagedStorage CreateBroadcastedUnsafe(UnmanagedStorage storage, Shape shape)
{
var ret = new UnmanagedStorage();
ret._Allocate(shape, storage.InternalArray);
ret._baseStorage = storage._baseStorage ?? storage;
ret.OnReshaped(); // a view never owns its buffer (NumPy: base != NULL ⟹ !OWNDATA)
ret.Engine = storage.Engine;
return ret;
}
private UnmanagedStorage() { }
/// <summary>
/// <see cref="Shape.Scalar"/> with <see cref="ArrayFlags.OWNDATA"/> pre-set — the shape every
/// allocating scalar constructor stores (a fresh scalar storage owns its buffer; NumPy's
/// <c>ctors.c</c> raises <c>NPY_ARRAY_OWNDATA</c> on every allocating constructor). Pre-built
/// once so the hot scalar ctors pay no per-construction flag fixup.
/// </summary>
private static readonly Shape ScalarOwnedShape = Shape.Scalar.WithFlags(flagsToSet: ArrayFlags.OWNDATA);
/// <summary>
/// A fresh C-contiguous vector shape carrying <see cref="ArrayFlags.OWNDATA"/> — stored by the
/// allocating managed-array constructors, which copy <c>values</c> into brand-new unmanaged
/// memory this storage owns.
/// </summary>
private static Shape OwnedVectorShape(long length) => new Shape(length).WithFlags(flagsToSet: ArrayFlags.OWNDATA);
/// <summary>
/// Scalar constructor
/// </summary>
private unsafe UnmanagedStorage(IArraySlice values)
{
_shape = ScalarOwnedShape;
_dtype = (_typecode = values.TypeCode).AsType();
Address = (byte*)values.Address;
Count = 1;
SetInternalArray(values);
}
/// <summary>
/// Creates an empty storage of type <paramref name="dtype"/>.
/// </summary>
/// <param name="dtype">The type of this storage</param>
/// <remarks>Usually <see cref="Allocate(NumSharp.Shape,System.Type)"/> is called after this constructor.</remarks>
public UnmanagedStorage(Type dtype)
{
_dtype = dtype ?? throw new ArgumentNullException(nameof(dtype));
_typecode = dtype.GetTypeCode();
}
/// <summary>
/// Creates an empty storage of type <paramref name="typeCode"/>.
/// </summary>
/// <param name="typeCode">The type of this storage</param>
/// <remarks>Usually <see cref="Allocate(NumSharp.Shape,System.Type)"/> is called after this constructor.</remarks>
public UnmanagedStorage(NPTypeCode typeCode)
{
if (typeCode == NPTypeCode.Empty)
throw new ArgumentNullException(nameof(typeCode));
_dtype = typeCode.AsType();
_typecode = typeCode;
}
/// <summary>
/// Creates an empty storage described by <paramref name="descr"/> — NumPy's <c>PyArray_NewFromDescr</c> entry:
/// the descriptor IS the array's dtype (<see cref="Descr"/>), its class supplies the storage lane
/// (<see cref="TypeCode"/>) and CLR element type (<see cref="DType"/>).
/// </summary>
/// <param name="descr">The dtype descriptor; a non-native byte order is canonicalised (NumSharp buffers are always native).</param>
/// <exception cref="ArgumentNullException"><paramref name="descr"/> is null.</exception>
/// <exception cref="NotSupportedException">The descriptor's class has no storage lane yet (a datetime64/timedelta64 descriptor before Stage C).</exception>
/// <remarks>Usually <see cref="Allocate(NumSharp.Shape,NumSharp.DType,bool)"/> is called after this constructor.</remarks>
public UnmanagedStorage(DType descr)
{
if (descr is null)
throw new ArgumentNullException(nameof(descr));
_typecode = descr.GetTypeCode(); // throws the descriptive "no storage yet" for a descriptor-only class
_dtype = descr.type;
_descr = descr.isnative ? descr : descr.Meta.EnsureCanonical(descr);
}
private UnmanagedStorage(object value)
{
_Allocate(Shape.Scalar, ArraySlice.Scalar(value));
}
/// <summary>
/// Wraps given <paramref name="arraySlice"/> in <see cref="UnmanagedStorage"/>.
/// </summary>
/// <param name="arraySlice">The slice to wrap </param>
public UnmanagedStorage(IArraySlice arraySlice, Shape shape)
{
if (shape.IsEmpty)
throw new ArgumentNullException(nameof(shape));
if (shape.size != arraySlice.Count)
throw new IncorrectShapeException($"Given shape size ({shape.size}) does not match the size of the given storage size ({arraySlice.Count})");
_Allocate(shape, arraySlice);
}
// %foreach supported_dtypes,supported_dtypes_lowercase%
// public UnmanagedStorage(#2 scalar)
// {
// _dtype = typeof(#1);
// _typecode = InfoOf<#2>.NPTypeCode;
// _shape = ScalarOwnedShape;
// InternalArray = _slices.#1 = ArraySlice.Scalar<#2>(scalar);
// unsafe
// {
// Address = (byte*)_slices.#1.Address;
// Count = _slices.#1.Count;
// }
// }
// %
public UnmanagedStorage(bool scalar)
{
_dtype = typeof(Boolean);
_typecode = InfoOf<bool>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Boolean = ArraySlice.Scalar<bool>(scalar);
unsafe
{
Address = (byte*)_slices.Boolean.Address;
Count = _slices.Boolean.Count;
}
}
public UnmanagedStorage(byte scalar)
{
_dtype = typeof(Byte);
_typecode = InfoOf<byte>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Byte = ArraySlice.Scalar<byte>(scalar);
unsafe
{
Address = (byte*)_slices.Byte.Address;
Count = _slices.Byte.Count;
}
}
public UnmanagedStorage(short scalar)
{
_dtype = typeof(Int16);
_typecode = InfoOf<short>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Int16 = ArraySlice.Scalar<short>(scalar);
unsafe
{
Address = (byte*)_slices.Int16.Address;
Count = _slices.Int16.Count;
}
}
public UnmanagedStorage(ushort scalar)
{
_dtype = typeof(UInt16);
_typecode = InfoOf<ushort>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.UInt16 = ArraySlice.Scalar<ushort>(scalar);
unsafe
{
Address = (byte*)_slices.UInt16.Address;
Count = _slices.UInt16.Count;
}
}
public UnmanagedStorage(int scalar)
{
_dtype = typeof(Int32);
_typecode = InfoOf<int>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Int32 = ArraySlice.Scalar<int>(scalar);
unsafe
{
Address = (byte*)_slices.Int32.Address;
Count = _slices.Int32.Count;
}
}
public UnmanagedStorage(uint scalar)
{
_dtype = typeof(UInt32);
_typecode = InfoOf<uint>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.UInt32 = ArraySlice.Scalar<uint>(scalar);
unsafe
{
Address = (byte*)_slices.UInt32.Address;
Count = _slices.UInt32.Count;
}
}
public UnmanagedStorage(long scalar)
{
_dtype = typeof(Int64);
_typecode = InfoOf<long>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Int64 = ArraySlice.Scalar<long>(scalar);
unsafe
{
Address = (byte*)_slices.Int64.Address;
Count = _slices.Int64.Count;
}
}
public UnmanagedStorage(ulong scalar)
{
_dtype = typeof(UInt64);
_typecode = InfoOf<ulong>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.UInt64 = ArraySlice.Scalar<ulong>(scalar);
unsafe
{
Address = (byte*)_slices.UInt64.Address;
Count = _slices.UInt64.Count;
}
}
public UnmanagedStorage(char scalar)
{
_dtype = typeof(Char);
_typecode = InfoOf<char>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Char = ArraySlice.Scalar<char>(scalar);
unsafe
{
Address = (byte*)_slices.Char.Address;
Count = _slices.Char.Count;
}
}
public UnmanagedStorage(double scalar)
{
_dtype = typeof(Double);
_typecode = InfoOf<double>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Double = ArraySlice.Scalar<double>(scalar);
unsafe
{
Address = (byte*)_slices.Double.Address;
Count = _slices.Double.Count;
}
}
public UnmanagedStorage(float scalar)
{
_dtype = typeof(Single);
_typecode = InfoOf<float>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Single = ArraySlice.Scalar<float>(scalar);
unsafe
{
Address = (byte*)_slices.Single.Address;
Count = _slices.Single.Count;
}
}
public UnmanagedStorage(decimal scalar)
{
_dtype = typeof(Decimal);
_typecode = InfoOf<decimal>.NPTypeCode;
_shape = ScalarOwnedShape;
InternalArray = _slices.Decimal = ArraySlice.Scalar<decimal>(scalar);
unsafe
{
Address = (byte*)_slices.Decimal.Address;
Count = _slices.Decimal.Count;
}
}
// %foreach supported_dtypes,supported_dtypes_lowercase%
// public UnmanagedStorage(#1[] values)
// {
// if (values == null)
// throw new ArgumentNullException(nameof(values));
// _dtype = typeof(#1);
// _typecode = _dtype.GetTypeCode();
// _shape = OwnedVectorShape(values.Length);
// InternalArray = _slices.#1 = new ArraySlice<#2>(UnmanagedMemoryBlock<#2>.FromArray(values));
// unsafe
// {
// Address = (byte*)_slices.#1.Address;
// Count = values.Length;
// }
// }
// %
public UnmanagedStorage(Boolean[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Boolean);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Boolean = new ArraySlice<bool>(UnmanagedMemoryBlock<bool>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Boolean.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Byte[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Byte);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Byte = new ArraySlice<byte>(UnmanagedMemoryBlock<byte>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Byte.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Int16[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Int16);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Int16 = new ArraySlice<short>(UnmanagedMemoryBlock<short>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Int16.Address;
Count = values.Length;
}
}
public UnmanagedStorage(UInt16[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(UInt16);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.UInt16 = new ArraySlice<ushort>(UnmanagedMemoryBlock<ushort>.FromArray(values));
unsafe
{
Address = (byte*)_slices.UInt16.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Int32[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Int32);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Int32 = new ArraySlice<int>(UnmanagedMemoryBlock<int>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Int32.Address;
Count = values.Length;
}
}
public UnmanagedStorage(UInt32[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(UInt32);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.UInt32 = new ArraySlice<uint>(UnmanagedMemoryBlock<uint>.FromArray(values));
unsafe
{
Address = (byte*)_slices.UInt32.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Int64[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Int64);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Int64 = new ArraySlice<long>(UnmanagedMemoryBlock<long>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Int64.Address;
Count = values.Length;
}
}
public UnmanagedStorage(UInt64[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(UInt64);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.UInt64 = new ArraySlice<ulong>(UnmanagedMemoryBlock<ulong>.FromArray(values));
unsafe
{
Address = (byte*)_slices.UInt64.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Char[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Char);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Char = new ArraySlice<char>(UnmanagedMemoryBlock<char>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Char.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Double[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Double);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Double = new ArraySlice<double>(UnmanagedMemoryBlock<double>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Double.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Single[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Single);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Single = new ArraySlice<float>(UnmanagedMemoryBlock<float>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Single.Address;
Count = values.Length;
}
}
public UnmanagedStorage(Decimal[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
_dtype = typeof(Decimal);
_typecode = _dtype.GetTypeCode();
_shape = OwnedVectorShape(values.Length);
InternalArray = _slices.Decimal = new ArraySlice<decimal>(UnmanagedMemoryBlock<decimal>.FromArray(values));
unsafe
{
Address = (byte*)_slices.Decimal.Address;
Count = values.Length;
}
}
#region Switched Accessing
/// <summary>
/// Replace internal storage array with given array.
/// </summary>
/// <param name="array">The array to set as internal storage</param>
/// <exception cref="InvalidCastException">When type of <paramref name="array"/> does not match <see cref="DType"/> of this storage</exception>
protected unsafe void SetInternalArray(Array array)
{
switch (_typecode)
{
// //Since it is a single assignment, we do not use 'as' casting but rather explicit casting that'll also type-check.
// %foreach supported_dtypes,supported_dtypes_lowercase%
// case NPTypeCode.#1:
// {
// InternalArray = _slices.#1 = ArraySlice.FromArray<#2>((#2[])array);
// Address = (byte*) _slices.#1.Address;
// Count = _slices.#1.Count;
// break;
// }
// %
// default:
// throw new NotSupportedException();
//Since it is a single assignment, we do not use 'as' casting but rather explicit casting that'll also type-check.
case NPTypeCode.Boolean:
{
InternalArray = _slices.Boolean = ArraySlice.FromArray<bool>((bool[])array);
Address = (byte*)_slices.Boolean.Address;
Count = _slices.Boolean.Count;
break;
}
case NPTypeCode.SByte:
{
InternalArray = _slices.SByte = ArraySlice.FromArray<sbyte>((sbyte[])array);
Address = (byte*)_slices.SByte.Address;
Count = _slices.SByte.Count;
break;
}
case NPTypeCode.Byte:
{
InternalArray = _slices.Byte = ArraySlice.FromArray<byte>((byte[])array);
Address = (byte*)_slices.Byte.Address;
Count = _slices.Byte.Count;
break;
}
case NPTypeCode.Int16:
{
InternalArray = _slices.Int16 = ArraySlice.FromArray<short>((short[])array);
Address = (byte*)_slices.Int16.Address;
Count = _slices.Int16.Count;
break;
}
case NPTypeCode.UInt16:
{
InternalArray = _slices.UInt16 = ArraySlice.FromArray<ushort>((ushort[])array);
Address = (byte*)_slices.UInt16.Address;
Count = _slices.UInt16.Count;
break;
}
case NPTypeCode.Int32:
{
InternalArray = _slices.Int32 = ArraySlice.FromArray<int>((int[])array);
Address = (byte*)_slices.Int32.Address;
Count = _slices.Int32.Count;
break;
}
case NPTypeCode.UInt32:
{
InternalArray = _slices.UInt32 = ArraySlice.FromArray<uint>((uint[])array);
Address = (byte*)_slices.UInt32.Address;
Count = _slices.UInt32.Count;
break;
}
case NPTypeCode.Int64:
{
InternalArray = _slices.Int64 = ArraySlice.FromArray<long>((long[])array);
Address = (byte*)_slices.Int64.Address;
Count = _slices.Int64.Count;
break;
}
case NPTypeCode.UInt64:
{
InternalArray = _slices.UInt64 = ArraySlice.FromArray<ulong>((ulong[])array);
Address = (byte*)_slices.UInt64.Address;
Count = _slices.UInt64.Count;
break;
}
case NPTypeCode.Char:
{
InternalArray = _slices.Char = ArraySlice.FromArray<char>((char[])array);
Address = (byte*)_slices.Char.Address;
Count = _slices.Char.Count;
break;
}
case NPTypeCode.Half:
{
InternalArray = _slices.Half = ArraySlice.FromArray<Half>((Half[])array);
Address = (byte*)_slices.Half.Address;
Count = _slices.Half.Count;
break;
}
case NPTypeCode.Double:
{
InternalArray = _slices.Double = ArraySlice.FromArray<double>((double[])array);
Address = (byte*)_slices.Double.Address;
Count = _slices.Double.Count;
break;
}