Skip to content

Commit

Permalink
A few boring stylistic changes
Browse files Browse the repository at this point in the history
Extracted from the as branch, reduces diff noise.
  • Loading branch information
arp242 committed Nov 24, 2021
1 parent 8014776 commit 14d3756
Show file tree
Hide file tree
Showing 7 changed files with 161 additions and 206 deletions.
19 changes: 11 additions & 8 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) {
return MetaData{}, e("Decode of nil %s", reflect.TypeOf(v))
}

// TODO: have parser should read from io.Reader? Or at the very least, make
// it read from []byte rather than string
// TODO: parser should read from io.Reader? Or at the very least, make it
// read from []byte rather than string
data, err := ioutil.ReadAll(dec.r)
if err != nil {
return MetaData{}, err
Expand All @@ -128,8 +128,11 @@ func (dec *Decoder) Decode(v interface{}) (MetaData, error) {
return MetaData{}, err
}
md := MetaData{
p.mapping, p.types, p.ordered,
make(map[string]bool, len(p.ordered)), nil,
mapping: p.mapping,
types: p.types,
keys: p.ordered,
decoded: make(map[string]bool, len(p.ordered)),
context: nil,
}
return md, md.unify(p.mapping, indirect(rv))
}
Expand Down Expand Up @@ -258,17 +261,17 @@ func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error {
for _, i := range f.index {
subv = indirect(subv.Field(i))
}

if isUnifiable(subv) {
md.decoded[md.context.add(key).String()] = true
md.context = append(md.context, key)
if err := md.unify(datum, subv); err != nil {
err := md.unify(datum, subv)
if err != nil {
return err
}
md.context = md.context[0 : len(md.context)-1]
} else if f.name != "" {
// Bad user! No soup for you!
return e("cannot write unexported field %s.%s",
rv.Type().String(), f.name)
return e("cannot write unexported field %s.%s", rv.Type().String(), f.name)
}
}
}
Expand Down
40 changes: 23 additions & 17 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var (
errAnything = errors.New("") // used in testing
)

var quotedReplacer = strings.NewReplacer(
var dblQuotedReplacer = strings.NewReplacer(
"\"", "\\\"",
"\\", "\\\\",
"\x00", `\u0000`,
Expand Down Expand Up @@ -95,13 +95,11 @@ type Marshaler interface {
// NOTE: only exported keys are encoded due to the use of reflection. Unexported
// keys are silently discarded.
type Encoder struct {
// The string to use for a single indentation level. The default is two
// spaces.
// String to use for a single indentation level; default is two spaces.
Indent string

// hasWritten is whether we have written any output to w yet.
hasWritten bool
w *bufio.Writer
hasWritten bool // written any output to w yet?
}

// NewEncoder create a new Encoder.
Expand Down Expand Up @@ -276,7 +274,7 @@ func floatAddDecimal(fstr string) string {
}

func (enc *Encoder) writeQuoted(s string) {
enc.wf("\"%s\"", quotedReplacer.Replace(s))
enc.wf("\"%s\"", dblQuotedReplacer.Replace(s))
}

func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) {
Expand Down Expand Up @@ -344,7 +342,7 @@ func (enc *Encoder) eMap(key Key, rv reflect.Value, inline bool) {
var mapKeysDirect, mapKeysSub []string
for _, mapKey := range rv.MapKeys() {
k := mapKey.String()
if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) {
if typeIsTable(tomlTypeOfGo(rv.MapIndex(mapKey))) {
mapKeysSub = append(mapKeysSub, k)
} else {
mapKeysDirect = append(mapKeysDirect, k)
Expand Down Expand Up @@ -426,7 +424,7 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
}
}

if typeIsHash(tomlTypeOfGo(frv)) {
if typeIsTable(tomlTypeOfGo(frv)) {
fieldsSub = append(fieldsSub, append(start, f.Index...))
} else {
// Copy so it works correct on 32bit archs; not clear why this
Expand Down Expand Up @@ -490,13 +488,13 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
}
}

// tomlTypeName returns the TOML type name of the Go value's type. It is
// used to determine whether the types of array elements are mixed (which is
// forbidden). If the Go value is nil, then it is illegal for it to be an array
// element, and valueIsNil is returned as true.

// Returns the TOML type of a Go value. The type may be `nil`, which means
// no concrete TOML type could be found.
// tomlTypeOfGo returns the TOML type name of the Go value's type.
//
// It is used to determine whether the types of array elements are mixed (which
// is forbidden). If the Go value is nil, then it is illegal for it to be an
// array element, and valueIsNil is returned as true.
//
// The type may be `nil`, which means no concrete TOML type could be found.
func tomlTypeOfGo(rv reflect.Value) tomlType {
if isNil(rv) || !rv.IsValid() {
return nil
Expand Down Expand Up @@ -632,7 +630,14 @@ func (enc *Encoder) newline() {
//
// key = <any value>
//
// If inline is true it won't add a newline at the end.
// This is also used for "k = v" in inline tables; so something like this will
// be written in three calls:
//
// ┌────────────────────┐
// │ ┌───┐ ┌─────┐│
// v v v v vv
// key = {k = v, k2 = v2}
//
func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) {
if len(key) == 0 {
encPanic(errNoKey)
Expand All @@ -645,7 +650,8 @@ func (enc *Encoder) writeKeyValue(key Key, val reflect.Value, inline bool) {
}

func (enc *Encoder) wf(format string, v ...interface{}) {
if _, err := fmt.Fprintf(enc.w, format, v...); err != nil {
_, err := fmt.Fprintf(enc.w, format, v...)
if err != nil {
encPanic(err)
}
enc.hasWritten = true
Expand Down
43 changes: 19 additions & 24 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,39 +22,34 @@ func TestEncodeRoundTrip(t *testing.T) {
}

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)
Age: 13,
Cats: []string{"one", "two", "three"},
Pi: 3.145,
Perfection: []int{11, 2, 3, 4},
DOB: time.Now(),
Ipaddress: net.ParseIP("192.168.59.254"),
}

var (
firstBuffer bytes.Buffer
secondBuffer bytes.Buffer
outputs Config
)
err := NewEncoder(&firstBuffer).Encode(inputs)
if err != nil {
t.Fatal(err)
}
var outputs Config
if _, err := Decode(firstBuffer.String(), &outputs); err != nil {
t.Logf("Could not decode:\n-----\n%s\n-----\n",
firstBuffer.String())
_, err = Decode(firstBuffer.String(), &outputs)
if err != nil {
t.Logf("Could not decode:\n%s\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)
err = NewEncoder(&secondBuffer).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())
t.Errorf("%s\n\nIS NOT IDENTICAL TO\n\n%s", firstBuffer.String(), secondBuffer.String())
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/tag/rm.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func Remove(typedJson interface{}) (interface{}, error) {
}
return m, nil

// Array: remove tags from all itenm.
// Array: remove tags from all items.
case []interface{}:
a := make([]interface{}, len(v))
for i := range v {
Expand Down
Loading

0 comments on commit 14d3756

Please sign in to comment.