Skip to content

Commit

Permalink
Add marshaling for Entry
Browse files Browse the repository at this point in the history
  • Loading branch information
AlCutter committed Jul 16, 2024
1 parent d2fb910 commit 7360149
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
30 changes: 29 additions & 1 deletion entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@
// Package tessera provides an implementation of a tile-based logging framework.
package tessera

import "github.com/transparency-dev/merkle/rfc6962"
import (
"encoding/binary"

"github.com/transparency-dev/merkle/rfc6962"
)

// Entry represents an entry in a log.
type Entry struct {
Expand Down Expand Up @@ -43,6 +47,30 @@ func NewEntry(data []byte, opts ...EntryOpt) Entry {
return e
}

func (e *Entry) MarshalBinary() ([]byte, error) {
buf := make([]byte, 0, len(e.data)+len(e.identity)+len(e.leafHash)+12)
buf = binary.AppendVarint(buf, int64(len(e.data)))
buf = append(buf, e.data...)
buf = binary.AppendVarint(buf, int64(len(e.identity)))
buf = append(buf, e.identity...)
buf = binary.AppendVarint(buf, int64(len(e.leafHash)))
buf = append(buf, e.leafHash...)
return buf, nil
}

func (e *Entry) UnmarshalBinary(buf []byte) error {
l, n := binary.Varint(buf)
buf = buf[n:]
e.data, buf = buf[:l], buf[l:]
l, n = binary.Varint(buf)
buf = buf[n:]
e.identity, buf = buf[:l], buf[l:]
l, n = binary.Varint(buf)
buf = buf[n:]
e.leafHash, buf = buf[:l], buf[l:]
return nil
}

// EntryOpt is the signature of options for creating new Entry instances.
type EntryOpt func(e *Entry)

Expand Down
42 changes: 42 additions & 0 deletions entry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2024 The Tessera authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tessera

import (
"reflect"
"testing"
)

func TestEntryMarshalRoundTrip(t *testing.T) {
e := &Entry{
data: []byte("this is data"),
identity: []byte("I am who I am"),
leafHash: []byte("lettuce"),
}

raw, err := e.MarshalBinary()
if err != nil {
t.Fatalf("MarshalBinary: %v", err)
}

e2 := &Entry{}
if err := e2.UnmarshalBinary(raw); err != nil {
t.Fatalf("UnmarshalBinary: %v", err)
}

if !reflect.DeepEqual(e, e2) {
t.Fatalf("got %#v, want %#v", e2, e)
}
}

0 comments on commit 7360149

Please sign in to comment.