scoop:scoop.std:0.1.0
src/io/encoding/base64_encode.scoop
Selected production source · src/io/encoding/base64_encode.scoop
1
package scoop.io.encoding3
import scoop.io.encoding.Base64.PaddingOption4
import scoop.text.checkedTextProduct5
import scoop.text.checkedTextSum7
internal fun encodeBase64(source: List<Byte>, urlSafe: Boolean, padding: PaddingOption): String {8
val length = source.size9
val remainder = length % 3L10
val tail = if (remainder == 0L) 0L else if (padding == PaddingOption.Absent) remainder + 1L else 4L11
val size = checkedTextSum(checkedTextProduct(length / 3L, 4L), tail)12
val output = MutableArray<Char>(size) { _ -> '=' }13
val alphabet = if (urlSafe) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"14
else "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"15
var position = 0L16
var target = 0L17
while (position < length) {18
val available = length - position19
val first = source[position].toUByte().toInt()20
val second = if (available > 1L) source[position + 1L].toUByte().toInt() else 021
val third = if (available > 2L) source[position + 2L].toUByte().toInt() else 022
output[target] = alphabet.getCharAt((first / 4).toLong())23
output[target + 1L] = alphabet.getCharAt(((first % 4) * 16 + second / 16).toLong())24
if (available > 1L) output[target + 2L] = alphabet.getCharAt(((second % 16) * 4 + third / 64).toLong())25
if (available > 2L) output[target + 3L] = alphabet.getCharAt((third % 64).toLong())26
if (available <= 3L) break27
position += 3L28
target += 4L29
}30
return String.fromChars(output)31
}