Skip to content

Commit

Permalink
Dedup PemEncoding.TryCountBase64 with Base64.IsValid (#86002)
Browse files Browse the repository at this point in the history
* Dedup PemEncoding.TryCountBase64 with Base64.IsValid

* Address PR feedback
  • Loading branch information
stephentoub authored May 10, 2023
1 parent 6971065 commit 52b81af
Showing 1 changed file with 14 additions and 53 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers.Text;
using System.Diagnostics;
using System.Runtime.CompilerServices;

Expand Down Expand Up @@ -233,63 +234,23 @@ private static bool TryCountBase64(
out int base64End,
out int base64DecodedSize)
{
base64Start = 0;
base64End = str.Length;

if (str.IsEmpty)
// Trim starting and ending allowed white space characters
int start = 0;
int end = str.Length - 1;
for (; start < str.Length && IsWhiteSpaceCharacter(str[start]); start++);
for (; end > start && IsWhiteSpaceCharacter(str[end]); end--);

// Validate that the remaining characters are valid base-64 encoded data.
if (Base64.IsValid(str.Slice(start, end + 1 - start), out base64DecodedSize))
{
base64DecodedSize = 0;
base64Start = start;
base64End = end + 1;
return true;
}

int significantCharacters = 0;
int paddingCharacters = 0;

for (int i = 0; i < str.Length; i++)
{
char ch = str[i];

if (IsWhiteSpaceCharacter(ch))
{
if (significantCharacters == 0)
{
base64Start++;
}
else
{
base64End--;
}

continue;
}

base64End = str.Length;

if (ch == '=')
{
paddingCharacters++;
}
else if (paddingCharacters == 0 && IsBase64Character(ch))
{
significantCharacters++;
}
else
{
base64DecodedSize = 0;
return false;
}
}

int totalChars = paddingCharacters + significantCharacters;

if (paddingCharacters > 2 || (totalChars & 0b11) != 0)
{
base64DecodedSize = 0;
return false;
}

base64DecodedSize = (totalChars >> 2) * 3 - paddingCharacters;
return true;
base64Start = 0;
base64End = 0;
return false;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down

0 comments on commit 52b81af

Please sign in to comment.