refactor: string map to uuidv5

This commit is contained in:
Skyxim 2022-05-06 14:02:34 +08:00
parent a95d439852
commit 980d8a2641
2 changed files with 8 additions and 20 deletions

View file

@ -1,8 +1,6 @@
package utils package utils
import ( import (
"crypto/sha1"
"encoding/hex"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
) )
@ -10,24 +8,12 @@ import (
func UUIDMap(str string) (uuid.UUID, error) { func UUIDMap(str string) (uuid.UUID, error) {
u, err := uuid.FromString(str) u, err := uuid.FromString(str)
if err != nil { if err != nil {
var Nil [16]byte uuidNamespace, err := uuid.FromString("00000000-0000-0000-0000-000000000000")
h := sha1.New() if err != nil {
h.Write(Nil[:]) return uuid.UUID{}, err
h.Write([]byte(str)) }
u := h.Sum(nil)[:16]
u[6] = (u[6] & 0x0f) | (5 << 4) return uuid.NewV5(uuidNamespace, str), err
u[8] = u[8]&(0xff>>2) | (0x02 << 6)
buf := make([]byte, 36)
hex.Encode(buf[0:8], u[0:4])
buf[8] = '-'
hex.Encode(buf[9:13], u[4:6])
buf[13] = '-'
hex.Encode(buf[14:18], u[6:8])
buf[18] = '-'
hex.Encode(buf[19:23], u[8:10])
buf[23] = '-'
hex.Encode(buf[24:], u[10:])
return uuid.FromString(string(buf))
} }
return u, nil return u, nil
} }

View file

@ -10,6 +10,7 @@ func TestUUIDMap(t *testing.T) {
type args struct { type args struct {
str string str string
} }
tests := []struct { tests := []struct {
name string name string
args args args args
@ -40,6 +41,7 @@ func TestUUIDMap(t *testing.T) {
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"), want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
wantErr: false, wantErr: false,
}, },
// GENERATED BY 'xray uuid -i'
{ {
name: "uuid-map-2", name: "uuid-map-2",
args: args{ args: args{