Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit eef6e8f

Browse files
committed
Optimize MD5 Hash for .net6
1 parent 11006a9 commit eef6e8f

File tree

2 files changed

+22
-16
lines changed

2 files changed

+22
-16
lines changed

src/ServiceStack.Text/StreamExtensions.cs

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -446,27 +446,23 @@ public static Task WriteAsync(this Stream stream, byte[] bytes, CancellationToke
446446
public static Task WriteAsync(this Stream stream, string text, CancellationToken token = default) =>
447447
MemoryProvider.Instance.WriteAsync(stream, text.AsSpan(), token);
448448

449-
public static string ToMd5Hash(this Stream stream)
449+
public static byte[] ToMd5Bytes(this Stream stream)
450450
{
451-
var hash = System.Security.Cryptography.MD5.Create().ComputeHash(stream);
452-
var sb = StringBuilderCache.Allocate();
453-
foreach (byte b in hash)
451+
#if NET6_0_OR_GREATER
452+
if (stream is MemoryStream ms)
453+
return System.Security.Cryptography.MD5.HashData(ms.GetBufferAsSpan());
454+
#endif
455+
if (stream.CanSeek)
454456
{
455-
sb.Append(b.ToString("x2"));
457+
stream.Position = 0;
456458
}
457-
return StringBuilderCache.ReturnAndFree(sb);
459+
return System.Security.Cryptography.MD5.Create().ComputeHash(stream);
458460
}
459461

460-
public static string ToMd5Hash(this byte[] bytes)
461-
{
462-
var hash = System.Security.Cryptography.MD5.Create().ComputeHash(bytes);
463-
var sb = StringBuilderCache.Allocate();
464-
foreach (byte b in hash)
465-
{
466-
sb.Append(b.ToString("x2"));
467-
}
468-
return StringBuilderCache.ReturnAndFree(sb);
469-
}
462+
public static string ToMd5Hash(this Stream stream) => ToMd5Bytes(stream).ToHex();
463+
464+
public static string ToMd5Hash(this byte[] bytes) =>
465+
System.Security.Cryptography.MD5.Create().ComputeHash(bytes).ToHex();
470466

471467
/// <summary>
472468
/// Returns bytes in publiclyVisible MemoryStream

tests/ServiceStack.Text.Tests/StreamTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,5 +52,15 @@ public void Does_escape_string_when_serializing_to_Stream()
5252
Assert.That(ssString, Is.EqualTo(expected));
5353
}
5454
}
55+
56+
[Test]
57+
public void Can_create_MD5_hashes_from_Stream()
58+
{
59+
var md5Hash = "35f184b0e35d7f5629e79cb4bc802893";
60+
var utf8Bytes = nameof(Can_create_MD5_hashes_from_Stream).ToUtf8Bytes();
61+
var ms = new MemoryStream(utf8Bytes);
62+
Assert.That(utf8Bytes.ToMd5Hash(), Is.EqualTo(md5Hash));
63+
Assert.That(ms.ToMd5Bytes().ToHex(), Is.EqualTo(md5Hash));
64+
}
5565
}
5666
}

0 commit comments

Comments
 (0)