Scoop API

scoop:scoop.std:0.1.0

src/io/encoding/base64.scoop

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

1package scoop.io.encoding
3/**
4 * A strict Base64 codec with standard or URL-safe alphabet and an explicit padding policy.
5 * Decoding rejects invalid alphabet, padding, and nonzero unused tail bits.
6 */
7public class Base64 private constructor(private val urlSafe: Boolean,
8 /**
9 * The padding rule used for encoding and decoding.
10 */
11 public val paddingOption: Base64.PaddingOption) {
12 /**
13 * Controls whether trailing equals signs are emitted and accepted.
14 */
15 public enum PaddingOption {
16 /**
17 * Emit padding and require it when a final partial group needs it.
18 */
19 Required,
20 /**
21 * Omit padding and reject padded input.
22 */
23 Absent,
24 /**
25 * Emit padding, while accepting valid input with or without padding.
26 */
27 Optional }
29 /**
30 * Preconfigured standard and URL-safe codecs.
31 */
32 public companion object {
33 /**
34 * The standard +/ alphabet with required padding.
35 */
36 public val Default: Base64 = Base64(false, PaddingOption.Required)
37 /**
38 * The URL-safe -_ alphabet with required padding.
39 */
40 public val UrlSafe: Base64 = Base64(true, PaddingOption.Required)
41 }
43 /**
44 * Returns a codec with the same alphabet and the selected padding policy.
45 */
46 public fun withPadding(option: PaddingOption): Base64 = Base64(urlSafe, option)
47 /**
48 * Encodes bytes using this alphabet and padding policy, without line breaks.
49 */
50 public fun encode(source: List<Byte>): String = encodeBase64(source, urlSafe, paddingOption)
51 /**
52 * Decodes valid text or returns None when alphabet, length, padding, or unused bits are
53 * invalid.
54 */
55 public fun decodeOrNone(source: String): Array<Byte>? = decodeBase64(source, urlSafe, paddingOption)
56 /**
57 * Decodes text or throws IllegalArgumentException for invalid Base64.
58 */
59 public fun decode(source: String): Array<Byte> = when (decodeOrNone(source)) {
60 case Some(val value) -> value
61 case None -> throw IllegalArgumentException(Some("invalid Base64"))
62 }