Skip to content

Commit

Permalink
Add binary package for base64 encoding (#137)
Browse files Browse the repository at this point in the history
  • Loading branch information
bmoylan authored and nmiyake committed Jan 10, 2019
1 parent d12f406 commit b2b3421
Show file tree
Hide file tree
Showing 2 changed files with 102 additions and 0 deletions.
45 changes: 45 additions & 0 deletions binary/binary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright (c) 2018 Palantir Technologies. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package binary

import (
"encoding/base64"
)

var b64 = base64.StdEncoding

// Binary wraps binary data and provides encoding helpers using base64.StdEncoding.
// Use this type for binary fields serialized/deserialized as base64 text.
// Type is specified as string rather than []byte so that it can be used as a map key.
// Use Bytes() to access the raw bytes.
// Values of this type are only valid when the backing string is Base64-encoded using standard encoding.
type Binary string

func New(data []byte) Binary {
return Binary(b64.EncodeToString(data))
}

func (b Binary) Bytes() ([]byte, error) {
return b64.DecodeString(string(b))
}

func (b Binary) MarshalText() (text []byte, err error) {
// Verify that data is base64-encoded
if _, err := b.Bytes(); err != nil {
return nil, err
}

return []byte(b), nil
}

func (b *Binary) UnmarshalText(data []byte) error {
// Verify that data is base64-encoded
if _, err := Binary(data).Bytes(); err != nil {
return err
}

*b = Binary(data)
return nil
}
57 changes: 57 additions & 0 deletions binary/binary_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright (c) 2018 Palantir Technologies. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package binary_test

import (
"encoding/json"
"testing"

"github.com/stretchr/testify/assert"

"github.com/palantir/pkg/binary"
)

func TestBinary_Marshal(t *testing.T) {
for _, test := range []struct {
Name string
Input []byte
Output []byte
}{
{
Name: "hello world",
Input: []byte(`hello world`),
Output: []byte(`"aGVsbG8gd29ybGQ="`),
},
} {
t.Run(test.Name, func(t *testing.T) {
out, err := json.Marshal(binary.New(test.Input))
assert.NoError(t, err)
assert.Equal(t, string(test.Output), string(out))
})
}
}

func TestBinary_Unmarshal(t *testing.T) {
for _, test := range []struct {
Name string
Input []byte
Output []byte
}{
{
Name: "hello world",
Input: []byte(`"aGVsbG8gd29ybGQ="`),
Output: []byte(`hello world`),
},
} {
t.Run(test.Name, func(t *testing.T) {
var bin binary.Binary
err := json.Unmarshal(test.Input, &bin)
assert.NoError(t, err)
bytes, err := bin.Bytes()
assert.NoError(t, err)
assert.Equal(t, string(test.Output), string(bytes))
})
}
}

0 comments on commit b2b3421

Please sign in to comment.