Skip to content

Commit

Permalink
Feature: decode namespace id
Browse files Browse the repository at this point in the history
  • Loading branch information
aopoltorzhicky committed Nov 22, 2023
1 parent 1a98936 commit a38397a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cmd/api/handler/responses/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type Namespace struct {
PfbCount int64 `example:"12" format:"integer" json:"pfb_count" swaggertype:"integer"`
LastHeight pkgTypes.Level `example:"100" format:"int64" json:"last_height" swaggertype:"integer"`
LastMessageTime time.Time `example:"2023-07-04T03:10:57+00:00" format:"date-time" json:"last_message_time" swaggertype:"string"`
Name string `example:"name" format:"string" json:"name" swaggertype:"string"`
Reserved bool `example:"true" json:"reserved"`
}

Expand All @@ -30,6 +31,7 @@ func NewNamespace(ns storage.Namespace) Namespace {
Size: ns.Size,
Version: ns.Version,
NamespaceID: hex.EncodeToString(ns.NamespaceID),
Name: decodeName(ns.NamespaceID),
Hash: ns.Hash(),
Reserved: ns.Reserved,
PfbCount: ns.PfbCount,
Expand All @@ -41,3 +43,22 @@ func NewNamespace(ns storage.Namespace) Namespace {
func (Namespace) SearchType() string {
return "namespace"
}

func decodeName(nsId []byte) string {
isDecodable := true
data := make([]byte, 0)
for i := range nsId {
if nsId[i] == 0 {
continue
}
if nsId[i] < 0x20 || nsId[i] > 0x7f {
isDecodable = false
}
data = append(data, nsId[i])
}

if isDecodable {
return string(data)
}
return hex.EncodeToString(data)
}
42 changes: 42 additions & 0 deletions cmd/api/handler/responses/namespace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: 2023 PK Lab AG <[email protected]>
// SPDX-License-Identifier: MIT

package responses

import (
"encoding/hex"
"testing"

"github.com/stretchr/testify/require"
)

func Test_decodeName(t *testing.T) {
tests := []struct {
name string
nsId string
want string
}{
{
name: "test 1",
nsId: "6d656d6573",
want: "memes",
}, {
name: "test 2",
nsId: "0000000000000000000000000000006d656d6573",
want: "memes",
}, {
name: "test 3",
nsId: "0000000000000000000000000000000000000000e6edd3ffbef8c7d8",
want: "e6edd3ffbef8c7d8",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
decoded, err := hex.DecodeString(tt.nsId)
require.NoError(t, err)

got := decodeName(decoded)
require.Equal(t, tt.want, got)
})
}
}

0 comments on commit a38397a

Please sign in to comment.