Debian Codegraph @

base64/base64_asm.go

raw
1 //go:build (amd64 || arm64) && !purego
2 // +build amd64 arm64
3 // +build !purego
4
5 package base64
6
7 import (
8 "encoding/base64"
9
10 "github.com/segmentio/asm/internal/unsafebytes"
11 )
12
13 // An Encoding is a radix 64 encoding/decoding scheme, defined by a
14 // 64-character alphabet.
15 type Encoding struct {
16 enc func(dst []byte, src []byte, lut *int8) (int, int)
17 enclut [encLutSize]int8
18
19 dec func(dst []byte, src []byte, lut *int8) (int, int)
20 declut [decLutSize]int8
21
22 base *base64.Encoding
23 }
24
25 // WithPadding creates a duplicate Encoding updated with a specified padding
26 // character, or NoPadding to disable padding. The padding character must not
27 // be contained in the encoding alphabet, must not be '\r' or '\n', and must
28 // be no greater than '\xFF'.
29 func (enc Encoding) WithPadding(padding rune) *Encoding {
30 enc.base = enc.base.WithPadding(padding)
31 return &enc
32 }
33
34 // Strict creates a duplicate encoding updated with strict decoding enabled.
35 // This requires that trailing padding bits are zero.
36 func (enc Encoding) Strict() *Encoding {
37 enc.base = enc.base.Strict()
38 return &enc
39 }
40
41 // Encode encodes src using the defined encoding alphabet.
42 // This will write EncodedLen(len(src)) bytes to dst.
43 func (enc *Encoding) Encode(dst, src []byte) {
44 if len(src) >= minEncodeLen && enc.enc != nil {
45 d, s := enc.enc(dst, src, &enc.enclut[0])
46 dst = dst[d:]
47 src = src[s:]
48 }
49 enc.base.Encode(dst, src)
50 }
51
52 // Encode encodes src using the encoding enc, writing
53 // EncodedLen(len(src)) bytes to dst.
54 func (enc *Encoding) EncodeToString(src []byte) string {
55 buf := make([]byte, enc.base.EncodedLen(len(src)))
56 enc.Encode(buf, src)
57 return string(buf)
58 }
59
60 // EncodedLen calculates the base64-encoded byte length for a message
61 // of length n.
62 func (enc *Encoding) EncodedLen(n int) int {
63 return enc.base.EncodedLen(n)
64 }
65
66 // Decode decodes src using the defined encoding alphabet.
67 // This will write DecodedLen(len(src)) bytes to dst and return the number of
68 // bytes written.
69 func (enc *Encoding) Decode(dst, src []byte) (n int, err error) {
70 var d, s int
71 if len(src) >= minDecodeLen && enc.dec != nil {
72 d, s = enc.dec(dst, src, &enc.declut[0])
73 dst = dst[d:]
74 src = src[s:]
75 }
76 n, err = enc.base.Decode(dst, src)
77 n += d
78 return
79 }
80
81 // DecodeString decodes the base64 encoded string s, returns the decoded
82 // value as bytes.
83 func (enc *Encoding) DecodeString(s string) ([]byte, error) {
84 src := unsafebytes.BytesOf(s)
85 dst := make([]byte, enc.base.DecodedLen(len(s)))
86 n, err := enc.Decode(dst, src)
87 return dst[:n], err
88 }
89
90 // DecodedLen calculates the decoded byte length for a base64-encoded message
91 // of length n.
92 func (enc *Encoding) DecodedLen(n int) int {
93 return enc.base.DecodedLen(n)
94 }