From 43e8de35edcec045c84f04128163334ddeabfa24 Mon Sep 17 00:00:00 2001 From: phuslu Date: Sun, 19 Jul 2020 23:17:50 +0800 Subject: [PATCH] add Encode method for memory sensitive cases Signed-off-by: phuslu --- id.go | 6 ++++++ id_test.go | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/id.go b/id.go index dbd1535..f1db1a1 100644 --- a/id.go +++ b/id.go @@ -181,6 +181,12 @@ func (id ID) String() string { return *(*string)(unsafe.Pointer(&text)) } +// Encode encodes the id using base32 encoding, writing 20 bytes to dst and return it. +func (id ID) Encode(dst []byte) []byte { + encode(dst, id[:]) + return dst +} + // MarshalText implements encoding/text TextMarshaler interface func (id ID) MarshalText() ([]byte, error) { text := make([]byte, encodedLen) diff --git a/id_test.go b/id_test.go index 29d01a0..0cbc816 100644 --- a/id_test.go +++ b/id_test.go @@ -105,6 +105,14 @@ func TestIDString(t *testing.T) { } } +func TestIDEncode(t *testing.T) { + id := ID{0x4d, 0x88, 0xe1, 0x5b, 0x60, 0xf4, 0x86, 0xe4, 0x28, 0x41, 0x2d, 0xc9} + text := make([]byte, encodedLen) + if got, want := string(id.Encode(text)), "9m4e2mr0ui3e8a215n4g"; got != want { + t.Errorf("Encode() = %v, want %v", got, want) + } +} + func TestFromString(t *testing.T) { got, err := FromString("9m4e2mr0ui3e8a215n4g") if err != nil {