package freelist

import (
	
	
	
	

	
)

type txPending struct {
	ids              []common.Pgid
	alloctx          []common.Txid // txids allocating the ids
	lastReleaseBegin common.Txid   // beginning txid of last matching releaseRange
}

type shared struct {
	Interface

	readonlyTXIDs []common.Txid               // all readonly transaction IDs.
	allocs        map[common.Pgid]common.Txid // mapping of Txid that allocated a pgid.
	cache         map[common.Pgid]struct{}    // fast lookup of all free and pending page ids.
	pending       map[common.Txid]*txPending  // mapping of soon-to-be free page ids by tx.
}

func newShared() *shared {
	return &shared{
		pending: make(map[common.Txid]*txPending),
		allocs:  make(map[common.Pgid]common.Txid),
		cache:   make(map[common.Pgid]struct{}),
	}
}

func ( *shared) () map[common.Txid]*txPending {
	return .pending
}

func ( *shared) () int {
	var  int
	for ,  := range .pending {
		 += len(.ids)
	}
	return 
}

func ( *shared) () int {
	return .FreeCount() + .PendingCount()
}

func ( *shared) ( common.Pgid) bool {
	,  := .cache[]
	return 
}

func ( *shared) ( common.Txid,  *common.Page) {
	if .Id() <= 1 {
		panic(fmt.Sprintf("cannot free page 0 or 1: %d", .Id()))
	}

	// Free page and all its overflow pages.
	 := .pending[]
	if  == nil {
		 = &txPending{}
		.pending[] = 
	}
	,  := .allocs[.Id()]
	common.Verify(func() {
		if  ==  {
			panic(fmt.Sprintf("free: freed page (%d) was allocated by the same transaction (%d)", .Id(), ))
		}
	})
	if  {
		delete(.allocs, .Id())
	}

	for  := .Id();  <= .Id()+common.Pgid(.Overflow()); ++ {
		// Verify that page is not already free.
		if ,  := .cache[];  {
			panic(fmt.Sprintf("page %d already freed", ))
		}
		// Add to the freelist and cache.
		.ids = append(.ids, )
		.alloctx = append(.alloctx, )
		.cache[] = struct{}{}
	}
}

func ( *shared) ( common.Txid) {
	// Remove page ids from cache.
	 := .pending[]
	if  == nil {
		return
	}
	for ,  := range .ids {
		delete(.cache, )
		 := .alloctx[]
		if  == 0 {
			continue
		}
		if  !=  {
			// Pending free aborted; restore page back to alloc list.
			.allocs[] = 
		} else {
			// A writing TXN should never free a page which was allocated by itself.
			panic(fmt.Sprintf("rollback: freed page (%d) was allocated by the same transaction (%d)", , ))
		}
	}
	// Remove pages from pending list and mark as free if allocated by txid.
	delete(.pending, )

	// Remove pgids which are allocated by this txid
	for ,  := range .allocs {
		if  ==  {
			delete(.allocs, )
		}
	}
}

func ( *shared) ( common.Txid) {
	.readonlyTXIDs = append(.readonlyTXIDs, )
}

func ( *shared) ( common.Txid) {
	for  := range .readonlyTXIDs {
		if .readonlyTXIDs[] ==  {
			 := len(.readonlyTXIDs) - 1
			.readonlyTXIDs[] = .readonlyTXIDs[]
			.readonlyTXIDs = .readonlyTXIDs[:]
			break
		}
	}
}

type txIDx []common.Txid

func ( txIDx) () int           { return len() }
func ( txIDx) (,  int)      { [], [] = [], [] }
func ( txIDx) (,  int) bool { return [] < [] }

func ( *shared) () {
	// Free all pending pages prior to the earliest open transaction.
	sort.Sort(txIDx(.readonlyTXIDs))
	 := common.Txid(math.MaxUint64)
	if len(.readonlyTXIDs) > 0 {
		 = .readonlyTXIDs[0]
	}
	if  > 0 {
		.release( - 1)
	}
	// Release unused txid extents.
	for ,  := range .readonlyTXIDs {
		.releaseRange(, -1)
		 =  + 1
	}
	.releaseRange(, common.Txid(math.MaxUint64))
	// Any page both allocated and freed in an extent is safe to release.
}

func ( *shared) ( common.Txid) {
	 := make(common.Pgids, 0)
	for ,  := range .pending {
		if  <=  {
			// Move transaction's pending pages to the available freelist.
			// Don't remove from the cache since the page is still free.
			 = append(, .ids...)
			delete(.pending, )
		}
	}
	.mergeSpans()
}

func ( *shared) (,  common.Txid) {
	if  >  {
		return
	}
	 := common.Pgids{}
	for ,  := range .pending {
		if  <  ||  >  {
			continue
		}
		// Don't recompute freed pages if ranges haven't updated.
		if .lastReleaseBegin ==  {
			continue
		}
		for  := 0;  < len(.ids); ++ {
			if  := .alloctx[];  <  ||  >  {
				continue
			}
			 = append(, .ids[])
			.ids[] = .ids[len(.ids)-1]
			.ids = .ids[:len(.ids)-1]
			.alloctx[] = .alloctx[len(.alloctx)-1]
			.alloctx = .alloctx[:len(.alloctx)-1]
			--
		}
		.lastReleaseBegin = 
		if len(.ids) == 0 {
			delete(.pending, )
		}
	}
	.mergeSpans()
}

// Copyall copies a list of all free ids and all pending ids in one sorted list.
// f.count returns the minimum length required for dst.
func ( *shared) ( []common.Pgid) {
	 := make(common.Pgids, 0, .PendingCount())
	for ,  := range .pendingPageIds() {
		 = append(, .ids...)
	}
	sort.Sort()
	common.Mergepgids(, .freePageIds(), )
}

func ( *shared) ( *common.Page) {
	.Read()
	.NoSyncReload(.freePageIds())
}

func ( *shared) ( common.Pgids) {
	// Build a cache of only pending pages.
	 := make(map[common.Pgid]struct{})
	for ,  := range .pending {
		for ,  := range .ids {
			[] = struct{}{}
		}
	}

	// Check each page in the freelist and build a new available freelist
	// with any pages not in the pending lists.
	 := []common.Pgid{}
	for ,  := range  {
		if ,  := []; ! {
			 = append(, )
		}
	}

	.Init()
}

// reindex rebuilds the free cache based on available and pending free lists.
func ( *shared) () {
	 := .freePageIds()
	 := .pendingPageIds()
	.cache = make(map[common.Pgid]struct{}, len())
	for ,  := range  {
		.cache[] = struct{}{}
	}
	for ,  := range  {
		for ,  := range .ids {
			.cache[] = struct{}{}
		}
	}
}

func ( *shared) ( *common.Page) {
	if !.IsFreelistPage() {
		panic(fmt.Sprintf("invalid freelist page: %d, page type is %s", .Id(), .Typ()))
	}

	 := .FreelistPageIds()

	// Copy the list of page ids from the freelist.
	if len() == 0 {
		.Init([]common.Pgid{})
	} else {
		// copy the ids, so we don't modify on the freelist page directly
		 := make([]common.Pgid, len())
		copy(, )
		// Make sure they're sorted.
		sort.Sort(common.Pgids())

		.Init()
	}
}

func ( *shared) () int {
	 := .Count()
	if  >= 0xFFFF {
		// The first element will be used to store the count. See freelist.write.
		++
	}
	return int(common.PageHeaderSize) + (int(unsafe.Sizeof(common.Pgid(0))) * )
}

func ( *shared) ( *common.Page) {
	// Combine the old free pgids and pgids waiting on an open transaction.

	// Update the header flag.
	.SetFlags(common.FreelistPageFlag)

	// The page.count can only hold up to 64k elements so if we overflow that
	// number then we handle it by putting the size in the first element.
	 := .Count()
	if  == 0 {
		.SetCount(uint16())
	} else if  < 0xFFFF {
		.SetCount(uint16())
		 := common.UnsafeAdd(unsafe.Pointer(), unsafe.Sizeof(*))
		 := unsafe.Slice((*common.Pgid)(), )
		.Copyall()
	} else {
		.SetCount(0xFFFF)
		 := common.UnsafeAdd(unsafe.Pointer(), unsafe.Sizeof(*))
		 := unsafe.Slice((*common.Pgid)(), +1)
		[0] = common.Pgid()
		.Copyall([1:])
	}
}