func (l *rlReadWriter) writePacket(b []byte) (n int, err error) {
	// Get the current max bandwidth.
	rl := l.rl
	bps := time.Duration(atomic.LoadInt64(&rl.atomicWriteBPS))

	// If bps is 0 there is no limit.
	if bps == 0 {
		return l.ReadWriter.Write(b)
	}

	rl.wmu.Lock()
	// Calculate how long we can take for our write.
	timeForWrite := time.Second / bps * time.Duration(len(b))

	// If the writeBlock is in the past we reset it to time.Now() +
	// timeForWrite. Otherwise we just add to the timestamp.
	wb := rl.writeBlock
	if rl.writeBlock.After(time.Now()) {
		rl.writeBlock = rl.writeBlock.Add(timeForWrite)
	} else {
		rl.writeBlock = time.Now().Add(timeForWrite)
	}
	rl.wmu.Unlock()

	// Sleep until it is safe to write.
	select {
	case <-time.After(time.Until(wb)):
	case <-l.ctx.Done():
		return 0, errors.New("write cancelled due to interrupt")
	}
	return l.ReadWriter.Write(b)
}
// writePacket is a helper function that writes up to a single packet worth of
// data.
writePacket is a helper function that writes up to a single packet worth of
data.
// writePacket is a helper function that writes up to a single packet worth of // data .
func (l *rlReadWriter) writePacket(b []byte) (n int, err error) {
	rl := l.rl
	bps := time.Duration(atomic.LoadInt64(&rl.atomicWriteBPS))
	if bps == 0 {
		return l.ReadWriter.Write(b)
	}
	rl.wmu.Lock()
	timeForWrite := time.Second / bps * time.Duration(len(b))
	wb := rl.writeBlock
	if rl.writeBlock.After(time.Now()) {
		rl.writeBlock = rl.writeBlock.Add(timeForWrite)
	} else {
		rl.writeBlock = time.Now().Add(timeForWrite)
	}
	rl.wmu.Unlock()
	select {
	case <-time.After(time.Until(wb)):
	case <-l.ctx.Done():
		return 0, errors.New("write cancelled due to interrupt")
	}
	return l.ReadWriter.Write(b)
}
func ( l * rlReadWriter ) writePacket ( b [ ] byte ) ( n int , err error ) { rl := l . rl bps := time . Duration ( atomic . LoadInt64 ( & rl . atomicWriteBPS ) ) if bps == 0 { return l . ReadWriter . Write ( b ) } rl . wmu . Lock ( ) timeForWrite := time . Second / bps * time . Duration ( len ( b ) ) wb := rl . writeBlock if rl . writeBlock . After ( time . Now ( ) ) { rl . writeBlock = rl . writeBlock . Add ( timeForWrite ) } else { rl . writeBlock = time . Now ( ) . Add ( timeForWrite ) } rl . wmu . Unlock ( ) select { case <- time . After ( time . Until ( wb ) ) : case <- l . ctx . Done ( ) : return 0 , errors . New ( " " ) } return l . ReadWriter . Write ( b ) }
writePacket is a helper function that writes up to a single packet worth of
data.
writePacket is a helper function that writes up to a single packet worth of data .
// Get the current max bandwidth. // If bps is 0 there is no limit. // Calculate how long we can take for our write. // If the writeBlock is in the past we reset it to time.Now() + // timeForWrite. Otherwise we just add to the timestamp. // Sleep until it is safe to write.