Skip to content

Commit

Permalink
修改ID的编解码key自定义
Browse files Browse the repository at this point in the history
  • Loading branch information
pangdogs committed Feb 26, 2023
1 parent a4654ee commit e6878ba
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion ec/id.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,38 @@
package ec

import "encoding/base64"
import (
"encoding/base64"
"errors"
"reflect"
"unsafe"
)

// ID 唯一ID(160位)
type ID [20]byte

func (id ID) String() string {
return EncodeIDToString(id)
}

var EncodeIDToString = func(id ID) string {
return base64.RawURLEncoding.EncodeToString(id[:])
}

var DecodeStringToID = func(str string) (id ID, err error) {
if base64.RawURLEncoding.DecodedLen(len(str)) > len(id) {
err = errors.New("string too long")
return
}
base64.RawURLEncoding.Decode(id[:], string2Bytes(str))
return
}

func string2Bytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{
Data: sh.Data,
Len: sh.Len,
Cap: sh.Len,
}
return *(*[]byte)(unsafe.Pointer(&bh))
}

0 comments on commit e6878ba

Please sign in to comment.