github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/bfs/meta_block.go (about)

     1  // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package bfs
     4  
     5  import (
     6  	"encoding/binary"
     7  	"errors"
     8  )
     9  
    10  type MetaAction = byte
    11  
    12  const (
    13  	MetaActionNew    MetaAction = '+'
    14  	MetaActionRemove MetaAction = '-'
    15  )
    16  
    17  func EncodeMetaBlock(action MetaAction, hash string, data []byte) ([]byte, error) {
    18  	var hl = len(hash)
    19  	if hl != HashLen {
    20  		return nil, errors.New("invalid hash length")
    21  	}
    22  
    23  	var l = 1 /** Action **/ + hl /** Hash **/ + len(data)
    24  
    25  	var b = make([]byte, 4 /** Len **/ +l)
    26  	binary.BigEndian.PutUint32(b, uint32(l))
    27  	b[4] = action
    28  	copy(b[5:], hash)
    29  	copy(b[5+hl:], data)
    30  	return b, nil
    31  }
    32  
    33  func DecodeMetaBlock(blockBytes []byte) (action MetaAction, hash string, data []byte, err error) {
    34  	var dataOffset = 4 /** Len **/ + HashLen + 1 /** Action **/
    35  	if len(blockBytes) < dataOffset {
    36  		err = errors.New("decode failed: invalid block data")
    37  		return
    38  	}
    39  
    40  	action = blockBytes[4]
    41  	hash = string(blockBytes[5 : 5+HashLen])
    42  
    43  	if action == MetaActionNew {
    44  		var rawData = blockBytes[dataOffset:]
    45  		if len(rawData) > 0 {
    46  			data = make([]byte, len(rawData))
    47  			copy(data, rawData)
    48  		}
    49  	}
    50  
    51  	return
    52  }