gitee.com/quant1x/num@v0.3.2/binary/memory.go (about)

     1  package binary
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"strings"
     7  	"unsafe"
     8  )
     9  
    10  type SliceHeader = reflect.SliceHeader
    11  
    12  type Memory struct {
    13  	addr *byte
    14  	data []byte
    15  	size int
    16  }
    17  
    18  func (m Memory) String() string {
    19  	sb := strings.Builder{}
    20  	bytes := m.data
    21  	for _, v := range bytes {
    22  		sb.WriteByte(' ')
    23  		sb.WriteString(fmt.Sprintf("%d", v))
    24  	}
    25  	text := sb.String()
    26  	return text[1:]
    27  }
    28  
    29  //func (m Memory) read() []byte {
    30  //	addr := uintptr(unsafe.Pointer(&m[0]))
    31  //	size := len([]byte(m))
    32  //	return *(*[]byte)(unsafe.Pointer(&SliceHeader{
    33  //		Data: addr,
    34  //		Len:  size,
    35  //		Cap:  size,
    36  //	}))
    37  //}
    38  //
    39  //func (m Memory) v1read() []byte {
    40  //	addr := uintptr(unsafe.Pointer(&m[0]))
    41  //	size := len([]byte(m))
    42  //	return *(*[]byte)(unsafe.Pointer(&SliceHeader{
    43  //		Data: addr,
    44  //		Len:  size,
    45  //		Cap:  size,
    46  //	}))
    47  //}
    48  
    49  func Mem2(data []byte) Memory {
    50  	m := Memory{
    51  		addr: &data[0],
    52  		data: data,
    53  		size: len(data),
    54  	}
    55  	return m
    56  }
    57  
    58  func MemData[E any](x E) Memory {
    59  	addr := &x
    60  	rawPtr := unsafe.Pointer(addr)
    61  	size := int(unsafe.Sizeof(x))
    62  	b0 := (*[1]byte)(rawPtr)[:]
    63  	b1 := unsafe.Slice(&(b0[0]), size)
    64  	m := Memory{
    65  		addr: &b0[0],
    66  		data: b1,
    67  		size: size,
    68  	}
    69  	return m
    70  }
    71  
    72  func (m Memory) address() *byte {
    73  	return m.addr
    74  }
    75  
    76  func (m Memory) Bytes() []byte {
    77  	return m.data
    78  }
    79  
    80  func (m Memory) Float64() float64 {
    81  	addr := m.address()
    82  	return *(*float64)(unsafe.Pointer(addr))
    83  }
    84  
    85  func (m Memory) Inf64() int64 {
    86  	addr := m.address()
    87  	return *(*int64)(unsafe.Pointer(addr))
    88  }