package common

import (
	
	
	
	

	
)

type Meta struct {
	magic    uint32
	version  uint32
	pageSize uint32
	flags    uint32
	root     InBucket
	freelist Pgid
	pgid     Pgid
	txid     Txid
	checksum uint64
}

// Validate checks the marker bytes and version of the meta page to ensure it matches this binary.
func ( *Meta) () error {
	if .magic != Magic {
		return errors.ErrInvalid
	} else if .version != Version {
		return errors.ErrVersionMismatch
	} else if .checksum != .Sum64() {
		return errors.ErrChecksum
	}
	return nil
}

// Copy copies one meta object to another.
func ( *Meta) ( *Meta) {
	* = *
}

// Write writes the meta onto a page.
func ( *Meta) ( *Page) {
	if .root.root >= .pgid {
		panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", .root.root, .pgid))
	} else if .freelist >= .pgid && .freelist != PgidNoFreelist {
		// TODO: reject pgidNoFreeList if !NoFreelistSync
		panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", .freelist, .pgid))
	}

	// Page id is either going to be 0 or 1 which we can determine by the transaction ID.
	.id = Pgid(.txid % 2)
	.SetFlags(MetaPageFlag)

	// Calculate the checksum.
	.checksum = .Sum64()

	.Copy(.Meta())
}

// Sum64 generates the checksum for the meta.
func ( *Meta) () uint64 {
	var  = fnv.New64a()
	_, _ = .Write((*[unsafe.Offsetof(Meta{}.checksum)]byte)(unsafe.Pointer())[:])
	return .Sum64()
}

func ( *Meta) () uint32 {
	return .magic
}

func ( *Meta) ( uint32) {
	.magic = 
}

func ( *Meta) () uint32 {
	return .version
}

func ( *Meta) ( uint32) {
	.version = 
}

func ( *Meta) () uint32 {
	return .pageSize
}

func ( *Meta) ( uint32) {
	.pageSize = 
}

func ( *Meta) () uint32 {
	return .flags
}

func ( *Meta) ( uint32) {
	.flags = 
}

func ( *Meta) ( InBucket) {
	.root = 
}

func ( *Meta) () *InBucket {
	return &.root
}

func ( *Meta) () Pgid {
	return .freelist
}

func ( *Meta) ( Pgid) {
	.freelist = 
}

func ( *Meta) () bool {
	return .freelist != PgidNoFreelist
}

func ( *Meta) () Pgid {
	return .pgid
}

func ( *Meta) ( Pgid) {
	.pgid = 
}

func ( *Meta) () Txid {
	return .txid
}

func ( *Meta) ( Txid) {
	.txid = 
}

func ( *Meta) () {
	.txid += 1
}

func ( *Meta) () {
	.txid -= 1
}

func ( *Meta) () uint64 {
	return .checksum
}

func ( *Meta) ( uint64) {
	.checksum = 
}

func ( *Meta) ( io.Writer) {
	fmt.Fprintf(, "Version:    %d\n", .version)
	fmt.Fprintf(, "Page Size:  %d bytes\n", .pageSize)
	fmt.Fprintf(, "Flags:      %08x\n", .flags)
	fmt.Fprintf(, "Root:       <pgid=%d>\n", .root.root)
	fmt.Fprintf(, "Freelist:   <pgid=%d>\n", .freelist)
	fmt.Fprintf(, "HWM:        <pgid=%d>\n", .pgid)
	fmt.Fprintf(, "Txn ID:     %d\n", .txid)
	fmt.Fprintf(, "Checksum:   %016x\n", .checksum)
	fmt.Fprintf(, "\n")
}