Skip to content

Commit

Permalink
go-ipfs-config: Merge pull request ipfs#16 from ipfs/fix/thread-safety
Browse files Browse the repository at this point in the history
add a Clone function
  • Loading branch information
Stebalien authored Dec 14, 2018
2 parents 16f3d22 + e4282bd commit b251798
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 0 deletions.
16 changes: 16 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,19 @@ func ToMap(conf *Config) (map[string]interface{}, error) {
}
return m, nil
}

// Clone copies the config. Use when updating.
func (c *Config) Clone() (*Config, error) {
var newConfig Config
var buf bytes.Buffer

if err := json.NewEncoder(&buf).Encode(c); err != nil {
return nil, fmt.Errorf("failure to encode config: %s", err)
}

if err := json.NewDecoder(&buf).Decode(&newConfig); err != nil {
return nil, fmt.Errorf("failure to decode config: %s", err)
}

return &newConfig, nil
}
29 changes: 29 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package config

import (
"testing"
)

func TestClone(t *testing.T) {
c := new(Config)
c.Identity.PeerID = "faketest"
c.API.HTTPHeaders = map[string][]string{"foo": {"bar"}}

newCfg, err := c.Clone()
if err != nil {
t.Fatal(err)
}
if newCfg.Identity.PeerID != c.Identity.PeerID {
t.Fatal("peer ID not preserved")
}

c.API.HTTPHeaders["foo"] = []string{"baz"}
if newCfg.API.HTTPHeaders["foo"][0] != "bar" {
t.Fatal("HTTP headers not preserved")
}

delete(c.API.HTTPHeaders, "foo")
if newCfg.API.HTTPHeaders["foo"][0] != "bar" {
t.Fatal("HTTP headers not preserved")
}
}
53 changes: 53 additions & 0 deletions config/types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package config

import (
"encoding/json"
"testing"
)

func TestOneStrings(t *testing.T) {
out, err := json.Marshal(Strings{"one"})
if err != nil {
t.Fatal(err)

}
expected := "\"one\""
if string(out) != expected {
t.Fatalf("expected %s, got %s", expected, string(out))
}
}

func TestNoStrings(t *testing.T) {
out, err := json.Marshal(Strings{})
if err != nil {
t.Fatal(err)

}
expected := "null"
if string(out) != expected {
t.Fatalf("expected %s, got %s", expected, string(out))
}
}

func TestManyStrings(t *testing.T) {
out, err := json.Marshal(Strings{"one", "two"})
if err != nil {
t.Fatal(err)

}
expected := "[\"one\",\"two\"]"
if string(out) != expected {
t.Fatalf("expected %s, got %s", expected, string(out))
}
}

func TestFunkyStrings(t *testing.T) {
toParse := " [ \"one\", \"two\" ] "
var s Strings
if err := json.Unmarshal([]byte(toParse), &s); err != nil {
t.Fatal(err)
}
if len(s) != 2 || s[0] != "one" && s[1] != "two" {
t.Fatalf("unexpected result: %v", s)
}
}

0 comments on commit b251798

Please sign in to comment.