package quic

import (
	
	
	
	
	

	
	
	
	
)

const defaultUrgency = 3

func encodeStreamPriority( int8,  bool,  uint32) uint64 {
	 := uint64(uint8()) | uint64()<<32
	if  {
		 |= 1 << 8
	}
	return 
}

func decodeStreamPriority( uint64) ( int8,  bool,  uint32) {
	return int8(), uint8(>>8) != 0, uint32( >> 32)
}

// A SendStream is a unidirectional Send Stream.
type SendStream struct {
	mutex sync.Mutex

	numOutstandingFrames int64 // outstanding STREAM and RESET_STREAM frames
	retransmissionQueue  []*wire.StreamFrame

	ctx       context.Context
	ctxCancel context.CancelCauseFunc

	streamID protocol.StreamID
	sender   streamSender

	// reliableSize is the portion of the stream that needs to be transmitted reliably,
	// even if the stream is cancelled.
	// This requires the peer to support RESET_STREAM_AT.
	// This value should not be accessed directly, but only through the reliableOffset method.
	// This method returns 0 if the peer doesn't support the RESET_STREAM_AT extension.
	reliableSize protocol.ByteCount
	writeOffset  protocol.ByteCount

	shutdownErr            error
	resetErr               *StreamError
	queuedResetStreamFrame *wire.ResetStreamFrame

	dataForWriting []byte // during a Write() call, this slice is the part of p that still needs to be sent out

	writeLimiter func(int) int
	// Set by the packetizer when writeLimiter reduces the allowed byte count. It makes the blocked
	// WriteWithLimit return ErrWriteLimitReached and prevents another dequeue before it wakes up.
	writeLimited bool

	nextFrame *wire.StreamFrame
	// set if flow control credit for nextFrame was already consumed
	nextFrameReserved bool

	// writeBuffer holds data accepted by the buffered write path, waiting to
	// be packetized. writeBufferHead is the offset of the first unsent byte.
	// See send_stream_buffer.go for the ordering rules.
	writeBuffer      []byte
	writeBufferHead  int
	writeBufferLimit int
	// active is set while the sender has been told this stream has data and
	// has not yet drained it. It lets the buffered write path skip a redundant
	// onHasStreamData for every write in a burst.
	active bool
	// Burst activation state. See send_stream_burst.go: a stream drained in
	// the middle of a burst corks the next write briefly so the writes behind
	// it can fill a packet.
	writesInEpisode uint16
	burstUntil      monotime.Time
	corkPending     bool
	activationTimer *time.Timer
	activationGen   uint64

	supportsResetStreamAt bool
	finishedWriting       bool // set once Close() is called
	finSent               bool // set when a STREAM_FRAME with FIN bit has been sent
	// Set when the application knows about the cancellation.
	// This can happen because the application called CancelWrite,
	// or because Write returned the error (for remote cancellations).
	cancellationFlagged bool
	completed           bool // set when this stream no longer needs to be scheduled

	priorityValue atomic.Uint64

	writeChan chan struct{}
	writeOnce chan struct{}
	deadline  monotime.Time

	flowController *streamFlowController
}

var (
	_ streamControlFrameGetter = &SendStream{}
	_ outgoingStream           = &SendStream{}
	_ sendStreamFrameHandler   = &SendStream{}
)

func newSendStream(
	 context.Context,
	 protocol.StreamID,
	 streamSender,
	 *streamFlowController,
	 bool,
) *SendStream {
	 := &SendStream{
		streamID:              ,
		sender:                ,
		flowController:        ,
		writeChan:             make(chan struct{}, 1),
		writeOnce:             make(chan struct{}, 1), // cap: 1, to protect against concurrent use of Write
		supportsResetStreamAt: ,
	}
	.priorityValue.Store(encodeStreamPriority(defaultUrgency, true, 0))
	.ctx, .ctxCancel = context.WithCancelCause()
	return 
}

// StreamID returns the stream ID.
func ( *SendStream) () StreamID {
	return .streamID // same for receiveStream and sendStream
}

// Write writes data to the stream.
// Write can be made to time out using [SendStream.SetWriteDeadline].
// If the stream was canceled, the error is a [StreamError].
func ( *SendStream) ( []byte) (int, error) {
	return .WriteWithLimit(, nil)
}

// WriteWithLimit writes data to the stream, subject to an additional send limit.
// During packetization, limiter receives the bytes allowed for the next STREAM frame after
// QUIC flow control and returns how many may be sent. Returning n in [0, maxBytes] commits
// n bytes of limiter credit; the limiter is not called again when those bytes are retransmitted.
// Values outside [0, maxBytes] are clamped.
// A short result returns the accepted prefix and [ErrWriteLimitReached]; the caller can wait
// for external credit and retry the suffix. QUIC blocking behaves like [SendStream.Write].
// limiter can run multiple times on another goroutine while QUIC send flow-control accounting
// is locked. It must be concurrency-safe and must not block or call QUIC methods.
// A nil limiter behaves like [SendStream.Write].
func ( *SendStream) ( []byte,  func( int) int) (int, error) {
	if .writeFast(, ) {
		return len(), nil
	}

	// Concurrent use of Write is not permitted (and doesn't make any sense),
	// but sometimes people do it anyway.
	// Make sure that we only execute one call at any given time to avoid hard to debug failures.
	.writeOnce <- struct{}{}
	defer func() { <-.writeOnce }()

	, ,  := .write(, )
	if  {
		.sender.onStreamCompleted(.streamID)
	}
	return , 
}

// writeFast handles the steady state of a stream being written in pieces small
// enough to buffer: copy under the mutex and return. It reports whether it took
// the write.
//
// go-iroh addition. WriteWithLimit signals writeOnce and defers a receive on it
// before it takes the mutex it needs anyway, so every write pays a channel round
// trip on top of the lock. That is a fixed cost per call, charged in inverse
// proportion to how much each call writes: invisible at 8 KiB, a large share of
// the budget at 32 bytes.
//
// The conditions are what makes skipping writeOnce safe. A nil dataForWriting
// means no blocking write is parked with older bytes queued, which is the case
// that matters: the drain order is nextFrame, write buffer, dataForWriting, so
// buffering newer bytes ahead of a blocked write's older ones would hand two
// ranges the same offset. active means the sender has already been told about
// this stream, so taking the write here cannot swallow a wakeup: active is
// cleared only by endEpisodeLocked, under the mutex held here, so a write can
// never land on a stream the sender has just dropped. Anything else, a deadline
// or a limiter or a shutdown or a full buffer, falls through to the general path
// unchanged.
//
// The dataForWriting check carries a second job. A WriteWithLimit call installs
// writeLimiter for the length of its write, and bytes taken here would be
// packetized under that limiter without ever having been offered to it. Nothing
// tests writeLimiter in this function, and nothing needs to: a write holding a
// limiter also holds dataForWriting, so the check above already refuses. It has
// to be that check and not the active one -- a stream with a limited write
// parked on it is still active, so !s.active refuses nothing here.
//
// One property is deliberately given up. writeOnce also catches concurrent Write
// calls, which are not permitted, and TryWriteAll probes it without blocking for
// the same reason; a write taken here is invisible to both. Concurrent writers
// cannot corrupt the buffer, since every append holds the mutex, but the misuse
// is no longer reported. TryWriteAll's ordering does not rest on that probe:
// tryWriteAll refuses outright while the buffer holds data, so a write taken
// here can only make it refuse, never make it queue bytes out of order.
func ( *SendStream) ( []byte,  func( int) int) bool {
	if  != nil || len() == 0 || len() > maxBufferedWriteSize {
		return false
	}
	.mutex.Lock()
	if !.active || .dataForWriting != nil || .writeLimited ||
		.resetErr != nil || .shutdownErr != nil || .finishedWriting ||
		!.deadline.IsZero() || !.growWriteBufferFor(len()) {
		.mutex.Unlock()
		return false
	}
	.appendWriteBuffer()
	.noteBufferedWriteLocked()
	.mutex.Unlock()
	return true
}

// TryWriteAll writes data to the stream if it can be queued immediately.
// It doesn't block for flow control credit and doesn't respect the write deadline.
// If the entire slice can't be queued immediately, it queues nothing and returns [ErrWouldBlock].
func ( *SendStream) ( []byte) error {
	select {
	case .writeOnce <- struct{}{}:
		defer func() { <-.writeOnce }()
	default:
		return ErrWouldBlock
	}

	, ,  := .tryWriteAll()
	if  {
		.sender.onStreamCompleted(.streamID)
	}
	if  {
		.sender.onHasStreamData(.streamID, )
	}
	return 
}

func ( *SendStream) ( []byte) (bool /* is newly completed */, bool /* has data */, error) {
	// This might wait briefly while a packet is dequeuing stream data.
	.mutex.Lock()
	defer .mutex.Unlock()

	if .resetErr != nil {
		.cancellationFlagged = true
		return .isNewlyCompleted(), false, .resetErr
	}
	if .shutdownErr != nil {
		return false, false, .shutdownErr
	}
	if .finishedWriting {
		return false, false, fmt.Errorf("write on closed stream %d", .streamID)
	}
	if len() == 0 {
		return false, false, nil
	}
	// nextFrame is drained before the write buffer, so extending it while the
	// buffer holds data would send bytes queued here at a lower offset than
	// bytes an earlier Write already buffered. Refuse instead: queueing
	// nothing is what TryWriteAll promises when it cannot take the whole
	// slice, and canBufferStreamFrame refuses on the same condition. The
	// check precedes the flow control reservation so a refusal costs no
	// credit.
	if .bufferedWriteLen() > 0 {
		return false, false, ErrWouldBlock
	}

	 := protocol.ByteCount(len())
	if .nextFrame != nil && !.nextFrameReserved {
		 += .nextFrame.DataLen()
	}
	if !.flowController.TryAddBytesSent() {
		return false, false, ErrWouldBlock
	}

	if .nextFrame == nil {
		.nextFrame = wire.GetStreamFrame()
		.nextFrame.Offset = .writeOffset
		.nextFrame.StreamID = .streamID
		.nextFrame.DataLenPresent = true
		.nextFrame.Data = .nextFrame.Data[:0]
	}
	 := len(.nextFrame.Data)
	if +len() > cap(.nextFrame.Data) {
		// Pooled STREAM frames must keep their packet-sized buffer.
		// Use a non-pooled frame when the queued data grows beyond that.
		 := &wire.StreamFrame{
			StreamID:       .streamID,
			Offset:         .nextFrame.Offset,
			DataLenPresent: true,
			Data:           make([]byte, +len()),
		}
		copy(.Data, .nextFrame.Data)
		.nextFrame.PutBack()
		.nextFrame = 
	} else {
		.nextFrame.Data = .nextFrame.Data[:+len()]
	}
	copy(.nextFrame.Data[:], )
	.nextFrameReserved = true
	return false, true, nil
}

func ( *SendStream) ( []byte,  func(int) int) (bool /* is newly completed */, int, error) {
	.mutex.Lock()
	.writeLimiter = 
	.writeLimited = false
	defer func() {
		.writeLimiter = nil
		.writeLimited = false
		.mutex.Unlock()
	}()

	if .resetErr != nil {
		.cancellationFlagged = true
		return .isNewlyCompleted(), 0, .resetErr
	}
	if .shutdownErr != nil {
		return false, 0, .shutdownErr
	}
	if .finishedWriting {
		return false, 0, fmt.Errorf("write on closed stream %d", .streamID)
	}
	if !.deadline.IsZero() && !monotime.Now().Before(.deadline) {
		return false, 0, errDeadline
	}
	if len() == 0 {
		return false, 0, nil
	}

	// Buffered fast path: copy small writes into stream-owned storage and
	// return, instead of waiting for them to be packetized. This path runs under
	// writeOnce, so no other slow-path write is in flight and the buffered bytes
	// are the newest data on the stream. writeFast reaches the same state without
	// writeOnce; see its comment for why that is safe.
	if  == nil && .deadline.IsZero() && len() <= maxBufferedWriteSize && .growWriteBufferFor(len()) {
		.appendWriteBuffer()
		.noteBufferedWriteLocked()
		if .active {
			return false, len(), nil
		}
		if !.activateOrDelayLocked() {
			return false, len(), nil
		}
		.mutex.Unlock()
		.sender.onHasStreamData(.streamID, ) // must be called without holding the mutex
		.mutex.Lock()
		return false, len(), nil
	}

	.dataForWriting = 

	var (
		  *time.Timer
		   int
		 bool
	)
	for {
		if .writeLimited {
			 = len() - len(.dataForWriting)
			.dataForWriting = nil
			break
		}
		// A shutdown or reset while this write was parked ends it, even if the
		// data would now fit somewhere: the checks below only look at capacity.
		if .shutdownErr != nil || .resetErr != nil {
			break
		}
		var  bool
		var  monotime.Time
		// Retry the write buffer: the packetizer may have made room while this
		// write was parked. Buffered bytes are all older than dataForWriting,
		// so appending keeps the stream in order.
		if  == nil && .deadline.IsZero() && len(.dataForWriting) > 0 &&
			len(.dataForWriting) <= maxBufferedWriteSize && .growWriteBufferFor(len(.dataForWriting)) {
			.appendWriteBuffer(.dataForWriting)
			.dataForWriting = nil
			 = len()
			 = true
		} else
		// As soon as dataForWriting becomes smaller than a certain size x, we copy all the data to a STREAM frame (s.nextFrame),
		// which can then be popped the next time we assemble a packet.
		// This allows us to return Write() when all data but x bytes have been sent out.
		// When the user now calls Close(), this is much more likely to happen before we popped that last STREAM frame,
		// allowing us to set the FIN bit on that frame (instead of sending an empty STREAM frame with FIN).
		if .canBufferStreamFrame() && len(.dataForWriting) > 0 {
			if .nextFrame == nil {
				 := wire.GetStreamFrame()
				.Offset = .writeOffset
				.StreamID = .streamID
				.DataLenPresent = true
				.Data = .Data[:len(.dataForWriting)]
				copy(.Data, .dataForWriting)
				.nextFrame = 
			} else {
				 := len(.nextFrame.Data)
				.nextFrame.Data = .nextFrame.Data[:+len(.dataForWriting)]
				copy(.nextFrame.Data[:], .dataForWriting)
			}
			.dataForWriting = nil
			 = len()
			 = true
		} else {
			 = len() - len(.dataForWriting)
			 = .deadline
			if !.IsZero() {
				if !monotime.Now().Before() {
					.dataForWriting = nil
					return false, , errDeadline
				}
				if  == nil {
					 = time.NewTimer(monotime.Until())
					defer .Stop()
				} else {
					.Reset(monotime.Until())
				}
			}
			if .dataForWriting == nil || .shutdownErr != nil || .resetErr != nil {
				break
			}
		}

		// A write large enough to reach here is being handed to the sender now,
		// so a cork left pending by an earlier small write is moot. Dropping it
		// here keeps active true from implying no cork is outstanding: without
		// this the timer stays armed across the drain, and because
		// activateOrDelayLocked arms only when the field is nil, the next cork
		// silently gets no timer of its own. Losing the timer costs nothing
		// once active is set, since the sender has already been told.
		.uncorkLocked()
		.active = true
		.mutex.Unlock()
		if ! {
			.sender.onHasStreamData(.streamID, ) // must be called without holding the mutex
			 = true
		}
		if  {
			.mutex.Lock()
			break
		}
		if .IsZero() {
			<-.writeChan
		} else {
			select {
			case <-.writeChan:
			case <-.C:
			}
		}
		.mutex.Lock()
	}

	if  == len() {
		return false, , nil
	}
	if .shutdownErr != nil {
		return false, , .shutdownErr
	}
	if .resetErr != nil {
		.cancellationFlagged = true
		return .isNewlyCompleted(), , .resetErr
	}
	if .writeLimited {
		return false, , ErrWriteLimitReached
	}
	return false, , nil
}

func ( *SendStream) () bool {
	if .writeLimiter != nil || .nextFrameReserved {
		return false
	}
	// Appending to nextFrame while the write buffer holds data would place
	// newer bytes ahead of older ones: nextFrame is drained first.
	if .bufferedWriteLen() > 0 {
		return false
	}
	var  protocol.ByteCount
	if .nextFrame != nil {
		 = .nextFrame.DataLen()
	}
	return +protocol.ByteCount(len(.dataForWriting)) <= protocol.MaxPacketBufferSize
}

// popStreamFrame returns the next STREAM frame that is supposed to be sent on this stream
// maxBytes is the maximum length this frame (including frame header) will have.
// hasMoreData says if more data can be sent after this call without first
// receiving a MAX_STREAM_DATA frame.
func ( *SendStream) ( protocol.ByteCount,  protocol.Version) ( ackhandler.StreamFrame,  *wire.StreamDataBlockedFrame,  bool) {
	.mutex.Lock()
	, ,  := .popNewStreamFrameForPacket(, )
	if  != nil {
		.numOutstandingFrames++
	}
	if  != nil {
		 = false
	}
	// The sender drops the stream when there is no more data, so the next
	// write has to notify it again.
	if ! {
		.endEpisodeLocked()
	}
	.mutex.Unlock()

	if  == nil {
		return ackhandler.StreamFrame{}, , 
	}
	return ackhandler.StreamFrame{
		Frame:   ,
		Handler: (*sendStreamAckHandler)(),
	}, , 
}

func ( *SendStream) ( protocol.ByteCount,  protocol.Version) ( *wire.StreamFrame,  *wire.StreamDataBlockedFrame,  bool) {
	if .shutdownErr != nil {
		return nil, nil, false
	}
	if .resetErr != nil {
		 := .reliableOffset()
		if  == 0 || .writeOffset >=  {
			return nil, nil, false
		}
	}

	if .writeLimited {
		return nil, nil, false
	}

	if len(.dataForWriting) == 0 && .nextFrame == nil && .bufferedWriteLen() == 0 {
		if .finishedWriting && !.finSent {
			.finSent = true
			return &wire.StreamFrame{
				StreamID:       .streamID,
				Offset:         .writeOffset,
				DataLenPresent: true,
				Fin:            true,
			}, nil, false
		}
		return nil, nil, false
	}

	// if the stream is canceled, only data up to the reliable size needs to be sent
	 := .reliableOffset()
	// A limiter meters the WriteWithLimit call that installed it, and the frame
	// below is built from that call's data only when nothing older is queued
	// ahead of it. Bytes still in the write buffer belong to an earlier Write,
	// so metering them would spend the limiter's credit on data it never saw,
	// and a limiter that refused would set writeLimited and strand them.
	 := .writeLimiter != nil && .nextFrame == nil && .bufferedWriteLen() == 0
	var  protocol.ByteCount
	if .nextFrameReserved {
		 = .nextFrame.DataLen()
	} else {
		 = .flowController.SendWindowSize()
	}
	if .resetErr != nil &&  > 0 {
		 = min(, -.writeOffset)
	}
	if .nextFrame != nil {
		 = min(, .nextFrame.MaxDataLen(, ), .nextFrame.DataLen())
	} else {
		 := wire.StreamFrame{
			StreamID:       .streamID,
			Offset:         .writeOffset,
			DataLenPresent: true,
		}
		 = min(, .MaxDataLen(, ), protocol.ByteCount(.bufferedWriteLen()+len(.dataForWriting)))
		// The frame is built from the write buffer alone when it holds data,
		// so flow control must not be charged for more than the buffer can
		// fill: the difference would be credit that is never sent.
		if  := protocol.ByteCount(.bufferedWriteLen());  > 0 {
			 = min(, )
		}
	}
	if  == 0 {
		return nil, nil, true
	}
	if  {
		,  := .flowController.AddBytesSentWithLimiter(, .writeLimiter)
		if  {
			.writeLimited = true
			.signalWrite()
		}
		 = 
		if  == 0 {
			return nil, nil, !
		}
	} else if !.nextFrameReserved && !.flowController.TryAddBytesSent() {
		return nil, nil, true
	}
	,  := .popNewStreamFrame()
	if .DataLen() > 0 {
		.writeOffset += .DataLen()
	}
	if .resetErr != nil && .writeOffset >=  {
		 = false
	}
	if .writeLimited {
		 = false
	}
	var  *wire.StreamDataBlockedFrame
	// Flow control for a reserved frame was consumed when it was queued. Don't
	// report the stream blocked while reserved bytes can still be sent.
	if .DataLen() > 0 && !.nextFrameReserved {
		if ,  := .flowController.isNewlyBlocked();  {
			 = &wire.StreamDataBlockedFrame{StreamID: .streamID, MaximumStreamData: }
		}
	}
	.Fin = .finishedWriting && .dataForWriting == nil && .nextFrame == nil && .bufferedWriteLen() == 0 && !.finSent
	if .Fin {
		.finSent = true
	}
	return , , 
}

// popNewStreamFrame returns a new STREAM frame to send for this stream
// hasMoreData says if there's more data to send, *not* taking into account the reliable size
func ( *SendStream) ( protocol.ByteCount) ( *wire.StreamFrame,  bool) {
	if .nextFrame != nil {
		 := .nextFrame
		 := .nextFrameReserved
		.nextFrame = nil
		.nextFrameReserved = false
		if .DataLen() >  {
			if .DataLen()- > protocol.MaxPacketBufferSize {
				.nextFrame = &wire.StreamFrame{
					Data: make([]byte, .DataLen()-),
				}
			} else {
				.nextFrame = wire.GetStreamFrame()
				.nextFrame.Data = .nextFrame.Data[:.DataLen()-]
			}
			.nextFrame.StreamID = .streamID
			.nextFrame.Offset = .writeOffset + 
			.nextFrame.DataLenPresent = true
			copy(.nextFrame.Data, .Data[:])
			.Data = .Data[:]
			.nextFrameReserved = 
		} else {
			.signalWrite()
		}
		return , .nextFrame != nil || .bufferedWriteLen() > 0 || .dataForWriting != nil
	}

	 := wire.GetStreamFrame()
	.Fin = false
	.StreamID = .streamID
	.Offset = .writeOffset
	.DataLenPresent = true
	.Data = .Data[:0]

	// Buffered data is older than dataForWriting, so it is sent first.
	if .bufferedWriteLen() > 0 {
		.Data = .Data[:min(int(), cap(.Data))]
		.Data = .Data[:.takeWriteBuffer(.Data)]
		// Draining the buffer makes room for a write blocked on it.
		.signalWrite()
		return , .bufferedWriteLen() > 0 || .dataForWriting != nil
	}

	.getDataForWriting(, )
	return , .dataForWriting != nil || .nextFrame != nil || .finishedWriting
}

func ( *SendStream) ( protocol.ByteCount,  protocol.Version) ( ackhandler.StreamFrame,  bool) {
	.mutex.Lock()
	if .shutdownErr != nil || len(.retransmissionQueue) == 0 {
		.mutex.Unlock()
		return ackhandler.StreamFrame{}, false
	}
	 := .retransmissionQueue[0]
	,  := .MaybeSplitOffFrame(, )
	if  {
		 = 
		 = true
	} else {
		.retransmissionQueue = .retransmissionQueue[1:]
		 = len(.retransmissionQueue) > 0
	}
	if  != nil {
		.numOutstandingFrames++
	}
	.mutex.Unlock()

	if  == nil {
		return ackhandler.StreamFrame{}, 
	}
	return ackhandler.StreamFrame{Frame: , Handler: (*sendStreamAckHandler)()}, 
}

func ( *SendStream) ( *wire.StreamFrame,  protocol.ByteCount) {
	if protocol.ByteCount(len(.dataForWriting)) <=  {
		.Data = .Data[:len(.dataForWriting)]
		copy(.Data, .dataForWriting)
		.dataForWriting = nil
		.signalWrite()
		return
	}
	.Data = .Data[:]
	copy(.Data, .dataForWriting)
	.dataForWriting = .dataForWriting[:]
	if .canBufferStreamFrame() {
		.signalWrite()
	}
}

func ( *SendStream) () bool {
	if .completed {
		return false
	}
	if .nextFrame != nil && .nextFrame.DataLen() > 0 {
		return false
	}
	if .bufferedWriteLen() > 0 {
		return false
	}
	// We need to keep the stream around until all frames have been sent and acknowledged.
	if .numOutstandingFrames > 0 || len(.retransmissionQueue) > 0 || .queuedResetStreamFrame != nil {
		return false
	}
	// The stream is completed if we sent the FIN.
	if .finSent {
		.completed = true
		return true
	}
	// The stream is also completed if:
	// 1. the application called CancelWrite, or
	// 2. we received a STOP_SENDING, and
	// 		* the application consumed the error via Write, or
	//		* the application called Close
	if .resetErr != nil && (.cancellationFlagged || .finishedWriting) {
		.completed = true
		return true
	}
	return false
}

// Close closes the write-direction of the stream.
// Future calls to [SendStream.Write] are not permitted after calling Close.
// It must not be called concurrently with [SendStream.Write].
// It must not be called after calling [SendStream.CancelWrite].
func ( *SendStream) () error {
	.mutex.Lock()
	if .shutdownErr != nil || .finishedWriting {
		.mutex.Unlock()
		return nil
	}
	.finishedWriting = true
	// The FIN is sent unconditionally below, so a pending cork would only
	// produce a stray wakeup after the stream is closed.
	.uncorkLocked()
	 := .resetErr != nil
	if  {
		.cancellationFlagged = true
	}
	 := .isNewlyCompleted()
	.mutex.Unlock()

	if  {
		.sender.onStreamCompleted(.streamID)
	}
	if  {
		return fmt.Errorf("close called for canceled stream %d", .streamID)
	}
	.sender.onHasStreamData(.streamID, ) // need to send the FIN, must be called without holding the mutex

	.ctxCancel(nil)
	return nil
}

// SetReliableBoundary marks the data written to this stream so far as reliable.
// It is valid to call this function multiple times, thereby increasing the reliable size.
// It only has an effect if the peer enabled support for the RESET_STREAM_AT extension,
// otherwise, it is a no-op.
func ( *SendStream) () {
	.mutex.Lock()
	defer .mutex.Unlock()

	.reliableSize = max(.reliableSize, .bufferStartOffset()+protocol.ByteCount(.bufferedWriteLen()))
}

// returnFramesToPool returns all queued frames to the sync.Pool
func ( *SendStream) () {
	.uncorkLocked()
	for ,  := range .retransmissionQueue {
		.PutBack()
	}
	clear(.retransmissionQueue)
	.retransmissionQueue = nil
	if .nextFrame != nil {
		.nextFrame.PutBack()
		.nextFrame = nil
	}
	.nextFrameReserved = false
	.dropWriteBuffer()
}

// CancelWrite aborts sending on this stream.
// Data already written, but not yet delivered to the peer is not guaranteed to be delivered reliably.
// [SendStream.Write] will unblock immediately, and future calls to it will fail.
// When called multiple times it is a no-op.
// When called after [SendStream.Close], it aborts reliable delivery of outstanding stream data.
// Note that there is no guarantee if the peer will receive the FIN or the cancellation error first.
func ( *SendStream) ( StreamErrorCode) {
	.mutex.Lock()
	if .shutdownErr != nil {
		.mutex.Unlock()
		return
	}

	.cancellationFlagged = true

	if .resetErr != nil {
		 := .isNewlyCompleted()
		.mutex.Unlock()
		// The user has called CancelWrite. If the previous cancellation was because of a
		// STOP_SENDING, we don't need to flag the error to the user anymore.
		if  {
			.sender.onStreamCompleted(.streamID)
		}
		return
	}
	.resetErr = &StreamError{StreamID: .streamID, ErrorCode: , Remote: false}
	.ctxCancel(.resetErr)

	 := .reliableOffset()
	var  bool
	 := max(.writeOffset, )
	if .nextFrameReserved && .nextFrame != nil {
		 = max(, .nextFrame.Offset+.nextFrame.DataLen())
	}
	if  == 0 {
		.numOutstandingFrames = 0
		.returnFramesToPool()
	}
	.queuedResetStreamFrame = &wire.ResetStreamFrame{
		StreamID:  .streamID,
		FinalSize: ,
		ErrorCode: ,
		// if the peer doesn't support the extension, the reliable offset will always be 0
		ReliableSize: ,
	}
	if  > 0 {
		// Buffered data beyond the reliable offset is dropped; what is below it
		// still has to be sent.
		if  := .bufferStartOffset();  >=  {
			.dropWriteBuffer()
		} else if +protocol.ByteCount(.bufferedWriteLen()) >  {
			.writeBuffer = .writeBuffer[:.writeBufferHead+int(-)]
		}
		if .nextFrame != nil {
			if .nextFrame.Offset >=  {
				.nextFrame.PutBack()
				.nextFrame = nil
				.nextFrameReserved = false
			} else if .nextFrame.Offset+.nextFrame.DataLen() >  {
				.nextFrame.Data = .nextFrame.Data[:-.nextFrame.Offset]
			}
		}
		if len(.retransmissionQueue) > 0 {
			 := make([]*wire.StreamFrame, 0, len(.retransmissionQueue))
			for ,  := range .retransmissionQueue {
				if .Offset >=  {
					.PutBack()
					continue
				}
				if .Offset+.DataLen() <=  {
					 = append(, )
				} else {
					.Data = .Data[:-.Offset]
					 = append(, )
				}
			}
			.retransmissionQueue = 
		}
		// The bytes below the boundary still have to reach the peer, so the
		// sender has to be told they are there. Nothing else will tell it: this
		// branch deliberately keeps the queued data rather than calling
		// returnFramesToPool, so it never goes through that function's uncork,
		// and a cork left pending by an earlier write has stopped being a
		// wakeup too, because activateAfterDelay bails on the resetErr set
		// just above. Uncorking is right for the same reason it is in
		// updateSendWindow: the tail delay exists to batch writes, and no
		// further write is coming.
		 = .bufferedWriteLen() > 0 || .nextFrame != nil || len(.retransmissionQueue) > 0
		if  {
			.uncorkLocked()
			.active = true
		}
	}
	.mutex.Unlock()

	.signalWrite()
	if  {
		.sender.onHasStreamData(.streamID, )
	}
	.sender.onHasStreamControlFrame(.streamID, )
}

func ( *SendStream) () {
	.mutex.Lock()
	.supportsResetStreamAt = true
	.mutex.Unlock()
}

func ( *SendStream) ( protocol.ByteCount) {
	.mutex.Lock()
	 := .flowController.UpdateSendWindow()
	if ! { // duplicate or reordered MAX_STREAM_DATA frame
		.mutex.Unlock()
		return
	}
	 := .dataForWriting != nil || .nextFrame != nil || .bufferedWriteLen() > 0
	if  {
		.uncorkLocked()
		.active = true
	}
	.mutex.Unlock()
	if  {
		.sender.onHasStreamData(.streamID, )
	}
}

// onConnectionSendWindowUpdated wakes a stream that is blocked on connection
// flow control. go-iroh addition: the connection-level window opening does not
// otherwise notify streams that already have data queued, so a stream that
// stopped writing for want of connection credit would wait for another event.
func ( *SendStream) () {
	.mutex.Lock()
	 := .dataForWriting != nil || .nextFrame != nil || .bufferedWriteLen() > 0
	if  {
		.uncorkLocked()
		.active = true
	}
	.mutex.Unlock()
	if  {
		.sender.onHasStreamData(.streamID, )
	}
}

func ( *SendStream) ( *wire.StopSendingFrame) {
	.mutex.Lock()
	if .shutdownErr != nil {
		.mutex.Unlock()
		return
	}

	// If the stream was already cancelled (either locally, or due to a previous STOP_SENDING frame),
	// there's nothing else to do.
	if .resetErr != nil && .reliableOffset() == 0 {
		.mutex.Unlock()
		return
	}
	// if the peer stopped reading from the stream, there's no need to transmit any data reliably
	.reliableSize = 0
	.numOutstandingFrames = 0
	 := .writeOffset
	if .nextFrameReserved && .nextFrame != nil {
		 = max(, .nextFrame.Offset+.nextFrame.DataLen())
	}
	.returnFramesToPool()
	if .resetErr == nil {
		.resetErr = &StreamError{StreamID: .streamID, ErrorCode: .ErrorCode, Remote: true}
		.ctxCancel(.resetErr)
	}
	.queuedResetStreamFrame = &wire.ResetStreamFrame{
		StreamID:  .streamID,
		FinalSize: ,
		ErrorCode: .resetErr.ErrorCode,
	}
	.mutex.Unlock()

	.signalWrite()
	.sender.onHasStreamControlFrame(.streamID, )
}

func ( *SendStream) (monotime.Time) ( ackhandler.Frame, ,  bool) {
	.mutex.Lock()
	defer .mutex.Unlock()

	if .queuedResetStreamFrame == nil {
		return ackhandler.Frame{}, false, false
	}
	.numOutstandingFrames++
	 := ackhandler.Frame{
		Frame:   .queuedResetStreamFrame,
		Handler: (*sendStreamResetStreamHandler)(),
	}
	.queuedResetStreamFrame = nil
	return , true, false
}

func ( *SendStream) () protocol.ByteCount {
	if !.supportsResetStreamAt {
		return 0
	}
	return .reliableSize
}

// SetPriority sets the scheduling priority for data sent on the stream.
// It uses the urgency and incremental parameters defined by [RFC 9218].
// Urgency is clipped to the range 0 through 7, with lower values taking priority.
// Within an urgency level, incremental streams are scheduled round-robin,
// while non-incremental streams are scheduled by stream ID.
//
// The default priority is urgency 3 with incremental set to true. RFC 9218
// instead defaults incremental to false.
//
// [RFC 9218]: https://www.rfc-editor.org/rfc/rfc9218.html
func ( *SendStream) ( int8,  bool) {
	 = max(0, min(, 7)) // urgency must be between 0 and 7
	.mutex.Lock()
	if .completed {
		.mutex.Unlock()
		return
	}
	, ,  := decodeStreamPriority(.priorityValue.Load())
	if  ==  &&  ==  {
		.mutex.Unlock()
		return
	}
	.priorityValue.Store(encodeStreamPriority(, , +1))
	// Keep qlogging under the lock so shutdown can't close the qlogger concurrently.
	.sender.recordStreamPriorityUpdated(.streamID, , )
	.mutex.Unlock()
	// The framer calls back into the stream while holding its lock.
	.sender.updateStreamPriority(.streamID)
}

// The Context is canceled as soon as the write-side of the stream is closed.
// This happens when [SendStream.Close] or [SendStream.CancelWrite] is called, or when the peer
// cancels the read-side of their stream.
// The cancellation cause is set to the error that caused the stream to
// close, or [context.Canceled] in case the stream is closed without error.
func ( *SendStream) () context.Context {
	return .ctx
}

// SetWriteDeadline sets the deadline for future [SendStream.Write] calls
// and any currently blocked call.
// Even if write times out, it may return n > 0, indicating that
// some data was successfully written.
// A zero value for t means [SendStream.Write] will not time out.
func ( *SendStream) ( time.Time) error {
	.mutex.Lock()
	.deadline = monotime.FromTime()
	.mutex.Unlock()
	.signalWrite()
	return nil
}

// CloseForShutdown closes a stream abruptly.
// It makes Write unblock (and return the error) immediately.
// The peer will NOT be informed about this: the stream is closed without sending a FIN or RST.
func ( *SendStream) ( error) {
	.mutex.Lock()
	.completed = true
	if .shutdownErr == nil && !.finishedWriting {
		.shutdownErr = 
		.returnFramesToPool()
	}
	.mutex.Unlock()
	.ctxCancel()
	.signalWrite()
}

// signalWrite performs a non-blocking send on the writeChan
func ( *SendStream) () {
	select {
	case .writeChan <- struct{}{}:
	default:
	}
}

func ( *SendStream) () ( int8,  bool,  uint32) {
	return decodeStreamPriority(.priorityValue.Load())
}

type sendStreamAckHandler SendStream

var _ ackhandler.FrameHandler = &sendStreamAckHandler{}

func ( *sendStreamAckHandler) ( wire.Frame) {
	 := .(*wire.StreamFrame)
	.PutBack()

	.mutex.Lock()
	if .resetErr != nil && (*SendStream)().reliableOffset() == 0 {
		.mutex.Unlock()
		return
	}
	.numOutstandingFrames--
	if .numOutstandingFrames < 0 {
		panic("numOutStandingFrames negative")
	}
	 := (*SendStream)().isNewlyCompleted()
	.mutex.Unlock()

	if  {
		.sender.onStreamCompleted(.streamID)
	}
}

func ( *sendStreamAckHandler) ( wire.Frame) {
	 := .(*wire.StreamFrame)
	.mutex.Lock()
	// If the reliable size was 0 when the stream was cancelled,
	// the number of outstanding frames was immediately set to 0, and the retransmission queue was dropped.
	if .resetErr != nil && (*SendStream)().reliableOffset() == 0 {
		// Return the frame to pool since it won't be retransmitted
		.PutBack()
		.mutex.Unlock()
		return
	}
	.numOutstandingFrames--
	if .numOutstandingFrames < 0 {
		panic("numOutStandingFrames negative")
	}

	if .resetErr != nil && (*SendStream)().reliableOffset() > 0 {
		// If the stream was reset, and this frame is beyond the reliable offset,
		// it doesn't need to be retransmitted.
		if .Offset >= (*SendStream)().reliableOffset() {
			.PutBack()
			// If this frame was the last one tracked, losing it might cause the stream to be completed.
			 := (*SendStream)().isNewlyCompleted()
			.mutex.Unlock()
			if  {
				.sender.onStreamCompleted(.streamID)
			}
			return
		}
		// If the payload of the frame extends beyond the reliable size,
		// truncate the frame to the reliable size.
		if .Offset+.DataLen() > (*SendStream)().reliableOffset() {
			.Data = .Data[:(*SendStream)().reliableOffset()-.Offset]
		}
	}

	.DataLenPresent = true
	 := len(.retransmissionQueue) == 0
	.retransmissionQueue = append(.retransmissionQueue, )
	.mutex.Unlock()

	if  {
		.sender.onHasStreamRetransmission(.streamID, (*SendStream)())
	}
}

type sendStreamResetStreamHandler SendStream

var _ ackhandler.FrameHandler = &sendStreamResetStreamHandler{}

func ( *sendStreamResetStreamHandler) ( wire.Frame) {
	 := .(*wire.ResetStreamFrame)
	.mutex.Lock()
	// If the peer sent a STOP_SENDING after we sent a RESET_STREAM_AT frame,
	// we sent 1. reduced the reliable size to 0 and 2. sent a RESET_STREAM frame.
	// In this case, we don't care about the acknowledgment of this frame.
	if .ReliableSize != (*SendStream)().reliableOffset() {
		.mutex.Unlock()
		return
	}
	.numOutstandingFrames--
	if .numOutstandingFrames < 0 {
		panic("numOutStandingFrames negative")
	}
	 := (*SendStream)().isNewlyCompleted()
	.mutex.Unlock()

	if  {
		.sender.onStreamCompleted(.streamID)
	}
}

func ( *sendStreamResetStreamHandler) ( wire.Frame) {
	 := .(*wire.ResetStreamFrame)
	.mutex.Lock()
	// If the peer sent a STOP_SENDING after we sent a RESET_STREAM_AT frame,
	// we sent 1. reduced the reliable size to 0 and 2. sent a RESET_STREAM frame.
	// In this case, the loss of the RESET_STREAM_AT frame can be ignored.
	if .ReliableSize != (*SendStream)().reliableOffset() {
		.mutex.Unlock()
		return
	}
	.queuedResetStreamFrame = 
	.numOutstandingFrames--
	.mutex.Unlock()
	.sender.onHasStreamControlFrame(.streamID, (*SendStream)())
}