Skip to content

[API Proposal]: InlineArray to Span conversion without Unsafe.As #105586

Open
@jkotas

Description

@jkotas

Background and motivation

C# allows an implicit conversion of InlineArray to Span. To perform this implicit conversion, Roslyn emits calls of several unsafe methods today (Unsafe.As, MemoryMarshal.CreateSpan).

Example: https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQAwAIpwHQCUCuAdgC4CWAtgKbYDCA9uQA6kA2lATgMocBupAxpQDOAbmTIoAFnQBZABQBKZAG9k6dQFFSAcwAWxDWyokh6Sjv2HKx4qYC86YJQBmAQ3wtiYpOvSdGroQAPKQkAHzoQgGE6A7megZGlCYivujIAL7iSADaAJKELKGUAILs7K4AnnIAHAoAushCxOz4/MToWglWNkIqar6hHZRJJN4ZQA===

In hindsight, we have realized that allowing Roslyn to produce unverifiable IL for safe C# is very slippery slope. Instead, we would like safe C# constructs to always produce IL that is verifiable using verification rules written in the same spirit as the existing ECMA-335 verification rules.

The proposed API enables Roslyn to perform the InlineArray to Span conversion without use of unsafe or unverifiable IL.

API Proposal

namespace System.Runtime.CompilerServices;

public class RuntimeHelpers
{
    public static Span<TElement> InlineArrayAsSpan<TInlineArray, TElement>(ref TInlineArray inlineArray) where TInlineArray: allows ref struct;
    public static ReadOnlySpan<TElement> InlineArrayAsReadOnlySpan<TInlineArray, TElement>(ref readonly TInlineArray inlineArray) where TInlineArray: allows ref struct;

}

API Usage

This API is not meant to be used directly by user code. It called by Roslyn generated code to perform InlineArray to Span conversion.

Alternative Designs

No response

Risks

The API is intrinsic with non-trivial expansion logic.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions