github.com/scottcagno/storage@v1.8.0/pkg/swal/seg.go (about)

     1  package swal
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  	"strconv"
     7  )
     8  
     9  func MakeFileNameFromIndex(index int64) string {
    10  	hexa := strconv.FormatInt(index, 16)
    11  	return fmt.Sprintf("%s%010s%s", FilePrefix, hexa, FileSuffix)
    12  }
    13  
    14  func GetIndexFromFileName(name string) (int64, error) {
    15  	hexa := name[len(FilePrefix) : len(name)-len(FileSuffix)]
    16  	return strconv.ParseInt(hexa, 16, 32)
    17  }
    18  
    19  // segEntry contains the metadata for a single segEntry within the file segment
    20  type segEntry struct {
    21  	index  int64 // index is the "id" of this segEntry
    22  	offset int64 // offset is the actual offset of this segEntry in the segment file
    23  }
    24  
    25  // String is the stringer method for an segEntry
    26  func (e segEntry) String() string {
    27  	return fmt.Sprintf("segEntry.index=%d, segEntry.offset=%d", e.index, e.offset)
    28  }
    29  
    30  // segment contains the metadata for the file segment
    31  type segment struct {
    32  	path      string     // path is the full path to this segment file
    33  	index     int64      // starting index of the segment
    34  	entries   []segEntry // entries is an index of the entries in the segment
    35  	remaining int64      // remaining is the bytes left after max file size minus segEntry data
    36  }
    37  
    38  // getFirstIndex returns the first index in the entries list
    39  func (s *segment) getFirstIndex() int64 {
    40  	return s.index
    41  }
    42  
    43  // getLastIndex returns the last index in the entries list
    44  func (s *segment) getLastIndex() int64 {
    45  	if len(s.entries) > 0 {
    46  		return s.entries[len(s.entries)-1].index
    47  	}
    48  	return s.index
    49  }
    50  
    51  // findEntryIndex performs binary search to find the segEntry containing provided index
    52  func (s *segment) findEntryIndex(index int64) int {
    53  	// declare for later
    54  	i, j := 0, len(s.entries)
    55  	// otherwise, perform binary search
    56  	for i < j {
    57  		h := i + (j-i)/2
    58  		if index >= s.entries[h].index {
    59  			i = h + 1
    60  		} else {
    61  			j = h
    62  		}
    63  	}
    64  	return i - 1
    65  }
    66  
    67  // String is the stringer method for a segment
    68  func (s *segment) String() string {
    69  	var ss string
    70  	ss += fmt.Sprintf("path: %q\n", filepath.Base(s.path))
    71  	ss += fmt.Sprintf("index: %d\n", s.index)
    72  	ss += fmt.Sprintf("entries: %d\n", len(s.entries))
    73  	ss += fmt.Sprintf("remaining: %d\n", s.remaining)
    74  	return ss
    75  }