| 1 |
//go:build amd64 && !purego |
| 2 |
// +build amd64,!purego |
| 3 |
|
| 4 |
package base64 |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding/base64" |
| 8 |
|
| 9 |
"github.com/segmentio/asm/cpu" |
| 10 |
"github.com/segmentio/asm/cpu/x86" |
| 11 |
) |
| 12 |
|
| 13 |
const ( |
| 14 |
encLutSize = 32 |
| 15 |
decLutSize = 48 |
| 16 |
minEncodeLen = 28 |
| 17 |
minDecodeLen = 45 |
| 18 |
) |
| 19 |
|
| 20 |
func newEncoding(encoder string) *Encoding { |
| 21 |
e := &Encoding{base: base64.NewEncoding(encoder)} |
| 22 |
if cpu.X86.Has(x86.AVX2) { |
| 23 |
e.enableEncodeAVX2(encoder) |
| 24 |
e.enableDecodeAVX2(encoder) |
| 25 |
} |
| 26 |
return e |
| 27 |
} |
| 28 |
|
| 29 |
func (e *Encoding) enableEncodeAVX2(encoder string) { |
| 30 |
// Translate values 0..63 to the Base64 alphabet. There are five sets: |
| 31 |
// |
| 32 |
// From To Add Index Example |
| 33 |
// [0..25] [65..90] +65 0 ABCDEFGHIJKLMNOPQRSTUVWXYZ |
| 34 |
// [26..51] [97..122] +71 1 abcdefghijklmnopqrstuvwxyz |
| 35 |
// [52..61] [48..57] -4 [2..11] 0123456789 |
| 36 |
// [62] [43] -19 12 + |
| 37 |
// [63] [47] -16 13 / |
| 38 |
tab := [encLutSize]int8{int8(encoder[0]), int8(encoder[letterRange]) - letterRange} |
| 39 |
for i, ch := range encoder[2*letterRange:] { |
| 40 |
tab[2+i] = int8(ch) - 2*letterRange - int8(i) |
| 41 |
} |
| 42 |
|
| 43 |
e.enc = encodeAVX2 |
| 44 |
e.enclut = tab |
| 45 |
} |
| 46 |
|
| 47 |
func (e *Encoding) enableDecodeAVX2(encoder string) { |
| 48 |
c62, c63 := int8(encoder[62]), int8(encoder[63]) |
| 49 |
url := c63 == '_' |
| 50 |
if url { |
| 51 |
c63 = '/' |
| 52 |
} |
| 53 |
|
| 54 |
// Translate values from the Base64 alphabet using five sets. Values outside |
| 55 |
// of these ranges are considered invalid: |
| 56 |
// |
| 57 |
// From To Add Index Example |
| 58 |
// [47] [63] +16 1 / |
| 59 |
// [43] [62] +19 2 + |
| 60 |
// [48..57] [52..61] +4 3 0123456789 |
| 61 |
// [65..90] [0..25] -65 4,5 ABCDEFGHIJKLMNOPQRSTUVWXYZ |
| 62 |
// [97..122] [26..51] -71 6,7 abcdefghijklmnopqrstuvwxyz |
| 63 |
tab := [decLutSize]int8{ |
| 64 |
0, 63 - c63, 62 - c62, 4, -65, -65, -71, -71, |
| 65 |
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, |
| 66 |
0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, |
| 67 |
0x11, 0x11, 0x13, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, |
| 68 |
} |
| 69 |
tab[(c62&15)+16] = 0x1A |
| 70 |
tab[(c63&15)+16] = 0x1A |
| 71 |
|
| 72 |
if url { |
| 73 |
e.dec = decodeAVX2URI |
| 74 |
} else { |
| 75 |
e.dec = decodeAVX2 |
| 76 |
} |
| 77 |
e.declut = tab |
| 78 |
} |