2011-12-16 14:51:26 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
2011-12-22 04:04:47 +00:00
|
|
|
"log"
|
2011-12-19 05:59:37 +00:00
|
|
|
"os"
|
2011-12-16 14:51:26 +00:00
|
|
|
)
|
|
|
|
|
2011-12-19 05:59:37 +00:00
|
|
|
type NeedleValue struct {
|
|
|
|
Offset uint32 "Volume offset" //since aligned to 8 bytes, range is 4G*8=32G
|
|
|
|
Size uint32 "Size of the data portion"
|
2011-12-16 14:51:26 +00:00
|
|
|
}
|
|
|
|
|
2011-12-19 05:59:37 +00:00
|
|
|
type NeedleMap struct {
|
2011-12-22 04:04:47 +00:00
|
|
|
indexFile *os.File
|
|
|
|
m map[uint64]*NeedleValue //mapping needle key(uint64) to NeedleValue
|
|
|
|
bytes []byte
|
2011-12-16 14:51:26 +00:00
|
|
|
}
|
2011-12-19 05:59:37 +00:00
|
|
|
|
|
|
|
func NewNeedleMap() *NeedleMap {
|
2011-12-22 04:04:47 +00:00
|
|
|
return &NeedleMap{m: make(map[uint64]*NeedleValue), bytes: make([]byte, 16)}
|
2011-12-16 14:51:26 +00:00
|
|
|
}
|
2011-12-22 04:04:47 +00:00
|
|
|
|
|
|
|
const (
|
|
|
|
RowsToRead = 1024
|
|
|
|
)
|
|
|
|
|
|
|
|
func LoadNeedleMap(file *os.File) *NeedleMap {
|
|
|
|
nm := NewNeedleMap()
|
|
|
|
nm.indexFile = file
|
|
|
|
bytes := make([]byte, 16*RowsToRead)
|
|
|
|
count, e := nm.indexFile.Read(bytes)
|
|
|
|
if count > 0 {
|
|
|
|
fstat, _ := file.Stat()
|
|
|
|
log.Println("Loading index file", fstat.Name, "size", fstat.Size)
|
|
|
|
}
|
|
|
|
for count > 0 && e == nil {
|
|
|
|
for i := 0; i < count; i += 16 {
|
|
|
|
key := BytesToUint64(bytes[i : i+8])
|
|
|
|
offset := BytesToUint32(bytes[i+8 : i+12])
|
|
|
|
size := BytesToUint32(bytes[i+12 : i+16])
|
|
|
|
nm.m[key] = &NeedleValue{Offset: offset, Size: size}
|
|
|
|
}
|
|
|
|
count, e = nm.indexFile.Read(bytes)
|
|
|
|
}
|
|
|
|
return nm
|
2011-12-19 05:59:37 +00:00
|
|
|
}
|
2011-12-20 02:34:53 +00:00
|
|
|
func (nm *NeedleMap) put(key uint64, offset uint32, size uint32) {
|
2011-12-22 04:04:47 +00:00
|
|
|
nm.m[key] = &NeedleValue{Offset: offset, Size: size}
|
|
|
|
Uint64toBytes(nm.bytes[0:8], key)
|
|
|
|
Uint32toBytes(nm.bytes[8:12], offset)
|
|
|
|
Uint32toBytes(nm.bytes[12:16], size)
|
|
|
|
nm.indexFile.Write(nm.bytes)
|
2011-12-19 05:59:37 +00:00
|
|
|
}
|
2011-12-20 02:34:53 +00:00
|
|
|
func (nm *NeedleMap) get(key uint64) (element *NeedleValue, ok bool) {
|
2011-12-22 04:04:47 +00:00
|
|
|
element, ok = nm.m[key]
|
2011-12-19 05:59:37 +00:00
|
|
|
return
|
2011-12-16 14:51:26 +00:00
|
|
|
}
|
2011-12-22 04:04:47 +00:00
|
|
|
func (nm *NeedleMap) Close() {
|
|
|
|
nm.indexFile.Close()
|
|
|
|
}
|