github.com/TeaOSLab/EdgeNode@v1.3.8/internal/iplibrary/ip_list_kv_objects.go (about)

     1  // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package iplibrary
     4  
     5  import (
     6  	"encoding/binary"
     7  	"errors"
     8  	"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
     9  	"google.golang.org/protobuf/proto"
    10  	"math"
    11  )
    12  
    13  type IPItemEncoder[T interface{ *pb.IPItem }] struct {
    14  }
    15  
    16  func NewIPItemEncoder[T interface{ *pb.IPItem }]() *IPItemEncoder[T] {
    17  	return &IPItemEncoder[T]{}
    18  }
    19  
    20  func (this *IPItemEncoder[T]) Encode(value T) ([]byte, error) {
    21  	return proto.Marshal(any(value).(*pb.IPItem))
    22  }
    23  
    24  func (this *IPItemEncoder[T]) EncodeField(value T, fieldName string) ([]byte, error) {
    25  	switch fieldName {
    26  	case "expiresAt":
    27  		var expiresAt = any(value).(*pb.IPItem).ExpiredAt
    28  		if expiresAt < 0 || expiresAt > int64(math.MaxUint32) {
    29  			expiresAt = 0
    30  		}
    31  		var b = make([]byte, 4)
    32  		binary.BigEndian.PutUint32(b, uint32(expiresAt))
    33  		return b, nil
    34  	}
    35  
    36  	return nil, errors.New("field '" + fieldName + "' not found")
    37  }
    38  
    39  func (this *IPItemEncoder[T]) Decode(valueBytes []byte) (value T, err error) {
    40  	var item = &pb.IPItem{}
    41  	err = proto.Unmarshal(valueBytes, item)
    42  	value = item
    43  	return
    44  }
    45  
    46  // EncodeKey generate key for ip item
    47  func (this *IPItemEncoder[T]) EncodeKey(item *pb.IPItem) string {
    48  	var b = make([]byte, 8)
    49  	if item.Id < 0 {
    50  		item.Id = 0
    51  	}
    52  
    53  	binary.BigEndian.PutUint64(b, uint64(item.Id))
    54  	return string(b)
    55  }