github.com/segmentio/parquet-go@v0.0.0-20230712180008-5d42db8f0d47/encoding/test/test_go18.go (about) 1 //go:build go1.18 2 3 package test 4 5 import ( 6 "fmt" 7 "testing" 8 9 "github.com/segmentio/parquet-go/encoding" 10 ) 11 12 func EncodeInt32(t *testing.T, enc encoding.Encoding, min, max int, bitWidth uint) { 13 t.Helper() 14 encode(t, enc, min, max, 15 encoding.Encoding.EncodeInt32, 16 encoding.Encoding.DecodeInt32, 17 func(i int) int32 { 18 value := int32(i) 19 mask := int32((1 << bitWidth) - 1) 20 if (i % 2) != 0 { 21 value = -value 22 } 23 return value & mask 24 }, 25 ) 26 } 27 28 func EncodeInt64(t *testing.T, enc encoding.Encoding, min, max int, bitWidth uint) { 29 t.Helper() 30 encode(t, enc, min, max, 31 encoding.Encoding.EncodeInt64, 32 encoding.Encoding.DecodeInt64, 33 func(i int) int64 { 34 value := int64(i) 35 mask := int64((1 << bitWidth) - 1) 36 if (i % 2) != 0 { 37 value = -value 38 } 39 return value & mask 40 }, 41 ) 42 } 43 44 func EncodeFloat(t *testing.T, enc encoding.Encoding, min, max int) { 45 t.Helper() 46 encode(t, enc, min, max, 47 encoding.Encoding.EncodeFloat, 48 encoding.Encoding.DecodeFloat, 49 func(i int) float32 { return float32(i) }, 50 ) 51 } 52 53 func EncodeDouble(t *testing.T, enc encoding.Encoding, min, max int) { 54 t.Helper() 55 encode(t, enc, min, max, 56 encoding.Encoding.EncodeDouble, 57 encoding.Encoding.DecodeDouble, 58 func(i int) float64 { return float64(i) }, 59 ) 60 } 61 62 type encodingFunc[T comparable] func(encoding.Encoding, []byte, []T) ([]byte, error) 63 64 type decodingFunc[T comparable] func(encoding.Encoding, []T, []byte) ([]T, error) 65 66 func encode[T comparable](t *testing.T, enc encoding.Encoding, min, max int, encode encodingFunc[T], decode decodingFunc[T], valueOf func(int) T) { 67 t.Helper() 68 69 for k := min; k <= max; k++ { 70 t.Run(fmt.Sprintf("N=%d", k), func(t *testing.T) { 71 src := make([]T, k) 72 for i := range src { 73 src[i] = valueOf(i) 74 } 75 76 buf, err := encode(enc, nil, src) 77 if err != nil { 78 t.Fatalf("encoding %d values: %v", k, err) 79 } 80 81 res, err := decode(enc, nil, buf) 82 if err != nil { 83 t.Fatalf("decoding %d values: %v", k, err) 84 } 85 86 if err := assertEqual(src, res); err != nil { 87 t.Fatalf("testing %d values: %v", k, err) 88 } 89 }) 90 } 91 } 92 93 func assertEqual[T comparable](want, got []T) error { 94 if len(want) != len(got) { 95 return fmt.Errorf("number of values mismatch: want=%d got=%d", len(want), len(got)) 96 } 97 98 for i := range want { 99 if want[i] != got[i] { 100 return fmt.Errorf("values at index %d/%d mismatch: want=%+v got=%+v", i, len(want), want[i], got[i]) 101 } 102 } 103 104 return nil 105 }