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

Avoid allocating byte[] just to convert to string #3425

Merged
Merged
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
27 changes: 22 additions & 5 deletions sdk/src/Core/Amazon.Runtime/Internal/Util/StringUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using Amazon.Util;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using System.Buffers;

namespace Amazon.Runtime.Internal.Util
{
Expand All @@ -32,7 +33,7 @@ public static class StringUtils
private static readonly Encoding UTF_8 = Encoding.UTF8;
private static readonly char[] rfc7230HeaderFieldValueDelimeters = "\"(),/:;<=>?@[\\]{}".ToCharArray();

public static string FromString(String value)
public static string FromString(String value)
{
return value;
}
Expand All @@ -49,14 +50,30 @@ public static string FromString(ConstantClass value)

public static string FromMemoryStream(MemoryStream value)
{
return Convert.ToBase64String(value.ToArray());
if (value.TryGetBuffer(out var buffer))
{
return Convert.ToBase64String(buffer.Array, buffer.Offset, buffer.Count);
}
else
{
var array = ArrayPool<byte>.Shared.Rent((int)value.Length);
try
{
value.Read(array, 0, (int)value.Length);
return Convert.ToBase64String(array, 0, (int)value.Length);
}
finally
{
ArrayPool<byte>.Shared.Return(array);
}
}
}

public static string FromInt(int value)
{
return value.ToString(CultureInfo.InvariantCulture);
}

public static string FromInt(int? value)
{
if (!value.HasValue)
Expand Down Expand Up @@ -348,7 +365,7 @@ public static string FromValueTypeList<T>(IEnumerable<T> values) where T : struc
/// <param name="values">List of T</param>
/// <returns>Header value representing the list of T</returns>
[SuppressMessage("Microsoft.Globalization", "CA1308", Justification = "Value is not surfaced to user. Booleans have been lowercased by SDK precedent.")]
public static string FromValueTypeList<T>(List<T> values) where T : struct
public static string FromValueTypeList<T>(List<T> values) where T : struct
{
// ToString() on boolean types automatically Pascal Cases. Xml-based protocols
// are case sensitive and accept "true" and "false" as the valid set of booleans.
Expand Down Expand Up @@ -404,7 +421,7 @@ private static string EscapeHeaderListEntry(string headerListEntry)
if (headerListEntry.IndexOfAny(rfc7230HeaderFieldValueDelimeters) != -1)
{
return $"\"{headerListEntry.Replace("\"", "\\\"")}\"";
}
}

return headerListEntry;
}
Expand Down