-
Notifications
You must be signed in to change notification settings - Fork 370
/
roundtrip.go
92 lines (79 loc) · 2.17 KB
/
roundtrip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package io
import (
"bytes"
"errors"
"io"
"reflect"
)
// RoundTripCheck is a helper to check that a serialization round trip is correct.
// It writes the object to a buffer, then reads it back and checks that the reconstructed object is equal to the original.
// It supports both io.ReaderFrom and UnsafeReaderFrom interfaces (to object)
// It also supports both io.WriterTo and WriterRawTo interfaces (from object)
func RoundTripCheck(from any, to func() any) error {
var buf bytes.Buffer
reconstruct := func(written int64) error {
// if builder implements io.ReaderFrom
if r, ok := to().(io.ReaderFrom); ok {
read, err := r.ReadFrom(bytes.NewReader(buf.Bytes()))
if err != nil {
return err
}
if !reflect.DeepEqual(from, r) {
return errors.New("reconstructed object don't match original (ReadFrom)")
}
if written != read {
return errors.New("bytes written / read don't match")
}
}
// if builder implements gnarkio.UnsafeReaderFrom
if r, ok := to().(UnsafeReaderFrom); ok {
read, err := r.UnsafeReadFrom(bytes.NewReader(buf.Bytes()))
if err != nil {
return err
}
if !reflect.DeepEqual(from, r) {
return errors.New("reconstructed object don't match original (UnsafeReadFrom)")
}
if written != read {
return errors.New("bytes written / read don't match")
}
}
return nil
}
// if from implements io.WriterTo
if w, ok := from.(io.WriterTo); ok {
written, err := w.WriteTo(&buf)
if err != nil {
return err
}
if err := reconstruct(written); err != nil {
return err
}
}
buf.Reset()
// if from implements gnarkio.WriterRawTo
if w, ok := from.(WriterRawTo); ok {
written, err := w.WriteRawTo(&buf)
if err != nil {
return err
}
if err := reconstruct(written); err != nil {
return err
}
}
return nil
}
func DumpRoundTripCheck(from any, to func() any) error {
var buf bytes.Buffer
if err := from.(BinaryDumper).WriteDump(&buf); err != nil {
return err
}
r := to().(BinaryDumper)
if err := r.ReadDump(bytes.NewReader(buf.Bytes())); err != nil {
return err
}
if !reflect.DeepEqual(from, r) {
return errors.New("reconstructed object don't match original (ReadDump)")
}
return nil
}