Skip to content

Removing unsafe parts of Decode method in QueryStringEnumerable #56630

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

Merged
merged 4 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -18,7 +18,7 @@ public class QueryCollectionBenchmarks
private string _singleValueWithPlus;
private string _encoded;

[IterationSetup]
[GlobalSetup]
public void Setup()
{
_queryString = "?key1=value1&key2=value2&key3=value3&key4=&key5=";
Expand Down
15 changes: 6 additions & 9 deletions src/Shared/QueryStringEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ public Enumerator GetEnumerator()
/// </summary>
public readonly struct EncodedNameValuePair
{
private static readonly SearchValues<char> DecodingChars = SearchValues.Create("%+");

/// <summary>
/// Gets the name from this name/value pair in its original encoded form.
/// To get the decoded string, call <see cref="DecodeName"/>.
Expand Down Expand Up @@ -88,21 +90,16 @@ public ReadOnlyMemory<char> DecodeName()
public ReadOnlyMemory<char> DecodeValue()
=> Decode(EncodedValue);

private static unsafe ReadOnlyMemory<char> Decode(ReadOnlyMemory<char> chars)
private static ReadOnlyMemory<char> Decode(ReadOnlyMemory<char> chars)
{
// If the value is short, it's cheap to check up front if it really needs decoding. If it doesn't,
// then we can save some allocations.
if (chars.Length < 16 && chars.Span.IndexOfAny('%', '+') < 0)
ReadOnlySpan<char> source = chars.Span;
if (source.Length < 16 && source.IndexOfAny(DecodingChars) < 0)
{
return chars;
}

#pragma warning disable CS8500 // This takes the address of, gets the size of, or declares a pointer to a managed type
ReadOnlySpan<char> span = chars.Span;
return Uri.UnescapeDataString(
string.Create(span.Length,
(IntPtr)(&span), static (dest, ptr) => ((ReadOnlySpan<char>*)ptr)->Replace(dest, '+', ' '))).AsMemory();
#pragma warning restore CS8500
return Uri.UnescapeDataString(string.Create(source.Length, source, static (dest, source) => source.Replace(dest, '+', ' '))).AsMemory();
}
}

Expand Down
Loading