-
Notifications
You must be signed in to change notification settings - Fork 0
/
animal.go
107 lines (95 loc) · 2.03 KB
/
animal.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package serendipity
import (
"bytes"
"database/sql/driver"
"encoding/json"
"fmt"
"log"
)
type AnimalType int
const (
AnimalTypeUnknown AnimalType = iota
AnimalTypeOcean
AnimalTypeDesert
AnimalTypeGrassland
AnimalTypeForest
AnimalTypeFarm
AnimalTypePet
AnimalTypeZoo
)
var animalTypeText = map[AnimalType]string{
AnimalTypeUnknown: "Unknown",
AnimalTypeOcean: "ocean",
AnimalTypeDesert: "desert",
AnimalTypeGrassland: "grassland",
AnimalTypeForest: "forest",
AnimalTypeFarm: "farm",
AnimalTypePet: "pet",
AnimalTypeZoo: "zoo",
}
func AnimalTypeText(code AnimalType) string {
return animalTypeText[code]
}
func (enum AnimalType) String() string {
if val, ok := animalTypeText[enum]; ok {
return val
}
return animalTypeText[AnimalTypeUnknown]
}
func (s *AnimalType) Scan(value interface{}) error {
*s = AnimalTypeUnknown
bytes, ok := value.([]byte)
if !ok {
val, ok := value.(string)
if !ok {
return nil //errors.New("Scan source is not []byte")
}
bytes = []byte(val)
}
for k, v := range animalTypeText {
if string(bytes) == v {
*s = k
return nil
}
}
return nil
}
func (s AnimalType) Value() (driver.Value, error) {
return AnimalTypeText(s), nil
}
func (s AnimalType) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(AnimalTypeText(s))
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
func (s *AnimalType) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
return s.Scan([]byte(j))
}
func (r *Serendipity) AnimalType() AnimalType {
return AnimalType(r.N(int(AnimalTypeOcean), int(AnimalTypeZoo)))
}
func (r *Serendipity) Animal(animalType ...AnimalType) string {
a := AnimalTypeUnknown
if len(animalType) > 0 {
a = animalType[0]
} else {
a = r.AnimalType()
}
obj, err := r.loadStrings(fmt.Sprintf("/animal_%s.txt", a.String()))
if err != nil {
log.Println(err)
return ""
}
count := len(*obj)
if count == 0 {
return ""
}
i := r.N(0, count-1)
return (*obj)[i]
}