Skip to content
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
@@ -0,0 +1,33 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.Http.Abstractions.Microbenchmarks;

[MemoryDiagnoser]
public class SetHeaderJoinedBenchmark
{
private readonly HeaderDictionary _dictionary = new HeaderDictionary();
private readonly StringValues _singleValue = new StringValues("GET");
private readonly StringValues _manyValues = new StringValues(new[] { "GET", "POST", "PUT", "DELETE" });
private readonly StringValues _quotedValues = new StringValues(new[] { "a,b", "c" });
private readonly string[] _appendValues = new[] { "X-Custom-Header", "X-Other-Header" };

[Benchmark]
public void SetSingleValue() => ParsingHelpers.SetHeaderJoined(_dictionary, "Access-Control-Allow-Methods", _singleValue);

[Benchmark]
public void SetManyValues() => ParsingHelpers.SetHeaderJoined(_dictionary, "Access-Control-Allow-Methods", _manyValues);

[Benchmark]
public void SetValuesNeedingQuotes() => ParsingHelpers.SetHeaderJoined(_dictionary, "X-Values", _quotedValues);

[Benchmark]
public void AppendValues()
{
_dictionary["Access-Control-Expose-Headers"] = "X-Existing";
ParsingHelpers.AppendHeaderJoined(_dictionary, "Access-Control-Expose-Headers", _appendValues);
}
}
84 changes: 74 additions & 10 deletions src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -57,20 +58,83 @@ public static void SetHeaderJoined(IHeaderDictionary headers, string key, String
}
else
{
headers[key] = string.Join(',', value.Select(QuoteIfNeeded));
headers[key] = JoinQuoted(prefix: null, value);
}
}

// Quote items that contain commas and are not already quoted.
private static string? QuoteIfNeeded(string? value)
// Joins the values with ',' (null values are treated as empty), quoting items that contain commas and are not already quoted.
// When prefix is not null, the result is prefix + "," + joined values.
private static string JoinQuoted(string? prefix, StringValues values)
{
if (!string.IsNullOrEmpty(value) &&
value.Contains(',') &&
(value[0] != '"' || value[value.Length - 1] != '"'))
var count = values.Count;

if (prefix is null && count == 1)
{
return $"\"{value}\"";
var single = values[0];
if (!NeedsQuotes(single))
{
return single ?? string.Empty;
}
}
return value;

var length = prefix is null ? count - 1 : prefix.Length + count;
for (var i = 0; i < count; i++)
{
var value = values[i];
if (value is not null)
{
length += NeedsQuotes(value) ? value.Length + 2 : value.Length;
}
}

return string.Create(length, (prefix, values), static (span, state) =>
{
var position = 0;
if (state.prefix is not null)
{
state.prefix.AsSpan().CopyTo(span);
position = state.prefix.Length;
span[position++] = ',';
}

var values = state.values;
for (var i = 0; i < values.Count; i++)
{
if (i > 0)
{
span[position++] = ',';
}

var value = values[i];
if (value is null)
{
continue;
}

if (NeedsQuotes(value))
{
span[position++] = '"';
value.AsSpan().CopyTo(span.Slice(position));
position += value.Length;
span[position++] = '"';
}
else
{
value.AsSpan().CopyTo(span.Slice(position));
position += value.Length;
}
}

Debug.Assert(position == span.Length);
});
}

// Items that contain commas and are not already quoted need to be quoted.
private static bool NeedsQuotes([NotNullWhen(true)] string? value)
{
return !string.IsNullOrEmpty(value) &&
value.Contains(',') &&
(value[0] != '"' || value[value.Length - 1] != '"');
}

private static string? DeQuote(string? value)
Expand Down Expand Up @@ -116,7 +180,7 @@ public static void AppendHeaderJoined(IHeaderDictionary headers, string key, par
}
else
{
headers[key] = existing + "," + string.Join(',', values.Select(QuoteIfNeeded));
headers[key] = JoinQuoted(existing, values);
}
}

Expand Down
93 changes: 93 additions & 0 deletions src/Http/Http/test/HeaderDictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,97 @@ public void ReturnsCorrectStringValuesEmptyForMissingHeaders(bool withStore)
IDictionary<string, StringValues> asIDictionary = emptyHeaders;
Assert.Throws<KeyNotFoundException>(() => asIDictionary["Header1"]);
}

[Theory]
[InlineData(new[] { "a" }, "a")]
[InlineData(new[] { "a", "b" }, "a,b")]
[InlineData(new[] { "a,b" }, "\"a,b\"")]
[InlineData(new[] { "\"a,b\"" }, "\"a,b\"")]
[InlineData(new[] { "\"a,b" }, "\"\"a,b\"")]
[InlineData(new[] { "a,b\"" }, "\"a,b\"\"")]
[InlineData(new[] { "," }, "\",\"")]
[InlineData(new[] { "\"" }, "\"")]
[InlineData(new[] { "a,b", "c", "\"d,e\"" }, "\"a,b\",c,\"d,e\"")]
[InlineData(new[] { null, "b" }, ",b")]
[InlineData(new[] { "a", null }, "a,")]
[InlineData(new[] { "", "" }, ",")]
[InlineData(new[] { "", "a,b" }, ",\"a,b\"")]
public void SetCommaSeparatedValues_JoinsAndQuotesValues(string[] values, string expected)
{
var headers = new HeaderDictionary();

headers.SetCommaSeparatedValues("Header1", values);

Assert.Equal(expected, headers["Header1"].ToString());
Assert.Equal(1, headers["Header1"].Count);
}

public static TheoryData<string[]> EmptyHeaderValues => new()
{
Array.Empty<string>(),
new[] { "" },
new string[] { null },
};

[Theory]
[MemberData(nameof(EmptyHeaderValues))]
public void SetCommaSeparatedValues_RemovesHeaderForEmptyValues(string[] values)
{
var headers = new HeaderDictionary
{
["Header1"] = "existing"
};

headers.SetCommaSeparatedValues("Header1", values);

Assert.False(headers.ContainsKey("Header1"));
}

[Theory]
[InlineData(new[] { "a" }, "x,a")]
[InlineData(new[] { "a", "b,c" }, "x,a,\"b,c\"")]
[InlineData(new[] { "\"b,c\"" }, "x,\"b,c\"")]
[InlineData(new[] { "" }, "x,")]
[InlineData(new string[] { null }, "x,")]
[InlineData(new[] { null, "a" }, "x,,a")]
public void AppendCommaSeparatedValues_AppendsToExistingValue(string[] values, string expected)
{
var headers = new HeaderDictionary
{
["Header1"] = "x"
};

headers.AppendCommaSeparatedValues("Header1", values);

Assert.Equal(expected, headers["Header1"].ToString());
Assert.Equal(1, headers["Header1"].Count);
}

[Fact]
public void AppendCommaSeparatedValues_AppendsToMultipleExistingValues()
{
var headers = new HeaderDictionary
{
["Header1"] = new StringValues(new[] { "x", "y" })
};

headers.AppendCommaSeparatedValues("Header1", "a", "b,c");

Assert.Equal("x,y,a,\"b,c\"", headers["Header1"].ToString());
Assert.Equal(1, headers["Header1"].Count);
}

[Fact]
public void AppendCommaSeparatedValues_SetsValueWhenHeaderIsMissing()
{
var headers = new HeaderDictionary();

headers.AppendCommaSeparatedValues("Header1", "a", "b,c");
headers.AppendCommaSeparatedValues("Header2", "");
headers.AppendCommaSeparatedValues("Header3");

Assert.Equal("a,\"b,c\"", headers["Header1"].ToString());
Assert.False(headers.ContainsKey("Header2"));
Assert.False(headers.ContainsKey("Header3"));
}
}
Loading