-
Notifications
You must be signed in to change notification settings - Fork 0
/
mem_util.go
49 lines (42 loc) · 1.1 KB
/
mem_util.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
package kernel
import (
"reflect"
"unsafe"
)
// Memset sets size bytes at the given address to the supplied value. The implementation
// is based on bytes.Repeat; instead of using a for loop, this function uses
// log2(size) copy calls which should give us a speed boost as page addresses
// are always aligned.
func Memset(addr uintptr, value byte, size uintptr) {
if size == 0 {
return
}
// overlay a slice on top of this address region
target := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Len: int(size),
Cap: int(size),
Data: addr,
}))
// Set first element and make log2(size) optimized copies
target[0] = value
for index := uintptr(1); index < size; index *= 2 {
copy(target[index:], target[:index])
}
}
// Memcopy copies size bytes from src to dst.
func Memcopy(src, dst uintptr, size uintptr) {
if size == 0 {
return
}
srcSlice := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Len: int(size),
Cap: int(size),
Data: src,
}))
dstSlice := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Len: int(size),
Cap: int(size),
Data: dst,
}))
copy(dstSlice, srcSlice)
}