Skip to content

Accessing folded conversion of string literals to UTF-8 from user code is problematic. #93501

Open

Description

@neon-sunset

Background

In scope of continued improvement of UTF-8 usability in .NET, thanks to #85328, the upcoming release has the ability to fold conversion of string literals to UTF-8 at callsites where JIT/AOT can recognize it.

Based on the results of reviewing Utf8.TryWriteInterpolatedStringHandler internals and the first third-party implementation at https://github.com/Cysharp/Utf8StringInterpolation, it appears, however, that only Utf8.TryWriteInterpolatedStringHandler itself is able to take advantage of this optimization, with UTF8EncodingSealed.ReadUtf8 remaining otherwise not accessible outside of CoreLib through normal means.

This means that alternate [InterpolatedStringHandler] implementations which enable scenarios like Utf8String.Format($"Today is {DateTime.Now}") are not able to (easily) use this optimization.

Proposal

As suggested by @EgorBo , one of the options could be including ReadUtf8 call into Encoding.UTF8.TryGetBytes which would enable the following patterns to be optimized:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AppendLiteral(string s)
{
    Retry:
    if (Encoding.UTF8.TryGetBytes(s, Free, out var written))
    {
        BytesWritten += written;
        return;
    }

    Grow();
    goto Retry;
}

Workarounds

  • Nesting Utf8.TryWriteInterpolatedStringHandler in another interpolated string handler, which is forced to duplicate stored state and re-create nested handler each time the buffer needs to be resized
  • Writing an unsafe proxy in IL with suppressed visibility checks that would resolve static Encoding.UTF8.s_default and corresponding UTF8EncodingSealed.ReadUtf8 (I'm not sure if this will work but in theory it may be possible)

Activity

  1. ghost added
    needs-area-label
    on Oct 14, 2023
  2. ghost added
    untriaged
    on Oct 14, 2023
  3. added
    area-CodeGen-coreclr
    and removed
    untriaged
    needs-area-label
    on Oct 14, 2023
  4. added this to the Future milestone on Oct 14, 2023
  5. self-assigned this
    on Oct 14, 2023
  6. EgorBo commented on Oct 14, 2023

    @EgorBo
    Member

    Marking as codegen as it needs some improvements there first. Marking as future, but will definitely give it a try in 9.0.

  7. neon-sunset commented on Apr 24, 2024

    @neon-sunset
    ContributorAuthor

    @EgorBo Small update: while revisiting interpolated handlers implementation in U8String, in the end, with UnsafeAccessor it was possible to access the folded conversion.

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    internal static void AppendConstantString<T>(ref T handler, [ConstantExpected] string s)
        where T : struct, IInterpolatedHandler // Multiple handler impls
    {
    Retry:
        var inner = new Utf8.TryWriteInterpolatedStringHandler(
            s.Length, 0, handler.Free, out _);
        if (inner.AppendLiteral(s))
        {
            handler.BytesWritten += inner.GetPosition();
            return;
        }
    
        handler.Grow();
        goto Retry;
    }
    
    [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_pos")]
    static extern ref int GetPosition(this ref Utf8.TryWriteInterpolatedStringHandler instance);

    It even unrolls the copies, honestly, performance win is too tempting to just go with this (bad) option 😅

    Edit: this was one step away from safely accessing it, at the cost of slight codegen regression - https://github.com/U8String/U8String/blob/main/Sources/U8String/Shared/U8Interpolation.cs#L250-L270

  8. EgorBo commented on Apr 24, 2024

    @EgorBo
    Member

    It even unrolls the copies, honestly, performance win is too tempting to just go with this (bad) option 😅

    Haha, nice! Although, just keep in mind that we don't guarantee API stability for internal stuff 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions