Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

base64.gno

1.89 Kb · 88 lines
 1package cards
 2
 3import "errors"
 4
 5// A hand-rolled strict standard-base64 decoder: the stdlib decoder costs about
 6// 35% more gas on a 13 KB deck, which every deck pass pays.
 7
 8const b64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
 9
10var b64Rev = func() [256]byte {
11	var t [256]byte
12	for i := range t {
13		t[i] = 0xff
14	}
15	for i := 0; i < 64; i++ {
16		t[b64Alphabet[i]] = byte(i)
17	}
18	return t
19}()
20
21var errBase64 = errors.New("invalid base64")
22
23// MaxBase64Len is the longest input DecodeBase64 accepts: one full deck.
24const MaxBase64Len = (DeckLen + 2) / 3 * 4
25
26var errBase64TooLong = errors.New("base64 input too long")
27
28// DecodeBase64 decodes padded standard base64 and rejects non-canonical input
29// and anything longer than MaxBase64Len.
30func DecodeBase64(s string) ([]byte, error) {
31	if len(s) > MaxBase64Len {
32		return nil, errBase64TooLong
33	}
34	if len(s)%4 != 0 {
35		return nil, errBase64
36	}
37	if len(s) == 0 {
38		return []byte{}, nil
39	}
40	pad := 0
41	if s[len(s)-1] == '=' {
42		pad++
43		if s[len(s)-2] == '=' {
44			pad++
45		}
46	}
47	// At most DeckLen bytes, by the MaxBase64Len check above.
48	n := len(s)/4*3 - pad
49	out := make([]byte, 0, n)[:n]
50	full := len(s) / 4
51	if pad > 0 {
52		full--
53	}
54	o := 0
55	for g := 0; g < full; g++ {
56		i := g * 4
57		a, b, c, d := b64Rev[s[i]], b64Rev[s[i+1]], b64Rev[s[i+2]], b64Rev[s[i+3]]
58		if (a|b|c|d)&0xc0 != 0 {
59			return nil, errBase64
60		}
61		v := uint32(a)<<18 | uint32(b)<<12 | uint32(c)<<6 | uint32(d)
62		out[o] = byte(v >> 16)
63		out[o+1] = byte(v >> 8)
64		out[o+2] = byte(v)
65		o += 3
66	}
67	if pad > 0 {
68		i := full * 4
69		a, b := b64Rev[s[i]], b64Rev[s[i+1]]
70		if a == 0xff || b == 0xff {
71			return nil, errBase64
72		}
73		if pad == 2 {
74			if b&0x0f != 0 {
75				return nil, errBase64
76			}
77			out[o] = a<<2 | b>>4
78		} else {
79			c := b64Rev[s[i+2]]
80			if c == 0xff || c&0x03 != 0 {
81				return nil, errBase64
82			}
83			out[o] = a<<2 | b>>4
84			out[o+1] = b<<4 | c>>2
85		}
86	}
87	return out, nil
88}