github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/kvstore/value_encode_int.go (about)

     1  // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package kvstore
     4  
     5  import (
     6  	"encoding/binary"
     7  	"github.com/iwind/TeaGo/types"
     8  	"golang.org/x/exp/constraints"
     9  	"strconv"
    10  )
    11  
    12  type IntValueEncoder[T constraints.Integer] struct {
    13  }
    14  
    15  func NewIntValueEncoder[T constraints.Integer]() *IntValueEncoder[T] {
    16  	return &IntValueEncoder[T]{}
    17  }
    18  
    19  func (this *IntValueEncoder[T]) Encode(value T) (data []byte, err error) {
    20  	switch v := any(value).(type) {
    21  	case int8, int16, int32, int, uint:
    22  		data = []byte(types.String(v))
    23  	case int64:
    24  		data = []byte(strconv.FormatInt(v, 16))
    25  	case uint8:
    26  		return []byte{v}, nil
    27  	case uint16:
    28  		data = make([]byte, 2)
    29  		binary.BigEndian.PutUint16(data, v)
    30  	case uint32:
    31  		data = make([]byte, 4)
    32  		binary.BigEndian.PutUint32(data, v)
    33  	case uint64:
    34  		data = make([]byte, 8)
    35  		binary.BigEndian.PutUint64(data, v)
    36  	}
    37  
    38  	return
    39  }
    40  
    41  func (this *IntValueEncoder[T]) EncodeField(value T, fieldName string) ([]byte, error) {
    42  	_ = fieldName
    43  	return this.Encode(value)
    44  }
    45  
    46  func (this *IntValueEncoder[T]) Decode(valueData []byte) (value T, err error) {
    47  	switch any(value).(type) {
    48  	case int8:
    49  		value = T(types.Int8(string(valueData)))
    50  	case int16:
    51  		value = T(types.Int16(string(valueData)))
    52  	case int32:
    53  		value = T(types.Int32(string(valueData)))
    54  	case int64:
    55  		int64Value, _ := strconv.ParseInt(string(valueData), 16, 64)
    56  		value = T(int64Value)
    57  	case int:
    58  		value = T(types.Int(string(valueData)))
    59  	case uint:
    60  		value = T(types.Uint(string(valueData)))
    61  	case uint8:
    62  		if len(valueData) == 1 {
    63  			value = T(valueData[0])
    64  		}
    65  	case uint16:
    66  		if len(valueData) == 2 {
    67  			value = T(binary.BigEndian.Uint16(valueData))
    68  		}
    69  	case uint32:
    70  		if len(valueData) == 4 {
    71  			value = T(binary.BigEndian.Uint32(valueData))
    72  		}
    73  	case uint64:
    74  		if len(valueData) == 8 {
    75  			value = T(binary.BigEndian.Uint64(valueData))
    76  		}
    77  	}
    78  
    79  	return
    80  }
    81