github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/bfs/file_header_lazy.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  	"bytes"
     7  	"encoding/json"
     8  )
     9  
    10  // LazyFileHeader load file header lazily to save memory
    11  type LazyFileHeader struct {
    12  	rawData    []byte
    13  	fileHeader *FileHeader
    14  }
    15  
    16  func NewLazyFileHeaderFromData(rawData []byte) *LazyFileHeader {
    17  	return &LazyFileHeader{
    18  		rawData: rawData,
    19  	}
    20  }
    21  
    22  func NewLazyFileHeader(fileHeader *FileHeader) *LazyFileHeader {
    23  	return &LazyFileHeader{
    24  		fileHeader: fileHeader,
    25  	}
    26  }
    27  
    28  func (this *LazyFileHeader) FileHeaderUnsafe() (*FileHeader, error) {
    29  	if this.fileHeader != nil {
    30  		return this.fileHeader, nil
    31  	}
    32  
    33  	var jsonPrefix = []byte("json:")
    34  
    35  	var header = &FileHeader{}
    36  
    37  	// json
    38  	if bytes.HasPrefix(this.rawData, jsonPrefix) {
    39  		err := json.Unmarshal(this.rawData[len(jsonPrefix):], header)
    40  		if err != nil {
    41  			return nil, err
    42  		}
    43  		return header, nil
    44  	}
    45  
    46  	decompressor, err := SharedDecompressPool.Get(bytes.NewBuffer(this.rawData))
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	defer func() {
    52  		_ = decompressor.Close()
    53  		SharedDecompressPool.Put(decompressor)
    54  	}()
    55  
    56  	err = json.NewDecoder(decompressor).Decode(header)
    57  	if err != nil {
    58  		return nil, err
    59  	}
    60  
    61  	header.IsWriting = false
    62  
    63  	this.fileHeader = header
    64  	this.rawData = nil
    65  
    66  	return header, nil
    67  }