github.com/leslie-fei/fastcache@v0.0.0-20240520092641-b7a9eb05711f/shm/shm.go (about) 1 package shm 2 3 import ( 4 "fmt" 5 "unsafe" 6 ) 7 8 // Memory 基于操作系统共享内存实现 9 type Memory struct { 10 createIfNotExists bool // create shm if not exists 11 shmkey string // shared memory key 12 shmid uint64 // shared memory handle 13 bytes uint64 // shared memory size 14 basep uint64 // base pointer 15 } 16 17 func (m *Memory) Key() string { 18 return m.shmkey 19 } 20 21 func (m *Memory) Handle() uint64 { 22 return m.shmid 23 } 24 25 func (m *Memory) Size() uint64 { 26 return m.bytes 27 } 28 29 func (m *Memory) Ptr() unsafe.Pointer { 30 return unsafe.Pointer(uintptr(m.basep)) 31 } 32 33 func (m *Memory) PtrOffset(offset uint64) unsafe.Pointer { 34 if offset >= m.bytes { 35 panic(fmt.Errorf("offset overflow: %d > %d", offset, m.bytes)) 36 } 37 return unsafe.Pointer(uintptr(m.basep) + uintptr(offset)) 38 } 39 40 func (m *Memory) Travel(skipOffset uint64, fn func(ptr unsafe.Pointer, size uint64) uint64) { 41 for skipOffset < m.bytes { 42 if advanceBytes := fn(m.PtrOffset(skipOffset), m.bytes-skipOffset); advanceBytes > 0 { 43 skipOffset += advanceBytes 44 continue 45 } 46 break 47 } 48 }