github.com/chrislusf/greenpack@v3.7.1-0.20170911073826-ad5bd10b7c47+incompatible/msgp/file_test.go (about) 1 // +build linux darwin dragonfly freebsd netbsd openbsd 2 3 package msgp_test 4 5 import ( 6 "bytes" 7 "crypto/rand" 8 "github.com/glycerine/greenpack/msgp" 9 prand "math/rand" 10 "os" 11 "testing" 12 ) 13 14 type rawBytes []byte 15 16 func (r rawBytes) MarshalMsg(b []byte) ([]byte, error) { 17 return msgp.AppendBytes(b, []byte(r)), nil 18 } 19 20 func (r rawBytes) Msgsize() int { 21 return msgp.BytesPrefixSize + len(r) 22 } 23 24 func (r *rawBytes) UnmarshalMsg(b []byte) ([]byte, error) { 25 var nbs *msgp.NilBitsStack 26 tmp, out, err := nbs.ReadBytesBytes(b, (*(*[]byte)(r))[:0]) 27 *r = rawBytes(tmp) 28 return out, err 29 } 30 31 func TestReadWriteFile(t *testing.T) { 32 t.Parallel() 33 34 f, err := os.Create("tmpfile") 35 if err != nil { 36 t.Fatal(err) 37 } 38 defer func() { 39 f.Close() 40 os.Remove("tmpfile") 41 }() 42 43 data := make([]byte, 1024*1024) 44 rand.Read(data) 45 46 err = msgp.WriteFile(rawBytes(data), f) 47 if err != nil { 48 t.Fatal(err) 49 } 50 51 var out rawBytes 52 f.Seek(0, os.SEEK_SET) 53 err = msgp.ReadFile(&out, f) 54 if err != nil { 55 t.Fatal(err) 56 } 57 58 if !bytes.Equal([]byte(out), []byte(data)) { 59 t.Fatal("Input and output not equal.") 60 } 61 } 62 63 var blobstrings = []string{"", "a string", "a longer string here!"} 64 var blobfloats = []float64{0.0, -1.0, 1.0, 3.1415926535} 65 var blobints = []int64{0, 1, -1, 80000, 1 << 30} 66 var blobbytes = [][]byte{[]byte{}, []byte("hello"), []byte("{\"is_json\":true,\"is_compact\":\"unable to determine\"}")} 67 68 func BenchmarkWriteReadFile(b *testing.B) { 69 70 // let's not run out of disk space... 71 if b.N > 10000000 { 72 b.N = 10000000 73 } 74 75 fname := "bench-tmpfile" 76 f, err := os.Create(fname) 77 if err != nil { 78 b.Fatal(err) 79 } 80 defer func(f *os.File, name string) { 81 f.Close() 82 os.Remove(name) 83 }(f, fname) 84 85 data := make(Blobs, b.N) 86 87 for i := range data { 88 data[i].Name = blobstrings[prand.Intn(len(blobstrings))] 89 data[i].Float = blobfloats[prand.Intn(len(blobfloats))] 90 data[i].Amount = blobints[prand.Intn(len(blobints))] 91 data[i].Bytes = blobbytes[prand.Intn(len(blobbytes))] 92 } 93 94 b.SetBytes(int64(data.Msgsize() / b.N)) 95 b.ResetTimer() 96 err = msgp.WriteFile(data, f) 97 if err != nil { 98 b.Fatal(err) 99 } 100 err = msgp.ReadFile(&data, f) 101 if err != nil { 102 b.Fatal(err) 103 } 104 }