NativeCollections 1.7.5
See the version list below for details.
dotnet add package NativeCollections --version 1.7.5
NuGet\Install-Package NativeCollections -Version 1.7.5
<PackageReference Include="NativeCollections" Version="1.7.5" />
<PackageVersion Include="NativeCollections" Version="1.7.5" />
<PackageReference Include="NativeCollections" />
paket add NativeCollections --version 1.7.5
#r "nuget: NativeCollections, 1.7.5"
#:package NativeCollections@1.7.5
#addin nuget:?package=NativeCollections&version=1.7.5
#tool nuget:?package=NativeCollections&version=1.7.5
NativeCollections
Pure C# collections, atomics, allocators, and concurrency primitives backed by unmanaged memory, with managed fallbacks only where documented. The public surface mirrors the .NET BCL where practical, and types backed by native storage do not allocate managed objects on their hot paths.
Design model
The prefix defines ownership only for the wrappers below. Static support types (NativeMemoryAllocator, NativeHashCode, NativeBitwise, NativeRandom) also use the Native prefix but hold no resource.
| Flavor | Storage and ownership | Lifetime |
|---|---|---|
Native* |
Holds the resource behind a handle: usually a pointer to the underlying Unsafe* value, a GCHandle for BCL-backed types, or the buffer itself for the NativeArray family. Dispose frees it; scope types such as NativeReaderWriterLockScope release a lock instead. |
Dispose the owning value exactly once. |
Unsafe* |
Stores its state directly in the struct: a buffer pointer for collections and views, or a NativeObject<T> handle for BCL-backed wrappers. Dispose frees an owning value's buffer or handle; UnsafeDisposable<T> instead disposes the wrapped value, and views such as UnsafeString free nothing. |
Dispose only the owning values, exactly once. |
Stackalloc* |
Operates on a caller-provided buffer. Never allocates or frees it. | No Dispose; the caller owns the buffer lifetime. |
| Shared support | Allocators, hashing, bitwise, and random. These hold no handle and define no Dispose. |
No resource lifetime. |
Where an Unsafe* counterpart exists, Native* forwards to it; the NativeArray family stores its buffer pointer directly. Stackalloc* offers the same core operations over fixed storage, but no growth members. Member names, results, and semantics are kept aligned across flavors; any difference must be documented. [BindingType] records the type that the decorated type is bound to.
- Stream growth differs by flavor.
UnsafeMemoryStream.SetLengthreturnsvoidand may grow its backing buffer;StackallocMemoryStream.SetLengthreturnsboolbecause it cannot grow a caller-provided buffer, returningfalsewhen the requested length exceedsCapacity. - No ownership tracking. There are no ownership flags, reference counts, or idempotent
Dispose. Double free, freeing memory you did not allocate, and using a disposed instance are caller errors with undefined behavior, not library bugs. TheGCHandlewrappersNativeObject<T>,NativeMemory<T>,NativeArrayRef<T>, andNativeMonitorLockfollow the same rule: they keep no ownership state, andIsCreatedonly observes the instance'sreadonlyhandle field. - Owning values are not shareable. Copying an owning
Native*orUnsafe*value copies its handle or pointer, not the resource; only one copy may be disposed. - Repeated or copied
GCHandledisposal is caller error.IsCreatedinNativeObject<T>,NativeMemory<T>,NativeArrayRef<T>, andNativeMonitorLockonly observes the instance'sreadonlyhandle field. Because that field cannot be cleared, a secondDispose()on the same instance, or aDispose()on any copy after one copy has freed the handle, frees the sameGCHandleagain. That is caller error with undefined behavior and must not be reported as a library bug. Keep exactly one owning instance, dispose it once, and pass references or views to everything else. - Views are not owned.
From(Span<T>),FromBytes,Slice, and span accessors such asAsSpan/AsReadOnlySpancreate views over existing memory. Never dispose a view, and never free an interior pointer. A factory that accepts an existing pointer or handle, such asNativeObject<T>.From(GCHandle)orNativePtr<T>.From(T*), transfers ownership of it to the returned value.
Behavior contract
- BCL parity. Types marked
FromType.Standardfollow the corresponding BCL type. Documented deviations are intentional.FromType.NotImplementedmeans the type wraps a managed BCL object instead of using native storage; its API and thread safety are those of the wrapped type.FromType.Nonemarks a type with no BCL counterpart. - Sizing.
Countis the logical element count.Capacityis allocated storage.NativeArray<T>.LengthandCountare the fixed element count of the buffer it wraps.UnsafeStringBuilder<T>.Length/Countis the logical element count,Capacitythe allocated element count,Buffera span over the whole storage, andTexta span over the logical content. - Unchecked indexing. Indexers are unchecked unless a type documents otherwise; the checked ones go through
Span<T>and throwIndexOutOfRangeException(for exampleUnsafeStringBuilder<T>). Where unchecked, callers must stay within0 .. Count - 1or the documented range, and violations are caller errors that yield garbage values or memory corruption, never exceptions. - Bool and Try results.
Try*,Write*, and other bool APIs returnfalsefor "already present", "not found", or "insufficient capacity" exactly as documented; they never throw for these outcomes.InsertResultreportsNone(the default),Success,AlreadyExists,Overwritten, orInsufficientCapacity. None of these outcomes is an exception. - Exceptions. Argument errors throw
ArgumentException/ArgumentOutOfRangeException; invalid states throwInvalidOperationException; unsupported operations throwNotSupportedException. Public members document the exceptions they throw, with their trigger conditions. - Allocation failure. Allocation failure throws
OutOfMemoryException, unless an abort callback was installed throughNativeMemoryAllocator.Custom; that callback then runs, and the allocation helper throwsOutOfMemoryExceptionwhen it returns. The library does not retry, clean up, or roll back on allocation failure; that policy belongs to the caller. - Enumeration.
foreachuses pattern-basedGetEnumerator(), which returns an enumerator holding a pointer to the source, so the source must not move while it is enumerated.IEnumerable<T>.GetEnumerator()throwsNotSupportedExceptionto avoid boxing, so LINQ and interface-based enumeration are unsupported. Mutations that bump the collection version invalidate enumerators, which then throwInvalidOperationException; each type documents which operations bump it (for example,UnsafeDictionary.Removedoes not). Enumerators that own traversal state must be disposed when used manually. - Equality and hashing. Collection and handle values compare the whole struct byte for byte, padding included, through
SpanHelpers; buffers passed to constructors marked[MustBeZeroed]must be zero-initialized; text types compare content. Types that declareIEquatable<T>provideEquals(T); equality operators,GetHashCode, andToStringare not guaranteed and exist only where documented. Atomics are the exception: their obsoleteEquals(object)/GetHashCodethrowNotSupportedException. - Atomics.
UnsafeAtomic*values must have a stable address: pin them withfixedor store them in unmanaged memory. Default operations are sequentially consistent;Load/Storetake an explicitOrdering(RelaxedthroughSeqCst), andLoadrejectsReleasewhileStorerejectsAcquirewithNotSupportedException. Do not copy an atomic while it is in use. - Concurrency. Thread safety is limited to
UnsafeAtomic*types,Concurrency/andThreading/types, and types documented as thread-safe. Ordinary collections have no internal locking; concurrent use is a caller error. On concurrent collections,Countis an observation that may be stale; useIsEmptyfor decisions. - Customization.
NativeMemoryAllocator.Custom,NativeHashCode.Custom, andUnsafeString.Customare process-wide hooks. Install them once, before any dependent type is used. Callbacks must be thread-safe and must not re-enter types that use the same hook.
Source conventions
- One public type per file; the file name is the type name, including the generic arity backtick (
UnsafeList`1.cs). Nested implementation types stay nested, and partial files add a dot-separated suffix before.cs(UnsafeStringBuilderExtensions.Format.cs). Directories follow flavor and category:Native/Collections,Unsafe/Atomics,Stackalloc/Pools,Specialized/Allocators, and so on. - Public value types use
[StructLayout(LayoutKind.Sequential)]and carry their flavor attribute withFromTypeflags; the only exceptions are theref structinterpolated-string handlers. Native wrappers arereadonly struct; owningUnsafe*collections are not, because their capacity and count change in place. - Every member, including private and internal ones, has XML documentation. Remarks state capacity, lifetime, ordering, and invariants;
<exception>tags list thrown exceptions. Comments must not restate the code. - Use
Unsafe.SizeOf<T>()orsizeof(T)for unmanaged element size and stride; neverMarshal.SizeOf. - Use the numeric conversion helpers (
I32,U32,Usize,Isize, and the sized variants) for size and index conversions. Signedness or width changes go through explicitFrom*/To*conversions, or*Uncheckedonly after a proven range check. Do not add ad-hoc casts or implicit conversions. - Access memory only through
Unsafe,UnsafeHelpers,MemoryMarshalHelpers, andSpanHelpers. Do not dereference, index, or perform arithmetic on raw pointers.CodeAnalysisenforces this rule. - The build enables
CheckForOverflowUnderflow. Use checked arithmetic for invariants,WrappingAdd/WrappingSub/WrappingMul/WrappingNegfor intentional wrap, and no ad-hocuncheckedblocks outside conversion or wrapping helpers. [MustBePinned]marks a constructor, method, property, or parameter whose value must be pinned so the GC cannot relocate it.[MustBeDistinct]marks a constructor or parameter that must receive distinct values.[MustBeZeroed]marks a constructor or parameter that must be zero-initialized. These marker attributes document intent; nothing in the library enforces them at compile time or run time.- All target frameworks must compile:
net10.0,net9.0,net8.0,net7.0,net6.0,net5.0, andnetstandard2.1(C# 9). Guard newer APIs withNET*_0_OR_GREATER. MethodImplOptions.AggressiveInliningmarks hot forwarding and leaf members;NoInliningmarks throw, allocation, and slow path helpers. Change inlining only with benchmark evidence.- There are no third-party dependencies.
netstandard2.1alone referencesSystem.Runtime.CompilerServices.Unsafe.
Contributing
- Open an issue with the target framework, a minimal repro, expected behavior, and actual behavior.
- Keep one logical change per commit or pull request. Do not mix formatting, refactoring, and behavior changes.
- Preserve public API, ABI, struct layout, ownership, capacity, and exception semantics. Treat changes to them as breaking changes and obtain explicit approval first.
- Document new or changed members, and update remarks whenever behavior, capacity, or lifetime changes.
- Satisfy the
CodeAnalysisrules and compile every target framework. For concurrent types, provide a multithreaded stress repro and run it on more than one target framework; the solution has no test project, so keep that repro outside the repository. - Remove generated files and run
git diff --checkbefore submitting. - Report the exact commands run, the target frameworks exercised, and the repro result before and after the change.
License
This project is licensed under the MIT License.
Rules
- Keep the flavor contracts intact: owning
Native*andUnsafe*values free their resource exactly once; views andStackalloc*never free. - Never add ownership tracking, reference counting, or automatic skipping of frees beyond the existing
GCHandlevalidity check. - Never catch, recover from, clean up after, or retry an allocation failure.
OutOfMemoryExceptionis a terminal contract, not a handled state. - Never convert a documented
falseresult (capacity, absence, orTryfailure) into an exception. - Never add locks, atomic state, or concurrency fallbacks to single-threaded types. Concurrent misuse is a caller error.
- Preserve sizing semantics exactly:
NativeArray<T>.Lengthis the fixed buffer length;UnsafeStringBuilderkeeps logical length and capacity separate;TrimExcesskeeps its documented behavior. - Preserve unchecked indexers and their documented valid ranges. Do not add hidden bounds checks.
- Preserve version and enumerator invalidation semantics precisely; do not add or remove version bumps.
- Preserve bitwise equality and hashing. Zero padding before hashing or comparing structs that contain it.
- Access pointers only through
Unsafehelpers. Never add raw pointer arithmetic, indexing, or dereferencing. - Convert numeric types only through the conversion helpers, with explicit checked or intentionally unchecked conversions.
- Use checked arithmetic unless wrap is intentional; express intentional wrap only through the
Wrapping*helpers. - Document every member: summary, type parameters, parameters, return value, exceptions, and remarks for capacity, lifetime, ordering, and invariants.
- Keep
Native*,Unsafe*, andStackalloc*APIs aligned. A missing member or a behavioral difference must be a documented design decision. - Compile and verify all seven target frameworks and every affected conditional-compilation branch.
- Do not add dependencies, change the public API, alter layout, or change exception behavior without explicit approval.
- Do not mix unrelated cleanup, formatting, naming, comments, or warnings into a behavior fix.
- Do not copy BCL behavior blindly. Match only the semantics this type documents, and record deliberate deviations in its remarks.
- Prove a bug with a minimal repro before changing semantics; state the observed result before and after.
- Ship no generated artifacts. Run
git diff --checkand review the exact diff before every commit.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 is compatible. net5.0-windows was computed. net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- System.Runtime.CompilerServices.Unsafe (>= 6.0.0)
-
net10.0
- No dependencies.
-
net5.0
- No dependencies.
-
net6.0
- No dependencies.
-
net7.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on NativeCollections:
| Package | Downloads |
|---|---|
|
zENet
ENet reliable UDP networking library with no binary dependencies. |
GitHub repositories (1)
Showing the top 1 popular GitHub repositories that depend on NativeCollections:
| Repository | Stars |
|---|---|
|
Molth/enet-csharp
ENet pure C# translation
|
| Version | Downloads | Last Updated | |
|---|---|---|---|
| 1.7.7 | 103 | 11/14/2026 | |
| 1.7.6 | 99 | 11/10/2026 | |
| 1.7.5 | 94 | 11/8/2026 | |
| 1.7.4 | 395 | 9/29/2026 | |
| 1.7.3 | 479 | 8/28/2026 | |
| 1.7.2 | 153 | 8/21/2026 | |
| 1.7.1 | 143 | 8/21/2026 | |
| 1.7.0 | 151 | 8/19/2026 | |
| 1.6.9 | 160 | 8/12/2026 | |
| 1.6.8 | 159 | 8/9/2026 | |
| 1.6.7 | 153 | 8/7/2026 | |
| 1.6.6 | 161 | 8/2/2026 | |
| 1.6.5 | 160 | 7/29/2026 | |
| 1.6.4 | 158 | 7/28/2026 | |
| 1.6.3 | 162 | 7/22/2026 | |
| 1.6.2 | 142 | 7/19/2026 | |
| 1.6.1 | 173 | 7/15/2026 | |
| 1.6.0 | 175 | 7/13/2026 | |
| 1.5.9 | 161 | 7/10/2026 | |
| 1.5.8 | 213 | 6/30/2026 |