-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum.go
45 lines (38 loc) · 908 Bytes
/
enum.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
package orm
import (
"reflect"
)
type EnumValues interface {
EnumValues() any
}
type enumDefinition struct {
fields []string
mapping map[string]int
required bool
defaultValue string
name string
}
func (d *enumDefinition) GetFields() []string {
return d.fields
}
func (d *enumDefinition) Has(value string) bool {
_, has := d.mapping[value]
return has
}
func (d *enumDefinition) Index(value string) int {
return d.mapping[value]
}
func initEnumDefinition(name string, def any, required bool) *enumDefinition {
enum := &enumDefinition{required: required}
e := reflect.ValueOf(def)
enum.mapping = make(map[string]int)
enum.name = name
enum.fields = make([]string, 0)
for i := 0; i < e.Type().NumField(); i++ {
name := e.Field(i).String()
enum.fields = append(enum.fields, name)
enum.mapping[name] = i + 1
}
enum.defaultValue = enum.fields[0]
return enum
}