package util

import (
	
	
)

type handleState struct {
	handles []any
	holes   int
}

func ( *handleState) ( context.Context,  uint32) {
	for ,  := range .handles {
		if ,  := .(io.Closer);  {
			.Close()
		}
	}
	.handles = nil
	.holes = 0
}

func ( context.Context,  Ptr_t) any {
	if  == 0 {
		return nil
	}
	 := .Value(moduleKey{}).(*moduleState)
	return .handles[^]
}

func ( context.Context,  Ptr_t) error {
	if  == 0 {
		return nil
	}
	 := .Value(moduleKey{}).(*moduleState)
	 := .handles[^]
	.handles[^] = nil
	if  := Ptr_t(len(.handles));  == ^ {
		.handles = .handles[:-1]
	} else {
		.holes++
	}
	if ,  := .(io.Closer);  {
		return .Close()
	}
	return nil
}

func ( context.Context,  any) Ptr_t {
	if  == nil {
		panic(NilErr)
	}

	 := .Value(moduleKey{}).(*moduleState)

	// Find an empty slot.
	if .holes > cap(.handles)-len(.handles) {
		for ,  := range .handles {
			if  == nil {
				.holes--
				.handles[] = 
				return ^Ptr_t()
			}
		}
	}

	// Add a new slot.
	.handles = append(.handles, )
	return -Ptr_t(len(.handles))
}