bolt/meta.go

70 lines
1.5 KiB
Go
Raw Normal View History

2014-01-08 15:06:17 +00:00
package bolt
import (
"errors"
"hash/fnv"
"unsafe"
)
2014-02-04 22:30:05 +00:00
const magic uint32 = 0xED0CDAED
2014-01-10 14:32:12 +00:00
var (
// ErrInvalid is returned when a data file is not a Bolt-formatted database.
ErrInvalid = errors.New("invalid database")
// ErrVersionMismatch is returned when the data file was created with a
// different version of Bolt.
ErrVersionMismatch = errors.New("version mismatch")
// ErrChecksum is returned when either meta page checksum does not match.
ErrChecksum = errors.New("checksum error")
)
2014-01-10 14:32:12 +00:00
type meta struct {
2014-01-24 23:32:18 +00:00
magic uint32
version uint32
pageSize uint32
2014-01-31 18:18:51 +00:00
flags uint32
root bucket
2014-02-09 22:52:19 +00:00
freelist pgid
2014-01-31 18:18:51 +00:00
pgid pgid
txid txid
checksum uint64
2014-01-10 14:32:12 +00:00
}
// validate checks the marker bytes and version of the meta page to ensure it matches this binary.
func (m *meta) validate() error {
if m.checksum != 0 && m.checksum != m.sum64() {
return ErrChecksum
} else if m.magic != magic {
2014-02-16 19:18:44 +00:00
return ErrInvalid
2014-01-31 17:22:58 +00:00
} else if m.version != version {
2014-02-16 19:18:44 +00:00
return ErrVersionMismatch
2014-01-10 14:32:12 +00:00
}
return nil
}
2014-01-30 03:35:58 +00:00
// copy copies one meta object to another.
func (m *meta) copy(dest *meta) {
*dest = *m
2014-01-30 03:35:58 +00:00
}
2014-01-30 23:22:02 +00:00
// write writes the meta onto a page.
func (m *meta) write(p *page) {
2014-03-09 03:25:37 +00:00
// Page id is either going to be 0 or 1 which we can determine by the transaction ID.
p.id = pgid(m.txid % 2)
2014-02-12 21:57:27 +00:00
p.flags |= metaPageFlag
2014-01-30 23:22:02 +00:00
// Calculate the checksum.
m.checksum = m.sum64()
2014-01-30 23:22:02 +00:00
m.copy(p.meta())
}
// generates the checksum for the meta.
func (m *meta) sum64() uint64 {
var h = fnv.New64a()
_, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:])
return h.Sum64()
}