-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboolExprType.go
81 lines (69 loc) · 1.99 KB
/
boolExprType.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
package squl
import (
"bytes"
"encoding/json"
"strings"
fmt "golang.org/x/xerrors"
"github.com/trivigy/squl/internal/global"
)
// BoolExprType describes the types of boolean expressions available.
type BoolExprType int
const (
// BoolExprTypeAnd describes the AND expression.
BoolExprTypeAnd BoolExprType = iota + 1
// BoolExprTypeOr describes the OR expression.
BoolExprTypeOr
)
const (
boolExprTypeAndStr = "and"
boolExprTypeOrStr = "or"
)
var toStringBoolExprType = map[BoolExprType]string{
BoolExprType(Unknown): unknownStr,
BoolExprTypeAnd: boolExprTypeAndStr,
BoolExprTypeOr: boolExprTypeOrStr,
}
// NewBoolExprType creates a new instance of the enum from raw string.
func NewBoolExprType(raw string) (BoolExprType, error) {
switch raw {
case boolExprTypeAndStr:
return BoolExprTypeAnd, nil
case boolExprTypeOrStr:
return BoolExprTypeOr, nil
default:
return BoolExprType(Unknown), fmt.Errorf(global.ErrFmt, pkg.Name(), fmt.Errorf("unknown type %q", raw))
}
}
// String returns the string representation of the enum type
func (r BoolExprType) String() string {
return toStringBoolExprType[r]
}
// UnmarshalJSON unmarshals a quoted json string to enum type.
func (r *BoolExprType) UnmarshalJSON(rbytes []byte) error {
var s string
if err := json.Unmarshal(rbytes, &s); err != nil {
return err
}
raw := strings.ToLower(s)
switch raw {
case boolExprTypeAndStr:
*r = BoolExprTypeAnd
case boolExprTypeOrStr:
*r = BoolExprTypeOr
default:
*r = Unknown
return fmt.Errorf(global.ErrFmt, pkg.Name(), fmt.Errorf("unknown type %q", raw))
}
return nil
}
// MarshalJSON marshals the enum as a quoted json string.
func (r BoolExprType) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
if _, err := buffer.WriteString(toStringBoolExprType[r]); err != nil {
return nil, fmt.Errorf(global.ErrFmt, pkg.Name(), err)
}
if _, err := buffer.WriteString(`"`); err != nil {
return nil, fmt.Errorf(global.ErrFmt, pkg.Name(), err)
}
return buffer.Bytes(), nil
}