Skip to content

Commit

Permalink
Close BurntSushi#39.
Browse files Browse the repository at this point in the history
Added @SvenDowideit's round trip test which reproduces the bug in BurntSushi#39.

Close BurntSushi#40.
  • Loading branch information
BurntSushi committed May 16, 2014
1 parent dbcc327 commit a5e2f9c
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 63 deletions.
23 changes: 13 additions & 10 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,17 @@ func (enc *Encoder) eElement(rv reflect.Value) error {
_, err := io.WriteString(enc.w, s)
return err
}
writeQuoted := func(s string) error {
s = strings.NewReplacer(
"\t", "\\t",
"\n", "\\n",
"\r", "\\r",
"\"", "\\\"",
"\\", "\\\\",
).Replace(s)
return ws("\"" + s + "\"")
}

// By the TOML spec, all floats must have a decimal with at least one
// number on either side.
floatAddDecimal := func(fstr string) string {
Expand All @@ -133,7 +144,7 @@ func (enc *Encoder) eElement(rv reflect.Value) error {
if err != nil {
return err
}
return ws(string(s))
return writeQuoted(string(s))
}

var err error
Expand All @@ -155,15 +166,7 @@ func (enc *Encoder) eElement(rv reflect.Value) error {
case reflect.Interface:
return enc.eElement(rv.Elem())
case reflect.String:
s := rv.String()
s = strings.NewReplacer(
"\t", "\\t",
"\n", "\\n",
"\r", "\\r",
"\"", "\\\"",
"\\", "\\\\",
).Replace(s)
err = ws("\"" + s + "\"")
err = writeQuoted(rv.String())
default:
return e("Unexpected primitive type: %s", k)
}
Expand Down
49 changes: 49 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,59 @@ package toml
import (
"bytes"
"fmt"
"log"
"net"
"testing"
"time"
)

func TestEncodeRoundTrip(t *testing.T) {
type Config struct {
Age int
Cats []string
Pi float64
Perfection []int
DOB time.Time
Ipaddress net.IP
}

var inputs = Config{
13,
[]string{"one", "two", "three"},
3.145,
[]int{11, 2, 3, 4},
time.Now(),
net.ParseIP("192.168.59.254"),
}

var firstBuffer bytes.Buffer
e := NewEncoder(&firstBuffer)
err := e.Encode(inputs)
if err != nil {
t.Fatal(err)
}
var outputs Config
if _, err := Decode(firstBuffer.String(), &outputs); err != nil {
log.Printf("Could not decode:\n-----\n%s\n-----\n",
firstBuffer.String())
t.Fatal(err)
}

// could test each value individually, but I'm lazy
var secondBuffer bytes.Buffer
e2 := NewEncoder(&secondBuffer)
err = e2.Encode(outputs)
if err != nil {
t.Fatal(err)
}
if firstBuffer.String() != secondBuffer.String() {
t.Error(
firstBuffer.String(),
"\n\n is not identical to\n\n",
secondBuffer.String())
}
}

// XXX(burntsushi)
// I think these tests probably should be removed. They are good, but they
// ought to be obsolete by toml-test.
Expand Down
53 changes: 0 additions & 53 deletions toml_test.go

This file was deleted.

0 comments on commit a5e2f9c

Please sign in to comment.