Skip to content

Commit 25136af

Browse files
chore: Use SHA512.HashDataAsync (#2324)
* Use SHA512.HashDataAsync Use `SHA512.HashDataAsync()` for .NET 8 to reduce allocations. * Apply suggestions from code review * chore: uses 31 serialization method --------- Co-authored-by: Vincent Biret <[email protected]>
1 parent b865a54 commit 25136af

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/Microsoft.OpenApi/Models/OpenApiDocument.cs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -524,20 +524,35 @@ public void SetReferenceHostDocument()
524524
/// <returns>The hash value.</returns>
525525
public async Task<string> GetHashCodeAsync(CancellationToken cancellationToken = default)
526526
{
527+
#if NET7_OR_GREATER
528+
using var memoryStream = new MemoryStream();
529+
using var streamWriter = new StreamWriter(memoryStream);
530+
531+
await WriteDocumentAsync(streamWriter, cancellationToken).ConfigureAwait(false);
532+
533+
memoryStream.Seek(0, SeekOrigin.Begin);
534+
535+
var hash = await SHA512.HashDataAsync(memoryStream, cancellationToken).ConfigureAwait(false);
536+
#else
527537
using HashAlgorithm sha = SHA512.Create();
528538
using var cryptoStream = new CryptoStream(Stream.Null, sha, CryptoStreamMode.Write);
529539
using var streamWriter = new StreamWriter(cryptoStream);
530540

531-
var openApiJsonWriter = new OpenApiJsonWriter(streamWriter, new() { Terse = true });
532-
SerializeAsV3(openApiJsonWriter);
533-
await openApiJsonWriter.FlushAsync(cancellationToken).ConfigureAwait(false);
541+
await WriteDocumentAsync(streamWriter, cancellationToken).ConfigureAwait(false);
534542

535-
#if NET5_0_OR_GREATER
536-
await cryptoStream.FlushFinalBlockAsync(cancellationToken).ConfigureAwait(false);
537-
#else
538543
cryptoStream.FlushFinalBlock();
544+
545+
var hash = sha.Hash;
539546
#endif
540-
return ConvertByteArrayToString(sha.Hash ?? []);
547+
548+
return ConvertByteArrayToString(hash ?? []);
549+
550+
async Task WriteDocumentAsync(TextWriter writer, CancellationToken token)
551+
{
552+
var openApiJsonWriter = new OpenApiJsonWriter(writer, new() { Terse = true });
553+
SerializeAsV31(openApiJsonWriter);
554+
await openApiJsonWriter.FlushAsync(cancellationToken).ConfigureAwait(false);
555+
}
541556
}
542557

543558
private static string ConvertByteArrayToString(byte[] hash)

0 commit comments

Comments
 (0)