作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢!
为了提升性能,使用 unsafe 代码来重构了凯撒加密的代码。代码如下:- const (
- lowerCaseAlphabet = "abcdefghijklmnopqrstuvwxyz"
- upperCaseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- )
- var (
- lowerCaseAlphabetArr = []byte(lowerCaseAlphabet)
- upperCaseAlphabetArr = []byte(upperCaseAlphabet)
- tableOflowerCaseAlphabet = unsafe.Pointer(&lowerCaseAlphabetArr[0])
- tableOfupperCaseAlphabe = unsafe.Pointer(&upperCaseAlphabetArr[0])
- )
- // CaesarFastEncode fast version
- func CaesarFastEncode(in []byte, out []byte, rot int) {
- start := unsafe.Pointer(&in[0])
- target := unsafe.Pointer(&out[0])
- for i := 0; i < len(in); i++ {
- c := *((*byte)(start))
- if c == '.' {
- *((*byte)(target)) = '='
- } else if c >= 'a' && c <= 'z' {
- idx := (int(26+(c-'a')) + rot) % 26
- *((*byte)(target)) = *((*byte)(unsafe.Pointer(uintptr(tableOflowerCaseAlphabet) + uintptr(idx))))
- } else if c >= 'A' && c <= 'Z' {
- idx := (int(26+(c-'A')) + rot) % 26
- *((*byte)(target)) = *((*byte)(unsafe.Pointer(uintptr(tableOfupperCaseAlphabe) + uintptr(idx))))
- } else {
- *((*byte)(target)) = *((*byte)(start))
- }
- start = unsafe.Pointer(uintptr(start) + uintptr(1))
- target = unsafe.Pointer(uintptr(target) + uintptr(1))
- }
- }
复制代码 由此看来,只要使用了 unsafe 代码,都应该加上-race选项。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |