Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[]byte から []uint64 への変換 #7

Closed
kawasin73 opened this issue Nov 8, 2018 · 1 comment
Closed

[]byte から []uint64 への変換 #7

kawasin73 opened this issue Nov 8, 2018 · 1 comment
Assignees

Comments

@kawasin73
Copy link
Owner

kawasin73 commented Nov 8, 2018

[]byte から []uint64 への変換方法を調査する

@kawasin73 kawasin73 self-assigned this Nov 8, 2018
@kawasin73
Copy link
Owner Author

一つ一つの値を変換する場合はバイト列の長さに応じて変換計算コストが必要になり、また大量のメモリコピーが発生する。

ゼロコピーでこの変換を実現するには C 言語のようなキャストが必要である。
これには、reflect パッケージと unsafe パッケージを利用する

https://stackoverflow.com/questions/11924196/convert-between-slices-of-different-types

import (
    "reflect"
    "unsafe"
)

const SIZEOF_INT32 = 4 // bytes

// Get the slice header
header := *(*reflect.SliceHeader)(unsafe.Pointer(&raw))

// The length and capacity of the slice are different.
header.Len /= SIZEOF_INT32
header.Cap /= SIZEOF_INT32

// Convert slice header to an []int32
data := *(*[]int32)(unsafe.Pointer(&header))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant