From ead5bb5bc6ddcca03e0d0b981e2f925e326788c7 Mon Sep 17 00:00:00 2001 From: Pieter Joost van de Sande Date: Thu, 10 Jan 2019 08:57:11 +0100 Subject: [PATCH] add Printable example to docs --- bindings/go/src/fdb/fdb.go | 9 ++++++++- bindings/go/src/fdb/fdb_test.go | 7 ++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/bindings/go/src/fdb/fdb.go b/bindings/go/src/fdb/fdb.go index 4037ac3360..212e712a31 100644 --- a/bindings/go/src/fdb/fdb.go +++ b/bindings/go/src/fdb/fdb.go @@ -380,8 +380,15 @@ func (k Key) FDBKey() Key { // String describes the key as a hexadecimal encoded string. func (k Key) String() string { + return Printable(k) +} + +// Printable returns a human readable version of a byte array. The bytes that correspond with +// ASCII printable characters [32-127) are passed through. Other bytes are +// replaced with \x followed by a two character zero-padded hex code for byte. +func Printable(d []byte) string { var sb strings.Builder - for _, b := range k { + for _, b := range d { if b >= 32 && b < 127 && b != '\\' { sb.WriteByte(b) continue diff --git a/bindings/go/src/fdb/fdb_test.go b/bindings/go/src/fdb/fdb_test.go index 768e93c8fe..ed9478878a 100644 --- a/bindings/go/src/fdb/fdb_test.go +++ b/bindings/go/src/fdb/fdb_test.go @@ -268,8 +268,8 @@ func TestKeyToString(t *testing.T) { key fdb.Key expect string }{ - {fdb.Key("plain-text"), "plain-text"}, {fdb.Key([]byte{0}), "\\x00"}, + {fdb.Key("plain-text"), "plain-text"}, {fdb.Key("\xbdascii☻☺"), "\\xbdascii\\xe2\\x98\\xbb\\xe2\\x98\\xba"}, } @@ -279,3 +279,8 @@ func TestKeyToString(t *testing.T) { } } } + +func ExamplePrintable() { + fmt.Println(fdb.Printable([]byte{0, 1, 2, 'a', 'b', 'c', '1', '2', '3', '!', '?', 255})) + // Output: \x00\x01\x02abc123!?\xff +}