package serialize

import (
	"bytes"
	"encoding/gob"
	"reflect"
	"testing"
)

func TestGobRecode(t *testing.T) {
	start := golden

	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err := enc.Encode(start)
	if err != nil {
		t.Fatalf("marshal: %v", err)
	}
	t.Logf("len: %d", buf.Len())

	dec := gob.NewDecoder(&buf)
	silver := new(talGolden)
	err = dec.Decode(silver)
	if err != nil {
		t.Fatalf("unmarshal: %v", err)
	}

	if have, want := silver, golden; !reflect.DeepEqual(have, want) {
		t.Errorf("values don't match:\n%#v\n!=\n%#v", have, want)
	}
}

func BenchmarkGobEncode(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var buf bytes.Buffer
		enc := gob.NewEncoder(&buf)
		err := enc.Encode(golden)
		if err != nil {
			b.Fatalf("marshal: %v", err)
		}
		if i == 0 {
			b.SetBytes(int64(buf.Len()))
		}
	}
}

func BenchmarkGobDecode(b *testing.B) {
	var buf bytes.Buffer
	enc := gob.NewEncoder(&buf)
	err := enc.Encode(golden)
	if err != nil {
		b.Fatalf("marshal: %v", err)
	}
	b.SetBytes(int64(buf.Len()))

	for i := 0; i < b.N; i++ {
		dec := gob.NewDecoder(bytes.NewReader(buf.Bytes()))
		var v talGolden
		err = dec.Decode(&v)
		if err != nil {
			b.Fatalf("unmarshal: %v", err)
		}
	}
}
