-
Notifications
You must be signed in to change notification settings - Fork 0
/
ref.go
58 lines (46 loc) · 1005 Bytes
/
ref.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
package jschema
import (
"crypto/md5"
"encoding/json"
"fmt"
"reflect"
"regexp"
)
type Ref struct {
Defs string
Package string
Name string
Hash string
ID string
}
func (s *Schemas) Ref(v interface{}) Ref {
return s.RefT(reflect.TypeOf(v))
}
var regTrimGeneric = regexp.MustCompile(`\[.+\]$`)
func (s *Schemas) RefT(t reflect.Type) Ref {
hash := fmt.Sprintf("%x", md5.Sum([]byte(t.PkgPath()+t.Name())))
id := regTrimGeneric.ReplaceAllString(t.Name(), "")
list, ok := s.names[id]
if !ok {
list = map[string]int{}
s.names[id] = list
}
i := 0
if _, has := list[hash]; !has {
i = len(list)
list[hash] = i
}
if i != 0 {
id = fmt.Sprintf("%s%d", id, i)
}
return Ref{s.refPrefix, t.PkgPath(), t.Name(), hash, id}
}
func (r Ref) String() string {
return r.Package + "." + r.Name
}
func (r Ref) MarshalJSON() ([]byte, error) {
return json.Marshal(fmt.Sprintf("%s/%s", r.Defs, r.ID))
}
func (r Ref) Unique() bool {
return r.Package != "" && r.Name != ""
}