chenshijun
2020-03-30 0ac2a08333b72a93e3b5f0b996d3cf954555a6bd
添加shmData库,支持共享内存中使用[]byte
1个文件已添加
58 ■■■■■ 已修改文件
shmData.go 58 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
shmData.go
New file
@@ -0,0 +1,58 @@
package shmqueue
import (
    "reflect"
    "unsafe"
)
// lock free queue struct
type ShmDataInfo struct {
    Capacity uint32
    Cache    []byte
}
// shmData2Info convert []byte to *ShmDataInfo
func shmData2Info(b []byte) *ShmDataInfo {
    return (*ShmDataInfo)(unsafe.Pointer(
        (*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
    ))
}
// ConvertToSlice convert to []byte
func ptr2Slice(s unsafe.Pointer, size int) []byte {
    var x reflect.SliceHeader
    x.Len = size
    x.Cap = size
    x.Data = uintptr(s)
    return *(*[]byte)(unsafe.Pointer(&x))
}
func WriteShmData(data []byte, shmId int) error {
    shmdata,err := Attach(shmId)
    if err != nil {
        return err
    }
    sdi := shmData2Info(shmdata)
    if len(data) <= len(shmdata) {
        sdi.Capacity = uint32(len(data))
    } else {
        sdi.Capacity = uint32(len(shmdata))
    }
    tmpData := ptr2Slice(unsafe.Pointer(&sdi.Cache), int(sdi.Capacity))
    copy(tmpData, data)
    return nil
}
func ReadShmData(shmId int) ([]byte,error) {
    shmdata,err := Attach(shmId)
    if err != nil {
        return nil,err
    }
    sdi := shmData2Info(shmdata)
    tmpData := ptr2Slice(unsafe.Pointer(&sdi.Cache), int(sdi.Capacity))
    return tmpData, nil
}