gitee.com/quant1x/gox@v1.21.2/cache/fast.go (about)

     1  package cache
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  	"unsafe"
     8  )
     9  
    10  type FastCache struct {
    11  	filename string
    12  	f        *os.File
    13  	size     int64
    14  	Data     MMap
    15  }
    16  
    17  func OpenCache(name string, size int64) (*FastCache, error) {
    18  	dir := filepath.Dir(name)
    19  	err := os.MkdirAll(dir, 0755)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	filename := name
    24  	f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644)
    25  	if nil != err {
    26  		return nil, err
    27  	}
    28  	err = f.Truncate(size)
    29  	if nil != err {
    30  		return nil, err
    31  	}
    32  	//data, err := syscall.Mmap(int(f.Fd()), 0, int(size), syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
    33  	data, err := mmap(int(size), RDWR, 0, f.Fd(), 0)
    34  	if nil != err {
    35  		return nil, err
    36  	}
    37  
    38  	return &FastCache{
    39  		filename: filename,
    40  		f:        f,
    41  		size:     size,
    42  		Data:     data,
    43  	}, nil
    44  }
    45  
    46  func (fc *FastCache) Close() {
    47  	if fc == nil {
    48  		return
    49  	}
    50  	err := fc.Data.Flush()
    51  	err = fc.Data.Unmap()
    52  	if fc.f != nil {
    53  		_ = fc.f.Close()
    54  	}
    55  	_ = err
    56  }
    57  
    58  func ToSlices2[E any](fc *FastCache) []E {
    59  	ptr := &fc.Data[0]
    60  	fmt.Printf("fc.Data addr=%p\n", fc.Data)
    61  	//unsafe.Slice(ptr, 2)
    62  	p := (*[1 << 32]E)(unsafe.Pointer(ptr))[:]
    63  	fmt.Printf("p addr=%p\n", p)
    64  	return p
    65  }
    66  
    67  func ToSlices[E any](fc *FastCache) []E {
    68  	var tmpValue E
    69  	size := int(unsafe.Sizeof(tmpValue))
    70  	num := int(fc.size) / size
    71  	ptr := &fc.Data[0]
    72  	//fmt.Printf("fc.Data addr=%p\n", fc.Data)
    73  	//unsafe.Slice(ptr, 2)
    74  	p := (*[1 << 32]E)(unsafe.Pointer(ptr))[:num:num]
    75  	//fmt.Printf("p addr=%p\n", p)
    76  	//p = slices.Grow(p, num)
    77  	return p
    78  }