Skip to content

Commit 1dec25a

Browse files
committed
Document encoding
1 parent b1f97d8 commit 1dec25a

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

map.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,19 @@ var _ json.Marshaler = Map(nil)
2323
// MarshalJSON implements json.Marshaler.
2424
//
2525
// It is guaranteed to return a nil error.
26-
// Any error marshalling a field will
27-
// become the field's value.
26+
// Any error marshalling a field will become the field's value.
27+
//
28+
// Every field value is encoded with the following process:
29+
//
30+
// 1. slog.Value is handled to allow any type to replace its representation for logging.
31+
//
32+
// 2. xerrors.Formatter is handled.
33+
//
34+
// 3. error and fmt.Stringer are handled.
35+
//
36+
// 4. slices and arrays are handled to go through the encode function for every value.
37+
//
38+
// 5. json.Marshal is invoked as the default case.
2839
func (m Map) MarshalJSON() ([]byte, error) {
2940
b := &bytes.Buffer{}
3041
b.WriteByte('{')
@@ -90,8 +101,7 @@ func encode(v interface{}) []byte {
90101
switch rv.Type().Kind() {
91102
case reflect.Slice:
92103
if rv.IsNil() {
93-
b, _ := json.Marshal(nil)
94-
return b
104+
break
95105
}
96106
fallthrough
97107
case reflect.Array:

map_test.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func TestMap(t *testing.T) {
9393
{
9494
"msg": "failed to marshal to JSON",
9595
"fun": "cdr.dev/slog.encode",
96-
"loc": "`+mapTestFile+`:105"
96+
"loc": "`+mapTestFile+`:115"
9797
},
9898
"json: unsupported type: func(*testing.T, string) string"
9999
],
@@ -164,6 +164,16 @@ func TestMap(t *testing.T) {
164164
"error": "xdxd"
165165
}`)
166166
})
167+
168+
t.Run("nilSlice", func(t *testing.T) {
169+
t.Parallel()
170+
171+
test(t, slog.M(
172+
slog.F("slice", []string(nil)),
173+
), `{
174+
"slice": null
175+
}`)
176+
})
167177
}
168178

169179
type meow struct {

0 commit comments

Comments
 (0)