File: enum_support.go

package info (click to toggle)
golang-github-onsi-ginkgo-v2 2.15.0-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 4,112 kB
  • sloc: javascript: 59; sh: 14; makefile: 7
file content (43 lines) | stat: -rw-r--r-- 923 bytes parent folder | download | duplicates (2)
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
package types

import "encoding/json"

type EnumSupport struct {
	toString map[uint]string
	toEnum   map[string]uint
	maxEnum  uint
}

func NewEnumSupport(toString map[uint]string) EnumSupport {
	toEnum, maxEnum := map[string]uint{}, uint(0)
	for k, v := range toString {
		toEnum[v] = k
		if maxEnum < k {
			maxEnum = k
		}
	}
	return EnumSupport{toString: toString, toEnum: toEnum, maxEnum: maxEnum}
}

func (es EnumSupport) String(e uint) string {
	if e > es.maxEnum {
		return es.toString[0]
	}
	return es.toString[e]
}

func (es EnumSupport) UnmarshJSON(b []byte) (uint, error) {
	var dec string
	if err := json.Unmarshal(b, &dec); err != nil {
		return 0, err
	}
	out := es.toEnum[dec] // if we miss we get 0 which is what we want anyway
	return out, nil
}

func (es EnumSupport) MarshJSON(e uint) ([]byte, error) {
	if e == 0 || e > es.maxEnum {
		return json.Marshal(nil)
	}
	return json.Marshal(es.toString[e])
}