File: file_test.go

package info (click to toggle)
golang-github-tinylib-msgp 1.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 836 kB
  • sloc: makefile: 47
file content (107 lines) | stat: -rw-r--r-- 2,322 bytes parent folder | download | duplicates (2)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//go:build linux || darwin || dragonfly || freebsd || illumos || netbsd || openbsd
// +build linux darwin dragonfly freebsd illumos netbsd openbsd

package msgp_test

import (
	"bytes"
	"crypto/rand"
	"io"
	prand "math/rand"
	"os"
	"testing"

	"github.com/tinylib/msgp/msgp"
)

type rawBytes []byte

func (r rawBytes) MarshalMsg(b []byte) ([]byte, error) {
	return msgp.AppendBytes(b, []byte(r)), nil
}

func (r rawBytes) Msgsize() int {
	return msgp.BytesPrefixSize + len(r)
}

func (r *rawBytes) UnmarshalMsg(b []byte) ([]byte, error) {
	tmp, out, err := msgp.ReadBytesBytes(b, (*(*[]byte)(r))[:0])
	*r = rawBytes(tmp)
	return out, err
}

func TestReadWriteFile(t *testing.T) {
	t.Parallel()

	f, err := os.Create("tmpfile")
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		f.Close()
		os.Remove("tmpfile")
	}()

	data := make([]byte, 1024*1024)
	rand.Read(data)

	err = msgp.WriteFile(rawBytes(data), f)
	if err != nil {
		t.Fatal(err)
	}

	var out rawBytes
	f.Seek(0, io.SeekStart)
	err = msgp.ReadFile(&out, f)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal([]byte(out), []byte(data)) {
		t.Fatal("Input and output not equal.")
	}
}

var (
	blobstrings = []string{"", "a string", "a longer string here!"}
	blobfloats  = []float64{0.0, -1.0, 1.0, 3.1415926535}
	blobints    = []int64{0, 1, -1, 80000, 1 << 30}
	blobbytes   = [][]byte{{}, []byte("hello"), []byte(`{"is_json":true,"is_compact":"unable to determine"}`)}
)

func BenchmarkWriteReadFile(b *testing.B) {
	// let's not run out of disk space...
	if b.N > 10000000 {
		b.N = 10000000 //nolint:staticcheck // ignoring "SA3001: should not assign to b.N (staticcheck)" as this should not usually happen.
	}

	fname := "bench-tmpfile"
	f, err := os.Create(fname)
	if err != nil {
		b.Fatal(err)
	}
	defer func(f *os.File, name string) {
		f.Close()
		os.Remove(name)
	}(f, fname)

	data := make(Blobs, b.N)

	for i := range data {
		data[i].Name = blobstrings[prand.Intn(len(blobstrings))]
		data[i].Float = blobfloats[prand.Intn(len(blobfloats))]
		data[i].Amount = blobints[prand.Intn(len(blobints))]
		data[i].Bytes = blobbytes[prand.Intn(len(blobbytes))]
	}

	b.SetBytes(int64(data.Msgsize() / b.N))
	b.ResetTimer()
	err = msgp.WriteFile(data, f)
	if err != nil {
		b.Fatal(err)
	}
	err = msgp.ReadFile(&data, f)
	if err != nil {
		b.Fatal(err)
	}
}