|
1 | 1 | using System.Buffers; |
| 2 | +using System.Buffers.Text; |
2 | 3 | using System.ComponentModel; |
3 | 4 | using System.Diagnostics; |
4 | 5 | using System.Diagnostics.CodeAnalysis; |
@@ -426,7 +427,17 @@ public ReadOnlyMemory<byte> DecodedData |
426 | 427 | if (_decodedData is null) |
427 | 428 | { |
428 | 429 | #if NET |
429 | | - _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(Data.Span)); |
| 430 | + // Decode directly from UTF-8 base64 bytes without string intermediate |
| 431 | + int maxLength = Base64.GetMaxDecodedFromUtf8Length(Data.Length); |
| 432 | + byte[] buffer = new byte[maxLength]; |
| 433 | + if (Base64.DecodeFromUtf8(Data.Span, buffer, out _, out int bytesWritten) == System.Buffers.OperationStatus.Done) |
| 434 | + { |
| 435 | + _decodedData = bytesWritten == maxLength ? buffer : buffer.AsMemory(0, bytesWritten).ToArray(); |
| 436 | + } |
| 437 | + else |
| 438 | + { |
| 439 | + throw new FormatException("Invalid base64 data"); |
| 440 | + } |
430 | 441 | #else |
431 | 442 | byte[] array = MemoryMarshal.TryGetArray(Data, out ArraySegment<byte> segment) && segment.Offset == 0 && segment.Count == segment.Array!.Length ? segment.Array : Data.ToArray(); |
432 | 443 | _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(array)); |
@@ -491,7 +502,17 @@ public ReadOnlyMemory<byte> DecodedData |
491 | 502 | if (_decodedData is null) |
492 | 503 | { |
493 | 504 | #if NET |
494 | | - _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(Data.Span)); |
| 505 | + // Decode directly from UTF-8 base64 bytes without string intermediate |
| 506 | + int maxLength = Base64.GetMaxDecodedFromUtf8Length(Data.Length); |
| 507 | + byte[] buffer = new byte[maxLength]; |
| 508 | + if (Base64.DecodeFromUtf8(Data.Span, buffer, out _, out int bytesWritten) == System.Buffers.OperationStatus.Done) |
| 509 | + { |
| 510 | + _decodedData = bytesWritten == maxLength ? buffer : buffer.AsMemory(0, bytesWritten).ToArray(); |
| 511 | + } |
| 512 | + else |
| 513 | + { |
| 514 | + throw new FormatException("Invalid base64 data"); |
| 515 | + } |
495 | 516 | #else |
496 | 517 | byte[] array = MemoryMarshal.TryGetArray(Data, out ArraySegment<byte> segment) && segment.Offset == 0 && segment.Count == segment.Array!.Length ? segment.Array : Data.ToArray(); |
497 | 518 | _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(array)); |
|
0 commit comments