-
Notifications
You must be signed in to change notification settings - Fork 66
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use base64 encoding for in memory maps.
Instead of using the string representation of UUIDs (37 chars) use a base64 encoded (24 chars) of the 16 bits
- Loading branch information
Showing
3 changed files
with
97 additions
and
43 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package memory | ||
|
||
import ( | ||
"encoding/base64" | ||
"fmt" | ||
|
||
"github.com/pborman/uuid" | ||
) | ||
|
||
// UUIDToBase64 recodes it into a compact string. | ||
func UUIDToBase64(uuid uuid.UUID) string { | ||
return base64.StdEncoding.EncodeToString([]byte(uuid)) | ||
} | ||
|
||
// UUIDToBase64 attempts to decode a base 64 encoded UUID. | ||
func Base64ToUUID(b64 string) (uuid.UUID, error) { | ||
bs, err := base64.StdEncoding.DecodeString(b64) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if got, want := len(bs), 16; got != want { | ||
return nil, fmt.Errorf("invalid UUID size; got %d, want %d", got, want) | ||
} | ||
return uuid.UUID(bs), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package memory | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/pborman/uuid" | ||
) | ||
|
||
func TestTwoWaySerialization(t *testing.T) { | ||
uuid1 := uuid.NewRandom() | ||
b64 := UUIDToBase64(uuid1) | ||
uuid2, err := Base64ToUUID(b64) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
if got, want := len(b64), 24; got != want { | ||
t.Fatalf("UUIDToBase64 returned an invalid size string; got %d, want %d", got, want) | ||
} | ||
if got, want := uuid2, uuid1; !uuid.Equal(got, want) { | ||
t.Fatalf("The marshal/unmarshal via base64 should have returned the same UUID; got %q, want %q", got, want) | ||
} | ||
} | ||
|
||
func TestInvalidDeserialization(t *testing.T) { | ||
if _, err := Base64ToUUID("bogus entry"); err == nil { | ||
t.Fatal("Base64ToUUID should have never returned a corrupted UUID") | ||
} | ||
} |