github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/shm/shmi_windows.go (about)

     1  package shm
     2  
     3  import (
     4  	"github.com/angenalZZZ/gofunc/f"
     5  	"io"
     6  	"os"
     7  	"syscall"
     8  )
     9  
    10  type sharedMemory struct {
    11  	h    syscall.Handle
    12  	v    uintptr
    13  	size int32
    14  }
    15  
    16  // create shared memory. return sharedMemory object.
    17  func create(name string, size int32) (*sharedMemory, error) {
    18  	key, err := syscall.UTF16PtrFromString(name)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	h, err := syscall.CreateFileMapping(
    24  		syscall.InvalidHandle, nil,
    25  		syscall.PAGE_READWRITE, 0, uint32(size), key)
    26  	if err != nil {
    27  		return nil, os.NewSyscallError("CreateFileMapping", err)
    28  	}
    29  
    30  	v, err := syscall.MapViewOfFile(h, syscall.FILE_MAP_WRITE, 0, 0, 0)
    31  	if err != nil {
    32  		syscall.CloseHandle(h)
    33  		return nil, os.NewSyscallError("MapViewOfFile", err)
    34  	}
    35  
    36  	return &sharedMemory{h, v, size}, nil
    37  }
    38  
    39  // open shared memory. return sharedMemory object.
    40  func open(name string, size int32) (*sharedMemory, error) {
    41  	return create(name, size)
    42  }
    43  
    44  func (o *sharedMemory) close() error {
    45  	if o.v != uintptr(0) {
    46  		syscall.UnmapViewOfFile(o.v)
    47  		o.v = uintptr(0)
    48  	}
    49  	if o.h != syscall.InvalidHandle {
    50  		syscall.CloseHandle(o.h)
    51  		o.h = syscall.InvalidHandle
    52  	}
    53  	return nil
    54  }
    55  
    56  // read shared memory. return read size.
    57  func (o *sharedMemory) readAt(p []byte, off int64) (n int, err error) {
    58  	if off >= int64(o.size) {
    59  		return 0, io.EOF
    60  	}
    61  	if max := int64(o.size) - off; int64(len(p)) > max {
    62  		p = p[:max]
    63  	}
    64  	return f.BytesFromPtr(o.v, p, off, o.size), nil
    65  }
    66  
    67  // write shared memory. return write size.
    68  func (o *sharedMemory) writeAt(p []byte, off int64) (n int, err error) {
    69  	if off >= int64(o.size) {
    70  		return 0, io.EOF
    71  	}
    72  	if max := int64(o.size) - off; int64(len(p)) > max {
    73  		p = p[:max]
    74  	}
    75  	return f.BytesToPtr(p, o.v, off, o.size), nil
    76  }