//go:build linux
// +build linux

package cancelreader

import (
	
	
	
	
	

	
)

// NewReader returns a reader and a cancel function. If the input reader is a
// File, the cancel function can be used to interrupt a blocking read call.
// In this case, the cancel function returns true if the call was canceled
// successfully. If the input reader is not a File, the cancel function
// does nothing and always returns false. The Linux implementation is based on
// the epoll mechanism.
func ( io.Reader) (CancelReader, error) {
	,  := .(File)
	if ! {
		return newFallbackCancelReader()
	}

	,  := unix.EpollCreate1(0)
	if  != nil {
		return nil, fmt.Errorf("create epoll: %w", )
	}

	 := &epollCancelReader{
		file:  ,
		epoll: ,
	}

	.cancelSignalReader, .cancelSignalWriter,  = os.Pipe()
	if  != nil {
		_ = unix.Close()
		return nil, 
	}

	 = unix.EpollCtl(, unix.EPOLL_CTL_ADD, int(.Fd()), &unix.EpollEvent{
		Events: unix.EPOLLIN,
		Fd:     int32(.Fd()),
	})
	if  != nil {
		_ = unix.Close()
		return nil, fmt.Errorf("add reader to epoll interest list")
	}

	 = unix.EpollCtl(, unix.EPOLL_CTL_ADD, int(.cancelSignalReader.Fd()), &unix.EpollEvent{
		Events: unix.EPOLLIN,
		Fd:     int32(.cancelSignalReader.Fd()),
	})
	if  != nil {
		_ = unix.Close()
		return nil, fmt.Errorf("add reader to epoll interest list")
	}

	return , nil
}

type epollCancelReader struct {
	file               File
	cancelSignalReader File
	cancelSignalWriter File
	cancelMixin
	epoll int
}

func ( *epollCancelReader) ( []byte) (int, error) {
	if .isCanceled() {
		return 0, ErrCanceled
	}

	 := .wait()
	if  != nil {
		if errors.Is(, ErrCanceled) {
			// remove signal from pipe
			var  [1]byte
			,  := .cancelSignalReader.Read([:])
			if  != nil {
				return 0, fmt.Errorf("reading cancel signal: %w", )
			}
		}

		return 0, 
	}

	return .file.Read()
}

func ( *epollCancelReader) () bool {
	.setCanceled()

	// send cancel signal
	,  := .cancelSignalWriter.Write([]byte{'c'})
	return  == nil
}

func ( *epollCancelReader) () error {
	var  []string

	// close kqueue
	 := unix.Close(.epoll)
	if  != nil {
		 = append(, fmt.Sprintf("closing epoll: %v", ))
	}

	// close pipe
	 = .cancelSignalWriter.Close()
	if  != nil {
		 = append(, fmt.Sprintf("closing cancel signal writer: %v", ))
	}

	 = .cancelSignalReader.Close()
	if  != nil {
		 = append(, fmt.Sprintf("closing cancel signal reader: %v", ))
	}

	if len() > 0 {
		return fmt.Errorf(strings.Join(, ", "))
	}

	return nil
}

func ( *epollCancelReader) () error {
	 := make([]unix.EpollEvent, 1)

	for {
		,  := unix.EpollWait(.epoll, , -1)
		if errors.Is(, unix.EINTR) {
			continue // try again if the syscall was interrupted
		}

		if  != nil {
			return fmt.Errorf("kevent: %w", )
		}

		break
	}

	switch [0].Fd {
	case int32(.file.Fd()):
		return nil
	case int32(.cancelSignalReader.Fd()):
		return ErrCanceled
	}

	return fmt.Errorf("unknown error")
}