add header mgr struct

This commit is contained in:
lion 2022-06-21 10:57:47 +08:00
parent 9751227b97
commit 14badde79e
3 changed files with 45 additions and 5 deletions

View File

@ -105,3 +105,29 @@ func (v VectorIndexBlock) Encode() []byte {
func (v VectorIndexBlock) String() string {
return fmt.Sprintf("{FristPtr: %d, LastPtr: %d}", v.FirstPtr, v.LastPtr)
}
// ------------
type Header struct {
data []byte
}
func (h *Header) Version() int {
return int(binary.LittleEndian.Uint16(h.data))
}
func (h *Header) IndexPolicy() IndexPolicy {
return IndexPolicy(binary.LittleEndian.Uint16(h.data[2:]))
}
func (h *Header) CreatedAt() uint32 {
return binary.LittleEndian.Uint32(h.data[4:])
}
func (h *Header) StartIndexPtr() uint32 {
return binary.LittleEndian.Uint32(h.data[8:])
}
func (h *Header) EndIndexPtr() uint32 {
return binary.LittleEndian.Uint32(h.data[12:])
}

View File

@ -116,7 +116,7 @@ func LoadVectorIndexFromBuff(cBuff []byte) ([][]*VectorIndexBlock, error) {
}
// LoadHeader load the header info from the specified handle
func LoadHeader(handle *os.File) ([]byte, error) {
func LoadHeader(handle *os.File) (*Header, error) {
_, err := handle.Seek(0, 0)
if err != nil {
return nil, fmt.Errorf("seek to the header: %w", err)
@ -132,11 +132,13 @@ func LoadHeader(handle *os.File) ([]byte, error) {
return nil, fmt.Errorf("incomplete read: readed bytes should be %d", len(buff))
}
return buff, nil
return &Header{
data: buff,
}, nil
}
// LoadHeaderFromFile load header info from the specified db file path
func LoadHeaderFromFile(dbFile string) ([]byte, error) {
func LoadHeaderFromFile(dbFile string) (*Header, error) {
handle, err := os.OpenFile(dbFile, os.O_RDONLY, 0600)
if err != nil {
return nil, fmt.Errorf("open xdb file `%s`: %w", dbFile, err)
@ -145,6 +147,13 @@ func LoadHeaderFromFile(dbFile string) ([]byte, error) {
return LoadHeader(handle)
}
// LoadHeaderFromBuff wrap the header info from the content buffer
func LoadHeaderFromBuff(cBuff []byte) (*Header, error) {
return &Header{
data: cBuff[0:256],
}, nil
}
// LoadContent load the whole xdb content from the specified file handle
func LoadContent(handle *os.File) ([]byte, error) {
// get file size

View File

@ -11,6 +11,7 @@ package xdb
import (
"fmt"
"testing"
"time"
)
func TestLoadVectorIndex(t *testing.T) {
@ -50,11 +51,15 @@ func TestLoadVectorIndexFromBuff(t *testing.T) {
}
func TestLoadHeader(t *testing.T) {
buff, err := LoadHeaderFromFile("../../../data/ip2region.xdb")
header, err := LoadHeaderFromFile("../../../data/ip2region.xdb")
if err != nil {
fmt.Printf("failed to load xdb header info: %s\n", err)
return
}
fmt.Printf("buff length: %d\n", len(buff))
fmt.Printf("Version : %d\n", header.Version())
fmt.Printf("IndexPolicy : %s\n", header.IndexPolicy().String())
fmt.Printf("CreatedAt : %d(%s)\n", header.CreatedAt(), time.Unix(int64(header.CreatedAt()), 0).Format(time.RFC3339))
fmt.Printf("StartIndexPtr : %d\n", header.StartIndexPtr())
fmt.Printf("EndIndexPtr : %d\n", header.EndIndexPtr())
}