-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.go
61 lines (57 loc) · 1.21 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* @file: parse.go
* @author: Jorge Quitério
* @copyright (c) 2022 Jorge Quitério
* @license: MIT
*/
package uuid
import (
"encoding/hex"
"regexp"
"strings"
)
// Parse decodes s string into a UUID or returns NilUUID if the string is invalid.
// formats:
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
func Parse(in interface{}) UUID {
u := UUID{}
switch in := in.(type) {
case string:
r, _ := regexp.Compile(`^(|{|urn:uuid:)([0-9a-fA-F]{8})\-([0-9a-fA-F]{4})\-([0-9a-fA-F]{4})\-([0-9a-fA-F]{4})\-([0-9a-fA-F]{12})(|})$`)
if r.MatchString(in) {
in = strings.Replace(in, "urn:uuid:", "", 1)
in = strings.Replace(in, "{", "", 1)
in = strings.Replace(in, "}", "", 1)
in = strings.Replace(in, "-", "", 4)
} else {
return Nil
}
b, err := hex.DecodeString(in)
if err != nil {
return Nil
}
if len(b) != 16 {
return Nil
}
copy(u[:], b)
return u
case []byte:
if len(in) != 16 {
return Nil
}
copy(u[:], in)
return u
case UUID:
return in
case nil:
return Nil
default:
return Nil
}
}
func IsValid(in interface{}) bool {
return Parse(in) != Nil
}