Skip to content

Commit

Permalink
Document span lifetime issue in CreateSpan (dotnet/corefxdotnet/corec…
Browse files Browse the repository at this point in the history
…lr#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<T>` 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<T>`. Hence both
CreateSpan and CreateReadOnlySpan will be assumed to have heap lifetime
even when provided stack based inputs. Example:

``` c#
Span<int> Example() {
  int i = 42;
  Span<int> 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 <[email protected]>

Commit migrated from dotnet/coreclr@ac63755
  • Loading branch information
dotnet-bot authored and jkotas committed Jun 18, 2018
1 parent bdd9562 commit 2cf01b5
Showing 1 changed file with 2 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(span)),
/// </summary>
/// <param name="reference">A reference to data.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> CreateSpan<T>(ref T reference, int length) => new Span<T>(ref reference, length);

Expand All @@ -224,6 +225,7 @@ ref Unsafe.As<TFrom, TTo>(ref MemoryMarshal.GetReference(span)),
/// </summary>
/// <param name="reference">A reference to data.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <returns>The lifetime of the returned span will not be validated for safety by span-aware languages.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<T> CreateReadOnlySpan<T>(ref T reference, int length) => new ReadOnlySpan<T>(ref reference, length);
}
Expand Down

0 comments on commit 2cf01b5

Please sign in to comment.