Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix SearchValues fixer introducing slight changes for edge case inputs #6926

Merged
merged 1 commit into from
Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,19 @@ protected override SyntaxNode GetDeclaratorInitializer(SyntaxNode syntax)
values.Count <= 128 && // Arbitrary limit to avoid emitting huge literals
!ContainsAnyComments(creationSyntax)) // Avoid removing potentially valuable comments
{
if (isByte)
{
foreach (char c in values)
{
if (c > 127)
{
// We shouldn't turn non-ASCII byte values into Utf8StringLiterals as that may change behavior.
// e.g. (byte)'ÿ' means 0xFF, but "ÿ"u8 is two bytes (0xC3, 0xBF) that encode that character in UTF8.
return null;
}
}
}

string valuesString = string.Concat(values);
string stringLiteral = SymbolDisplay.FormatLiteral(valuesString, quote: true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,42 @@ private void TestMethod(string text)
await VerifyCodeFixAsync(LanguageVersion.CSharp7_3, source, expected);
}

[Fact]
public async Task TestCodeFixerDoesNotUseUtf8StringLiteralsForNonAsciiChars()
{
string source =
"""
using System;
using System.Buffers;

internal sealed class Test
{
private void TestMethod(ReadOnlySpan<byte> span)
{
_ = span.IndexOfAny([|new[] { (byte)'ÿ', (byte)'a', (byte)'e', (byte)'i', (byte)'o', (byte)'u' }|]);
}
}
""";

string expected =
"""
using System;
using System.Buffers;

internal sealed class Test
{
private static readonly SearchValues<byte> s_myBytes = SearchValues.Create(new[] { (byte)'ÿ', (byte)'a', (byte)'e', (byte)'i', (byte)'o', (byte)'u' });

private void TestMethod(ReadOnlySpan<byte> span)
{
_ = span.IndexOfAny(s_myBytes);
}
}
""";

await VerifyCodeFixAsync(LanguageVersion.CSharp11, source, expected);
}

[Fact]
public static async Task TestCodeFixerDoesNotRemoveTheOriginalMemberIfPublic()
{
Expand Down