Skip to content

Commit

Permalink
Merge pull request #17 from tayloraswift/configurable-base64-padding
Browse files Browse the repository at this point in the history
allow configuring the Base64 padding
  • Loading branch information
tayloraswift authored Jul 1, 2024
2 parents 886ed5b + f39eec8 commit caee551
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions Sources/Base64/Base64.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ enum Base64
/// Encodes a sequence of bytes to a base-64 string with padding if needed.
@inlinable public static
func encode<Bytes>(_ bytes:Bytes) -> String where Bytes:Sequence<UInt8>
{
self.encode(bytes, padding: true)
}

/// Encodes a sequence of bytes to a base-64 string, padding the output with `=` characters
/// if `padding` is true.
@inlinable public static
func encode<Bytes>(_ bytes:Bytes, padding:Bool) -> String where Bytes:Sequence<UInt8>
{
var encoded:String = ""
encoded.reserveCapacity(bytes.underestimatedCount * 4 / 3)
Expand All @@ -79,9 +87,14 @@ enum Base64
else
{
encoded.append(Digits[first << 4])
encoded.append("=")
encoded.append("=")
continue

if padding
{
encoded.append("=")
encoded.append("=")
}

break
}

encoded.append( Digits[first << 4 | second >> 4])
Expand All @@ -90,8 +103,12 @@ enum Base64
else
{
encoded.append(Digits[second << 2])
encoded.append("=")
continue

if padding
{
encoded.append("=")
}
break
}

encoded.append( Digits[second << 2 | third >> 6])
Expand Down

0 comments on commit caee551

Please sign in to comment.