Skip to content

Commit

Permalink
Treat byte slices as binary blobs in Any (#339)
Browse files Browse the repository at this point in the history
Since `byte` and `uint8` are aliases (as are `rune` and `int32`), `Any` can't distinguish them. To match our intuition about what users likely intend, treat single bytes as integers, byte slices as binary blobs, and runes as integers.
  • Loading branch information
ansel1 authored and akshayjshah committed Feb 24, 2017
1 parent a4c2b88 commit 12592ca
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
8 changes: 6 additions & 2 deletions field.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@ func Object(key string, val zapcore.ObjectMarshaler) zapcore.Field {
// Any takes a key and an arbitrary value and chooses the best way to represent
// them as a field, falling back to a reflection-based approach only if
// necessary.
//
// Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between
// them. To minimize suprise, []byte values are treated as binary blobs, byte
// values are treated as uint8, and runes are always treated as integers.
func Any(key string, value interface{}) zapcore.Field {
switch val := value.(type) {
case zapcore.ObjectMarshaler:
Expand Down Expand Up @@ -292,8 +296,8 @@ func Any(key string, value interface{}) zapcore.Field {
return Uint16s(key, val)
case uint8:
return Uint8(key, val)
case []uint8:
return Uint8s(key, val)
case []byte:
return Binary(key, val)
case uintptr:
return Uintptr(key, val)
case []uintptr:
Expand Down
4 changes: 2 additions & 2 deletions field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func TestFieldConstructors(t *testing.T) {
{"Any:Bool", Any("k", true), Bool("k", true)},
{"Any:Bools", Any("k", []bool{true}), Bools("k", []bool{true})},
{"Any:Byte", Any("k", byte(1)), Uint8("k", 1)},
{"Any:Bytes", Any("k", []byte{1}), Uint8s("k", []uint8{1})},
{"Any:Bytes", Any("k", []byte{1}), Binary("k", []byte{1})},
{"Any:Complex128", Any("k", 1+2i), Complex128("k", 1+2i)},
{"Any:Complex128s", Any("k", []complex128{1 + 2i}), Complex128s("k", []complex128{1 + 2i})},
{"Any:Complex64", Any("k", complex64(1+2i)), Complex64("k", 1+2i)},
Expand Down Expand Up @@ -144,7 +144,7 @@ func TestFieldConstructors(t *testing.T) {
{"Any:Uint16", Any("k", uint16(1)), Uint16("k", 1)},
{"Any:Uint16s", Any("k", []uint16{1}), Uint16s("k", []uint16{1})},
{"Any:Uint8", Any("k", uint8(1)), Uint8("k", 1)},
{"Any:Uint8s", Any("k", []uint8{1}), Uint8s("k", []uint8{1})},
{"Any:Uint8s", Any("k", []uint8{1}), Binary("k", []uint8{1})},
{"Any:Uintptr", Any("k", uintptr(1)), Uintptr("k", 1)},
{"Any:Uintptrs", Any("k", []uintptr{1}), Uintptrs("k", []uintptr{1})},
{"Any:Time", Any("k", time.Unix(0, 0)), Time("k", time.Unix(0, 0))},
Expand Down

0 comments on commit 12592ca

Please sign in to comment.