-
Notifications
You must be signed in to change notification settings - Fork 17
/
quaternion-in-json.go
83 lines (69 loc) · 1.59 KB
/
quaternion-in-json.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
package main
import (
"encoding/json"
"fmt"
"github.com/alexflint/go-restructure"
)
var quaternionRegexp = restructure.MustCompile(QuotedQuaternion{}, restructure.Options{})
type RealPart struct {
Sign string `regexp:"[+-]?"`
Real string `regexp:"[0-9]+"`
}
type SignedInt struct {
Sign string `regexp:"[+-]"`
Real string `regexp:"[0-9]+"`
}
type IPart struct {
Magnitude SignedInt
_ struct{} `regexp:"i"`
}
type JPart struct {
Magnitude SignedInt
_ struct{} `regexp:"j"`
}
type KPart struct {
Magnitude SignedInt
_ struct{} `regexp:"k"`
}
// matches "1+2i+3j+4k", "-1+2k", "-1", etc
type Quaternion struct {
Real *RealPart
I *IPart `regexp:"?"`
J *JPart `regexp:"?"`
K *KPart `regexp:"?"`
}
// matches the quoted strings `"-1+2i+3j+4k"`, `"3-4k"`, `"12+34i"`, etc
type QuotedQuaternion struct {
_ struct{} `regexp:"^"`
_ struct{} `regexp:"\""`
Quaternion *Quaternion
_ struct{} `regexp:"\""`
_ struct{} `regexp:"$"`
}
func (c *QuotedQuaternion) UnmarshalJSON(b []byte) error {
if !quaternionRegexp.Find(c, string(b)) {
return fmt.Errorf("%s is not a quaternion number", string(b))
}
return nil
}
// this struct is handled by JSON
type Var struct {
Name string
Value *QuotedQuaternion
}
func prettyPrint(x interface{}) string {
buf, err := json.MarshalIndent(x, "", " ")
if err != nil {
return err.Error()
}
return string(buf)
}
func main() {
src := `{"name": "foo", "value": "1+2i+3j+4k"}`
var v Var
err := json.Unmarshal([]byte(src), &v)
if err != nil {
fmt.Println(err)
}
fmt.Println(prettyPrint(v))
}