-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmmap_test.go
96 lines (79 loc) · 2.3 KB
/
mmap_test.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
93
94
95
96
package cgommap_test
import (
"bytes"
"cgommap"
"github.com/stretchr/testify/require"
"io"
"io/ioutil"
"log"
"os"
"testing"
)
func TestMmap(t *testing.T) {
file, err := ioutil.TempFile(os.TempDir(), "prefix")
if err != nil {
log.Fatal(err)
}
defer os.Remove(file.Name())
defer file.Close()
testText := []byte("Testing the memory mapped file")
n, err := file.Write(testText)
require.NoError(t, err)
require.Equal(t, len(testText), n)
require.NoError(t, err)
mmap, err := cgommap.New(int64(len(testText)),0, cgommap.PROT_READWRITE, cgommap.MAP_SHARED, file.Fd())
require.NoError(t, err)
defer func() {
err = mmap.Close()
require.NoError(t, err)
}()
{ // Read Test
buf := make([]byte, mmap.Size())
n, err = mmap.Read(buf[0:])
require.NoError(t, err)
require.Equal(t, len(testText), len(buf))
require.True(t, bytes.Equal(testText, buf))
buf = make([]byte, mmap.Size())
n, err = mmap.Read(buf[0:])
require.Error(t, err)
}
{ // Seek test
off, err := mmap.Seek(0, io.SeekStart)
require.NoError(t, err)
require.Equal(t, int64(0), off)
buf := make([]byte, mmap.Size())
n, err = mmap.Read(buf[0:])
require.NoError(t, err)
require.Equal(t, len(testText), len(buf))
require.True(t, bytes.Equal(testText, buf))
// Seek to middle of text
off, err = mmap.Seek(int64(len(testText)/2), io.SeekStart)
require.NoError(t, err)
require.Equal(t, int64(len(testText)/2), off)
buf = make([]byte, len(testText)/2)
n, err = mmap.Read(buf[0:])
require.NoError(t, err)
require.Equal(t, len(testText)/2, len(buf))
require.True(t, bytes.Equal(testText[len(testText)/2:], buf))
}
{ // Write Test
off, err := mmap.Seek(0, io.SeekStart)
require.NoError(t, err)
require.Equal(t, int64(0), off)
testWriteText := []byte("Writing into the darkest abyss")
n, err := mmap.Write(testWriteText)
require.NoError(t, err)
require.Equal(t, len(testWriteText), n)
off, err = mmap.Seek(0, io.SeekStart)
require.NoError(t, err)
require.Equal(t, int64(0), off)
buf := make([]byte, mmap.Size())
n, err = mmap.Read(buf[0:])
require.NoError(t, err)
require.Equal(t, len(testWriteText), len(buf))
require.True(t, bytes.Equal(testWriteText, buf))
// Try to write again while already seeked to the end of the file
_, err = mmap.Write(testWriteText)
require.Error(t, err)
}
}