Unmarshal ints and floats

This commit is contained in:
Thomas Pelletier
2021-03-14 18:06:34 -04:00
parent 9a1cfcdd8e
commit 590d674153
7 changed files with 368 additions and 245 deletions
+35 -3
View File
@@ -158,11 +158,43 @@ func (n *Node) Key() []Node {
// Guaranteed to be non-nil.
// Panics if not called on a KeyValue node, or if the Children are malformed.
func (n *Node) Value() *Node {
if n.Kind != KeyValue {
panic(fmt.Errorf("Key() should only be called on on a KeyValue, not %s", n.Kind))
}
assertKind(KeyValue, n)
if len(n.Children) < 2 {
panic(fmt.Errorf("KeyValue should have at least two children, not %d", len(n.Children)))
}
return &n.Children[len(n.Children)-1]
}
// DecodeInteger parse the data of an Integer node and returns the represented
// int64, or an error.
// Panics if not called on an Integer node.
func (n *Node) DecodeInteger() (int64, error) {
assertKind(Integer, n)
if len(n.Data) > 2 && n.Data[0] == '0' {
switch n.Data[1] {
case 'x':
return parseIntHex(n.Data)
case 'b':
return parseIntBin(n.Data)
case 'o':
return parseIntOct(n.Data)
default:
return 0, fmt.Errorf("invalid base: '%c'", n.Data[1])
}
}
return parseIntDec(n.Data)
}
// DecodeFloat parse the data of a Float node and returns the represented
// float64, or an error.
// Panics if not called on an Float node.
func (n *Node) DecodeFloat() (float64, error) {
assertKind(Float, n)
return parseFloat(n.Data)
}
func assertKind(k Kind, n *Node) {
if n.Kind != k {
panic(fmt.Errorf("method was expecting a %s, not a %s", k, n.Kind))
}
}