Scoop API

scoop:scoop.std:0.1.0

src/io/encoding/base64_encode.scoop

Selected production source · src/io/encoding/base64_encode.scoop

1package scoop.io.encoding
3import scoop.io.encoding.Base64.PaddingOption
4import scoop.text.checkedTextProduct
5import scoop.text.checkedTextSum
7internal fun encodeBase64(source: List<Byte>, urlSafe: Boolean, padding: PaddingOption): String {
8 val length = source.size
9 val remainder = length % 3L
10 val tail = if (remainder == 0L) 0L else if (padding == PaddingOption.Absent) remainder + 1L else 4L
11 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 = 0L
16 var target = 0L
17 while (position < length) {
18 val available = length - position
19 val first = source[position].toUByte().toInt()
20 val second = if (available > 1L) source[position + 1L].toUByte().toInt() else 0
21 val third = if (available > 2L) source[position + 2L].toUByte().toInt() else 0
22 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) break
27 position += 3L
28 target += 4L
29 }
30 return String.fromChars(output)