package nettool

import (
	"net"
	"sync"
)

var (
	_ net.Listener = (*OnceCloseListener)(nil)
)

// OnceCloseListener wraps a net.Listener, protecting it from
// multiple Close calls.
type OnceCloseListener struct {
	net.Listener
	mu     sync.Mutex
	closed bool
}

func (oc *OnceCloseListener) Close() error {
	oc.mu.Lock()
	defer oc.mu.Unlock()
	if oc.closed {
		return nil
	}
	oc.closed = true
	return oc.Listener.Close() // only close and return an error once
}
