package quic

import (
	

	
)

type sender interface {
	Send(p *packetBuffer, gsoSize uint16, ecn protocol.ECN)
	SendProbe(*packetBuffer, net.Addr)
	Run() error
	WouldBlock() bool
	Available() <-chan struct{}
	Close()
}

type queueEntry struct {
	buf     *packetBuffer
	gsoSize uint16
	ecn     protocol.ECN
}

type sendQueue struct {
	queue       chan queueEntry
	closeCalled chan struct{} // runStopped when Close() is called
	runStopped  chan struct{} // runStopped when the run loop returns
	available   chan struct{}
	conn        sendConn
}

var _ sender = &sendQueue{}

const sendQueueCapacity = 8

func newSendQueue( sendConn) sender {
	return &sendQueue{
		conn:        ,
		runStopped:  make(chan struct{}),
		closeCalled: make(chan struct{}),
		available:   make(chan struct{}, 1),
		queue:       make(chan queueEntry, sendQueueCapacity),
	}
}

// Send sends out a packet. It's guaranteed to not block.
// Callers need to make sure that there's actually space in the send queue by calling WouldBlock.
// Otherwise Send will panic.
func ( *sendQueue) ( *packetBuffer,  uint16,  protocol.ECN) {
	select {
	case .queue <- queueEntry{buf: , gsoSize: , ecn: }:
		// clear available channel if we've reached capacity
		if len(.queue) == sendQueueCapacity {
			select {
			case <-.available:
			default:
			}
		}
	case <-.runStopped:
	default:
		panic("sendQueue.Send would have blocked")
	}
}

func ( *sendQueue) ( *packetBuffer,  net.Addr) {
	.conn.WriteTo(.Data, )
}

func ( *sendQueue) () bool {
	return len(.queue) == sendQueueCapacity
}

func ( *sendQueue) () <-chan struct{} {
	return .available
}

func ( *sendQueue) () error {
	defer close(.runStopped)
	var  bool
	for {
		if  && len(.queue) == 0 {
			return nil
		}
		select {
		case <-.closeCalled:
			.closeCalled = nil // prevent this case from being selected again
			// make sure that all queued packets are actually sent out
			 = true
		case  := <-.queue:
			if  := .conn.Write(.buf.Data, .gsoSize, .ecn);  != nil {
				// This additional check enables:
				// 1. Checking for "datagram too large" message from the kernel, as such,
				// 2. Path MTU discovery,and
				// 3. Eventual detection of loss PingFrame.
				if !isSendMsgSizeErr() {
					return 
				}
			}
			.buf.Release()
			select {
			case .available <- struct{}{}:
			default:
			}
		}
	}
}

func ( *sendQueue) () {
	close(.closeCalled)
	// wait until the run loop returned
	<-.runStopped
}