package freelist

import (
	
	

	
)

type array struct {
	*shared

	ids []common.Pgid // all free and available free page ids.
}

func ( *array) ( common.Pgids) {
	.ids = 
	.reindex()
}

func ( *array) ( common.Txid,  int) common.Pgid {
	if len(.ids) == 0 {
		return 0
	}

	var ,  common.Pgid
	for ,  := range .ids {
		if  <= 1 {
			panic(fmt.Sprintf("invalid page allocation: %d", ))
		}

		// Reset initial page if this is not contiguous.
		if  == 0 || - != 1 {
			 = 
		}

		// If we found a contiguous block then remove it and return it.
		if (-)+1 == common.Pgid() {
			// If we're allocating off the beginning then take the fast path
			// and just adjust the existing slice. This will use extra memory
			// temporarily but the append() in free() will realloc the slice
			// as is necessary.
			if ( + 1) ==  {
				.ids = .ids[+1:]
			} else {
				copy(.ids[-+1:], .ids[+1:])
				.ids = .ids[:len(.ids)-]
			}

			// Remove from the free cache.
			for  := common.Pgid(0);  < common.Pgid(); ++ {
				delete(.cache, +)
			}
			.allocs[] = 
			return 
		}

		 = 
	}
	return 0
}

func ( *array) () int {
	return len(.ids)
}

func ( *array) () common.Pgids {
	return .ids
}

func ( *array) ( common.Pgids) {
	sort.Sort()
	common.Verify(func() {
		 := make(map[common.Pgid]struct{})
		for ,  := range .ids {
			// The existing f.ids shouldn't have duplicated free ID.
			if ,  := [];  {
				panic(fmt.Sprintf("detected duplicated free page ID: %d in existing f.ids: %v", , .ids))
			}
			[] = struct{}{}
		}

		 := common.Pgid(0)
		for ,  := range  {
			// The ids shouldn't have duplicated free ID. Note page 0 and 1
			// are reserved for meta pages, so they can never be free page IDs.
			if  ==  {
				panic(fmt.Sprintf("detected duplicated free ID: %d in ids: %v", , ))
			}
			 = 

			// The ids shouldn't have any overlap with the existing f.ids.
			if ,  := [];  {
				panic(fmt.Sprintf("detected overlapped free page ID: %d between ids: %v and existing f.ids: %v", , , .ids))
			}
		}
	})
	.ids = common.Pgids(.ids).Merge()
}

func () Interface {
	 := &array{
		shared: newShared(),
		ids:    []common.Pgid{},
	}
	.Interface = 
	return 
}