Skip to content

[API Proposal]: TextEncoder.FindFirstCharacterToEncode(ReadOnlySpan<char>) #114423

Open
@EgorBo

Description

@EgorBo

Background and motivation

TextEncoder does not provide a safe version of FindFirstCharacterToEncode for UTF16, it only has an unsafe (accepting an unmanaged pointer) for UTF16 and a safe one for UTF8.

It's needed to remove an unnecessary unsafe context from System.Text.Json, see https://github.com/dotnet/runtime/pull/114154/files#r2025039597

This is part of the "remove unsafe" effort.

API Proposal

namespaceSystem.Text.Encodings.Web;

public abstract class TextEncoder
{
        public abstract unsafe int FindFirstCharacterToEncode(char* text, int textLength);
+       public int FindFirstCharacterToEncode(ReadOnlySpan<char> text);
        public virtual int FindFirstCharacterToEncodeUtf8(ReadOnlySpan<byte> utf8Text)
}

API Usage

return (encoder ?? JavaScriptEncoder.Default).FindFirstCharacterToEncode(value);

instead of what we currently have to do:

unsafe
{
    fixed (char* ptr = value)
    {
        return (encoder ?? JavaScriptEncoder.Default).FindFirstCharacterToEncode(ptr, value.Length);
    }
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions