Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .licenserc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ header:
paths-ignore:
- 'internal/native/avx2/*.go'
- 'internal/native/sse/*.go'
- 'internal/simd/*.go'

comment: on-failure
7 changes: 5 additions & 2 deletions base64x_error_native_amd64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build amd64 && !noasm && !appengine
// +build amd64,!noasm,!appengine
//go:build (!go1.27 || !goexperiment.simd) && amd64 && !noasm && !appengine
// +build !go1.27 !goexperiment.simd
// +build amd64
// +build !noasm
// +build !appengine

package base64x

Expand Down
32 changes: 15 additions & 17 deletions base64x_fallback_test.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
//go:build !amd64 || noasm || appengine
// +build !amd64 noasm appengine
// Copyright 2024 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//go:build (go1.27 && goexperiment.simd) || !amd64 || noasm || appengine
// +build go1.27,goexperiment.simd !amd64 noasm appengine

package base64x

Expand Down
35 changes: 18 additions & 17 deletions base64x_native.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
//go:build amd64 && !noasm && !appengine
// +build amd64,!noasm,!appengine
// Copyright 2024 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
* Copyright 2024 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//go:build (!go1.27 || !goexperiment.simd) && amd64 && !noasm && !appengine
// +build !go1.27 !goexperiment.simd
// +build amd64
// +build !noasm
// +build !appengine

package base64x

Expand Down
278 changes: 278 additions & 0 deletions base64x_simd_amd64.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,278 @@
// Copyright 2026 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build go1.27 && goexperiment.simd && amd64 && !noasm && !appengine
// +build go1.27,goexperiment.simd,amd64,!noasm,!appengine

package base64x

import (
"bytes"
"encoding/base64"
"errors"
"simd/archsimd"

"github.com/cloudwego/base64x/internal/simd"
)

// Note: under go1.27 && goexperiment.simd, this file replaces base64x_native.go
// and base64x_subr_native_amd64.go with static Go simd/archsimd kernels (no
// runtime executable page loader). On Go <= 1.26 (even if GOEXPERIMENT=simd is
// set), base64x remains on internal/native so _subr__b64decode stays populated
// for bytedance/sonic's JIT (which is gated by !go1.27 in sonic). On Go 1.27+
// with goexperiment.simd, _subr__b64decode and _subr__b64encode remain 0,
// matching -tags noasm and appengine builds.

func encode(out *[]byte, src []byte, mode int) {
if !archsimd.X86.AVX2() {
encodeStdlib(out, src, mode)
return
}
url := 0
if mode&_MODE_URL != 0 {
url = 1
}
pad := 1
if mode&_MODE_RAW != 0 {
pad = 0
}
enc := encodingForModeSimd(mode)
dst := *out
start := len(dst)
need := enc.EncodedLen(len(src))
dst = dst[:start+need]
simd.B64_encode(src, uint64(len(src)), dst[start:start+need], uint64(need), url, pad)
*out = dst
}

func decode(out *[]byte, src []byte, mode int) (int, error) {
input := src
var escBuf [256]byte
var escMapBuf [256]int
var posMap []int
if mode&_MODE_JSON != 0 {
var err error
input, posMap, err = unescapeJSONBase64(src, escBuf[:0], escMapBuf[:0])
if err != nil {
return 0, err
}
}
if !archsimd.X86.AVX2() {
n, err := decodeStdlib(out, input, mode)
if err != nil {
return 0, remapDecodeError(err, posMap, len(src))
}
return n, nil
}

url := 0
if mode&_MODE_URL != 0 {
url = 1
}
pad := 1
if mode&_MODE_RAW != 0 {
pad = 0
}
enc := encodingForModeSimd(mode)
dst := *out
start := len(dst)
availCap := cap(dst) - start
need := enc.DecodedLen(len(input))

// simd.B64_decode bounds 32-byte vector stores to (dst_cap - offset) >= 32
// and writes any remaining tail bytes individually up to the decoded count.
// Use a scratch buffer only when the caller of DecodeUnsafe supplied a slice
// whose remaining capacity is smaller than DecodedLen(len(input)).
if availCap < need {
var tmp [256]byte
var buf []byte
if need <= len(tmp) {
buf = tmp[:need]
} else {
buf = make([]byte, need)
}
var posErr uint64
w := simd.B64_decode(input, uint64(len(input)), buf, uint64(len(buf)), url, pad, &posErr)
if posErr != ^uint64(0) {
return 0, mapCorruptPos(posErr, posMap, len(src))
}
dst = dst[:start+int(w)]
copy(dst[start:], buf[:w])
*out = dst
return int(w), nil
}

var posErr uint64
w := simd.B64_decode(input, uint64(len(input)), dst[start:cap(dst)], uint64(availCap), url, pad, &posErr)
if posErr != ^uint64(0) {
return 0, mapCorruptPos(posErr, posMap, len(src))
}
*out = dst[:start+int(w)]
return int(w), nil
}

func encodingForModeSimd(mode int) *base64.Encoding {
switch mode & (_MODE_URL | _MODE_RAW) {
case _MODE_URL:
return base64.URLEncoding
case _MODE_RAW:
return base64.RawStdEncoding
case _MODE_URL | _MODE_RAW:
return base64.RawURLEncoding
default:
return base64.StdEncoding
}
}

func encodeStdlib(out *[]byte, src []byte, mode int) {
enc := encodingForModeSimd(mode)
dst := *out
start := len(dst)
need := enc.EncodedLen(len(src))
dst = dst[:start+need]
enc.Encode(dst[start:], src)
*out = dst
}

func decodeStdlib(out *[]byte, input []byte, mode int) (int, error) {
enc := encodingForModeSimd(mode)
dst := *out
start := len(dst)
buf := dst[start:cap(dst)]
n, err := enc.Decode(buf, input)
if err != nil {
return 0, err
}
*out = dst[:start+n]
return n, nil
}

func unquoteJSONBase64(src []byte) ([]byte, error) {
out, _, err := unescapeJSONBase64(src, nil, nil)
return out, err
}

// unescapeJSONBase64 matches the JSON escape subset of native/native.h
// (unescape_asc): \r, \n, \/, and ASCII \uXXXX (< 0x80). Raw \r and \n remain
// untouched for the base64 decoder to skip, and any invalid escape returns
// base64.CorruptInputError at the backslash index in src.
func unescapeJSONBase64(src []byte, dstBuf []byte, mapBuf []int) ([]byte, []int, error) {
first := bytes.IndexByte(src, '\\')
if first < 0 {
return src, nil, nil
}

var out []byte
var posMap []int
if cap(dstBuf) >= len(src) {
out = dstBuf[:0]
} else {
out = make([]byte, 0, len(src))
}
if cap(mapBuf) >= len(src) {
posMap = mapBuf[:0]
} else {
posMap = make([]int, 0, len(src))
}

out = append(out, src[:first]...)
for i := 0; i < first; i++ {
posMap = append(posMap, i)
}

for i := first; i < len(src); {
b := src[i]
if b != '\\' {
out = append(out, b)
posMap = append(posMap, i)
i++
continue
}
if i+1 >= len(src) {
return nil, nil, base64.CorruptInputError(i)
}
switch src[i+1] {
case 'r':
out = append(out, '\r')
posMap = append(posMap, i)
i += 2
case 'n':
out = append(out, '\n')
posMap = append(posMap, i)
i += 2
case '/':
out = append(out, '/')
posMap = append(posMap, i)
i += 2
case 'u':
if i+6 > len(src) {
return nil, nil, base64.CorruptInputError(i)
}
v, ok := parseHex4ASCII(src[i+2 : i+6])
if !ok {
return nil, nil, base64.CorruptInputError(i)
}
out = append(out, v)
posMap = append(posMap, i)
i += 6
default:
return nil, nil, base64.CorruptInputError(i)
}
}
return out, posMap, nil
}

func parseHex4ASCII(s []byte) (byte, bool) {
var v uint16
for i := 0; i < 4; i++ {
c := s[i]
var d uint16
switch {
case c >= '0' && c <= '9':
d = uint16(c - '0')
case c >= 'a' && c <= 'f':
d = uint16(c - 'a' + 10)
case c >= 'A' && c <= 'F':
d = uint16(c - 'A' + 10)
default:
return 0, false
}
v = (v << 4) | d
}
if v >= 0x80 {
return 0, false
}
return byte(v), true
}

func mapCorruptPos(pos uint64, posMap []int, srcLen int) error {
if posMap == nil {
return base64.CorruptInputError(pos)
}
if pos < uint64(len(posMap)) {
return base64.CorruptInputError(posMap[pos])
}
return base64.CorruptInputError(srcLen)
}

func remapDecodeError(err error, posMap []int, srcLen int) error {
if posMap == nil {
return err
}
var ce base64.CorruptInputError
if errors.As(err, &ce) && ce >= 0 {
return mapCorruptPos(uint64(ce), posMap, srcLen)
}
return err
}
Loading