File: type_info.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.124.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,288 kB
  • sloc: sh: 344; makefile: 4
file content (54 lines) | stat: -rw-r--r-- 985 bytes parent folder | download | duplicates (3)
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
package openapi3gen

import (
	"reflect"
	"sort"
	"sync"
)

var (
	typeInfos      = map[reflect.Type]*theTypeInfo{}
	typeInfosMutex sync.RWMutex
)

// theTypeInfo contains information about JSON serialization of a type
type theTypeInfo struct {
	Type   reflect.Type
	Fields []theFieldInfo
}

// getTypeInfo returns theTypeInfo for the given type.
func getTypeInfo(t reflect.Type) *theTypeInfo {
	for t.Kind() == reflect.Ptr {
		t = t.Elem()
	}
	typeInfosMutex.RLock()
	typeInfo, exists := typeInfos[t]
	typeInfosMutex.RUnlock()
	if exists {
		return typeInfo
	}
	if t.Kind() != reflect.Struct {
		typeInfo = &theTypeInfo{
			Type: t,
		}
	} else {
		// Allocate
		typeInfo = &theTypeInfo{
			Type:   t,
			Fields: make([]theFieldInfo, 0, 16),
		}

		// Add fields
		typeInfo.Fields = appendFields(nil, nil, t)

		// Sort fields
		sort.Sort(sortableFieldInfos(typeInfo.Fields))
	}

	// Publish
	typeInfosMutex.Lock()
	typeInfos[t] = typeInfo
	typeInfosMutex.Unlock()
	return typeInfo
}