From 2cf01b54d855f8b8a060b25975d2030b45759ce8 Mon Sep 17 00:00:00 2001 From: dotnet bot Date: Mon, 18 Jun 2018 10:45:42 -0700 Subject: [PATCH] Document span lifetime issue in CreateSpan (dotnet/corefxdotnet/coreclr#30490) (dotnet/coreclr#18528) The language rules around span safety that C# and F# adhere to assume there is no way to create a `Span` wrapper over a `ref` local / parameter. This means `ref` inputs into a method are not considered when calculating the allowed lifetime of a returned `Span`. Hence both CreateSpan and CreateReadOnlySpan will be assumed to have heap lifetime even when provided stack based inputs. Example: ``` c# Span Example() { int i = 42; Span span = MemoryMarshal.CreateSpan(ref i, length: 1); return span; // C# and F# will allow this } ``` In this case the actual lifetime of `span` is that of `i`. Yet the compiler doesn't consider the `ref i` input and hence believes this must be heap based and hence safe to return out of the method. This is okay as these methods are unsafe. But want to explicitly document that fact. More information on the safety rules can be found in the [span safety proposal](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/span-safety.md) Signed-off-by: dotnet-bot-corefx-mirror Commit migrated from https://github.com/dotnet/coreclr/commit/ac637552982717e72e473df03d0994e65c2dccd8 --- .../src/System/Runtime/InteropServices/MemoryMarshal.Fast.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.Fast.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.Fast.cs index e212f7d..c71c782 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.Fast.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.Fast.cs @@ -214,6 +214,7 @@ namespace System.Runtime.InteropServices /// /// A reference to data. /// The number of elements the memory contains. + /// The lifetime of the returned span will not be validated for safety by span-aware languages. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span CreateSpan(ref T reference, int length) => new Span(ref reference, length); @@ -224,6 +225,7 @@ namespace System.Runtime.InteropServices /// /// A reference to data. /// The number of elements the memory contains. + /// The lifetime of the returned span will not be validated for safety by span-aware languages. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan CreateReadOnlySpan(ref T reference, int length) => new ReadOnlySpan(ref reference, length); } -- 2.7.4