OLD | NEW |
1 package model | 1 package model |
2 | 2 |
3 import ( | 3 import ( |
4 "bytes" | 4 "bytes" |
5 "math" | |
6 "strconv" | 5 "strconv" |
7 ) | 6 ) |
8 | 7 |
9 func round(f float64) int { | 8 // Node is a node in a Tests tree. |
10 » if math.Abs(f) < 0.5 { | 9 // |
11 » » return 0 | 10 // In reality, it as almost as weak as empty interface, |
12 » } | 11 // but the unexported method allow the package to achieve |
13 » return int(f + math.Copysign(0.5, f)) | 12 // type safety internally. |
| 13 type Node interface { |
| 14 » node() |
14 } | 15 } |
15 | 16 |
16 // TestNode is a node in a Tests tree. | 17 // Number is an integer that supports JSON unmarshaling from a string |
17 type TestNode interface { | 18 // and marshaling back to a string. |
18 » // Children returns a map of a TestNode's children. | 19 type Number int |
19 » Children() map[string]TestNode | |
20 | 20 |
21 » testnode() | 21 // UnmarshalJSON unmarshals data into n. |
22 } | 22 // data is expected to be a JSON string. If the string |
23 | 23 // fails to parse to an integer, UnmarshalJSON returns |
24 // number is an integer that supports JSON unmarshaling from a string | 24 // an error. |
25 // and marshaling back to a string. | 25 func (n *Number) UnmarshalJSON(data []byte) error { |
26 type number int | |
27 | |
28 func (n *number) UnmarshalJSON(data []byte) error { | |
29 data = bytes.Trim(data, `"`) | 26 data = bytes.Trim(data, `"`) |
30 num, err := strconv.Atoi(string(data)) | 27 num, err := strconv.Atoi(string(data)) |
31 if err != nil { | 28 if err != nil { |
32 return err | 29 return err |
33 } | 30 } |
34 » *n = number(num) | 31 » *n = Number(num) |
35 return nil | 32 return nil |
36 } | 33 } |
37 | 34 |
38 func (n *number) MarshalJSON() ([]byte, error) { | 35 // MarshalJSON marshals n into JSON string. |
| 36 func (n *Number) MarshalJSON() ([]byte, error) { |
39 return []byte(strconv.Itoa(int(*n))), nil | 37 return []byte(strconv.Itoa(int(*n))), nil |
40 } | 38 } |
OLD | NEW |