Add some helpers for tree manipulation

This commit is contained in:
Thomas Pelletier
2013-02-24 19:22:25 +01:00
parent a4e5fe8d12
commit 3c9a474015
3 changed files with 81 additions and 2 deletions
+26
View File
@@ -1,3 +1,29 @@
// TOML Parser.
package toml
import (
"strings"
)
// Given a tree and a key, create the necessary intermediate subtrees to create
// a subtree at that point. In-place.
//
// e.g. passing a.b.c will create (assuming tree is empty) tree[a], tree[a][b]
// and tree[a][b][c]
func createSubTree(tree *tomlTree, key string) {
subtree := tree
for _, intermediate_key := range strings.Split(key, ".") {
_, exists := (*subtree)[intermediate_key]
if !exists {
(*subtree)[intermediate_key] = make(tomlTree)
}
subtree = (*subtree)[intermediate_key].(*tomlTree)
}
}
func parse(chan token) *tomlTree {
result := make(tomlTree)
return &result
}
+13
View File
@@ -0,0 +1,13 @@
package toml
import "testing"
func testCreateSubTree(t *testing.T) {
tree := make(tomlTree)
createSubTree(&tree, "a.b.c")
tree.Set("a.b.c", 42)
if tree.Get("a.b.c") != 42 {
t.Fail()
}
}
+42 -2
View File
@@ -2,7 +2,47 @@
package toml
func Load() map[string]interface{} {
result := make(map[string]interface{})
import (
"strings"
)
// Definition of a tomlTree
type tomlTree map[string]interface{}
// Retrieve an element from the tree.
//
// If the path described by the key does not exist, nil is returned.
func (t *tomlTree) Get(key string) interface{} {
subtree := t
keys := strings.Split(key, ".")
for _, intermediate_key := range keys[:len(keys)-1] {
_, exists := (*subtree)[intermediate_key]
if !exists {
return nil
}
subtree = (*subtree)[intermediate_key].(*tomlTree)
}
return (*subtree)[keys[len(keys) - 1]]
}
// Set an element in the tree.
//
// Creates all necessary intermediates trees, if needed.
func (t *tomlTree) Set(key string, value interface{}) {
subtree := t
keys := strings.Split(key, ".")
for _, intermediate_key := range keys[:len(keys)-1] {
_, exists := (*subtree)[intermediate_key]
if !exists {
(*subtree)[intermediate_key] = make(tomlTree)
}
subtree = (*subtree)[intermediate_key].(*tomlTree)
}
(*subtree)[keys[len(key) - 1]] = value
}
func Load() tomlTree {
result := make(tomlTree)
return result
}