|
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; |
@@ -421,7 +422,17 @@ public ReadOnlyMemory<byte> DecodedData |
421 | 422 | if (_decodedData is null) |
422 | 423 | { |
423 | 424 | #if NET |
424 | | - _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(Data.Span)); |
| 425 | + // Decode directly from UTF-8 base64 bytes without string intermediate |
| 426 | + int maxLength = Base64.GetMaxDecodedFromUtf8Length(Data.Length); |
| 427 | + byte[] buffer = new byte[maxLength]; |
| 428 | + if (Base64.DecodeFromUtf8(Data.Span, buffer, out _, out int bytesWritten) == System.Buffers.OperationStatus.Done) |
| 429 | + { |
| 430 | + _decodedData = bytesWritten == maxLength ? buffer : buffer.AsMemory(0, bytesWritten).ToArray(); |
| 431 | + } |
| 432 | + else |
| 433 | + { |
| 434 | + throw new FormatException("Invalid base64 data"); |
| 435 | + } |
425 | 436 | #else |
426 | 437 | byte[] array = MemoryMarshal.TryGetArray(Data, out ArraySegment<byte> segment) && segment.Offset == 0 && segment.Count == segment.Array!.Length ? segment.Array : Data.ToArray(); |
427 | 438 | _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(array)); |
@@ -482,7 +493,17 @@ public ReadOnlyMemory<byte> DecodedData |
482 | 493 | if (_decodedData is null) |
483 | 494 | { |
484 | 495 | #if NET |
485 | | - _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(Data.Span)); |
| 496 | + // Decode directly from UTF-8 base64 bytes without string intermediate |
| 497 | + int maxLength = Base64.GetMaxDecodedFromUtf8Length(Data.Length); |
| 498 | + byte[] buffer = new byte[maxLength]; |
| 499 | + if (Base64.DecodeFromUtf8(Data.Span, buffer, out _, out int bytesWritten) == System.Buffers.OperationStatus.Done) |
| 500 | + { |
| 501 | + _decodedData = bytesWritten == maxLength ? buffer : buffer.AsMemory(0, bytesWritten).ToArray(); |
| 502 | + } |
| 503 | + else |
| 504 | + { |
| 505 | + throw new FormatException("Invalid base64 data"); |
| 506 | + } |
486 | 507 | #else |
487 | 508 | byte[] array = MemoryMarshal.TryGetArray(Data, out ArraySegment<byte> segment) && segment.Offset == 0 && segment.Count == segment.Array!.Length ? segment.Array : Data.ToArray(); |
488 | 509 | _decodedData = Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(array)); |
|
0 commit comments