Skip to content

Commit

Permalink
Handle empty keyword strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
jjeffery committed Jan 23, 2017
1 parent cf4da72 commit a2a9ec5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
24 changes: 21 additions & 3 deletions logfmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import (

// constant byte values
var (
bytesNull = []byte("null")
bytesPanic = []byte(`<PANIC>`)
bytesError = []byte(`<ERROR>`)
bytesNull = []byte("null")
bytesPanic = []byte(`<PANIC>`)
bytesError = []byte(`<ERROR>`)
bytesEmptyK = []byte(`<EMPTY>`)
bytesEmptyV = []byte(`""`)

escapeSequences = map[rune]string{
'\t': `\t`,
Expand Down Expand Up @@ -83,6 +85,10 @@ func writeBytesKey(buf *bytes.Buffer, b []byte) {
buf.Write(bytesNull)
return
}
if len(b) == 0 {
buf.Write(bytesEmptyK)
return
}
for {
index := bytes.IndexFunc(b, invalidKey)
if index < 0 {
Expand All @@ -100,6 +106,10 @@ func writeBytesKey(buf *bytes.Buffer, b []byte) {
}

func writeStringKey(buf *bytes.Buffer, s string) {
if s == "" {
buf.Write(bytesEmptyK)
return
}
index := strings.IndexFunc(s, invalidKey)
if index < 0 {
buf.WriteString(s)
Expand Down Expand Up @@ -173,6 +183,10 @@ func writeBytesValue(buf *bytes.Buffer, b []byte) {
buf.Write(bytesNull)
return
}
if len(b) == 0 {
buf.Write(bytesEmptyV)
return
}
index := bytes.IndexFunc(b, needsQuote)
if index < 0 {
buf.Write(b)
Expand Down Expand Up @@ -201,6 +215,10 @@ func writeBytesValue(buf *bytes.Buffer, b []byte) {
}

func writeStringValue(buf *bytes.Buffer, s string) {
if s == "" {
buf.Write(bytesEmptyV)
return
}
index := strings.IndexFunc(s, needsQuote)
if index < 0 {
buf.WriteString(s)
Expand Down
7 changes: 6 additions & 1 deletion logfmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ func TestWriteKeyValue(t *testing.T) {
value: 25,
want: "17=25",
},
{
key: "",
value: "",
want: `<EMPTY>=""`,
},
{
key: nil,
value: nil,
Expand Down Expand Up @@ -116,7 +121,7 @@ func TestWriteKeyValue(t *testing.T) {
var buf bytes.Buffer
writeKeyValue(&buf, key, value)
if got := buf.String(); got != want {
t.Errorf("%d: got=%s want=%s", i, got, want)
t.Errorf("%d: got `%s` want `%s`", i, got, want)
}
}
doTest(tt.key, tt.value, tt.want)
Expand Down

0 comments on commit a2a9ec5

Please sign in to comment.