Skip to content

Add reflection encoder for lists #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 35 additions & 8 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,29 @@ import (
// Map represents an ordered map of fields.
type Map []Field

// SlogValue implements Value.
func (m Map) SlogValue() interface{} {
return ForceJSON(m)
}

var _ json.Marshaler = Map(nil)

// MarshalJSON implements json.Marshaler.
//
// It is guaranteed to return a nil error.
// Any error marshalling a field will
// become the field's value.
// Any error marshalling a field will become the field's value.
//
// Every field value is encoded with the following process:
//
// 1. slog.Value is handled to allow any type to replace its representation for logging.
//
// 2. xerrors.Formatter is handled.
//
// 3. error and fmt.Stringer are handled.
//
// 4. slices and arrays are handled to go through the encode function for every value.
//
// 5. json.Marshal is invoked as the default case.
func (m Map) MarshalJSON() ([]byte, error) {
b := &bytes.Buffer{}
b.WriteByte('{')
Expand Down Expand Up @@ -55,14 +71,14 @@ func (v jsonVal) MarshalJSON() ([]byte, error) {
return json.Marshal(v.v)
}

func marshalArray(a []interface{}) []byte {
func marshalList(rv reflect.Value) []byte {
b := &bytes.Buffer{}
b.WriteByte('[')
for i, v := range a {
for i := 0; i < rv.Len(); i++ {
b.WriteByte('\n')
b.Write(encode(v))
b.Write(encode(rv.Index(i).Interface()))

if i < len(a)-1 {
if i < rv.Len()-1 {
b.WriteByte(',')
}
}
Expand All @@ -75,13 +91,24 @@ func encode(v interface{}) []byte {
switch v := v.(type) {
case Value:
return encode(v.SlogValue())
case []interface{}:
return marshalArray(v)
case xerrors.Formatter:
return encode(errorChain(v))
case error, fmt.Stringer:
return encode(fmt.Sprint(v))
default:
rv := reflect.Indirect(reflect.ValueOf(v))
if rv.IsValid() {
switch rv.Type().Kind() {
case reflect.Slice:
if rv.IsNil() {
break
}
fallthrough
case reflect.Array:
return marshalList(rv)
}
}

b, err := json.Marshal(v)
if err != nil {
return encode(M(
Expand Down
12 changes: 11 additions & 1 deletion map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func TestMap(t *testing.T) {
{
"msg": "failed to marshal to JSON",
"fun": "cdr.dev/slog.encode",
"loc": "`+mapTestFile+`:88"
"loc": "`+mapTestFile+`:115"
},
"json: unsupported type: func(*testing.T, string) string"
],
Expand Down Expand Up @@ -164,6 +164,16 @@ func TestMap(t *testing.T) {
"error": "xdxd"
}`)
})

t.Run("nilSlice", func(t *testing.T) {
t.Parallel()

test(t, slog.M(
slog.F("slice", []string(nil)),
), `{
"slice": null
}`)
})
}

type meow struct {
Expand Down