package door

import (
	"net"
	"os"
)

// Create a map of os.File.Fd() to *os.File
var fdmap map[uintptr]*os.File

func init() {
	fdmap = make(map[uintptr]*os.File)
}

func socket_to_fd(socket net.Conn) int {
	client_conn := socket.(*net.TCPConn)
	// This creates a duplicate fd, but once closed -- the fd gets reused!
	client_file, _ := client_conn.File()
	// Preserve the *os.File so it doesn't close
	fdmap[client_file.Fd()] = client_file
	return int(client_file.Fd())
}

// If we find the Fd in the map, close and delete it.
func close_fd(fd int) {
	var fd_uintptr uintptr = uintptr(fd)
	file, ok := fdmap[fd_uintptr]
	if ok {
		file.Close()
		delete(fdmap, fd_uintptr)
	}
}