github.com/puellanivis/breton@v0.2.16/lib/files/socketfiles/throttling.go (about)

     1  package socketfiles
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  type throttler struct {
     8  	bitrate int
     9  
    10  	delay time.Duration
    11  	next  *time.Timer
    12  }
    13  
    14  func (t *throttler) drain() {
    15  	if t.next == nil {
    16  		return
    17  	}
    18  
    19  	if !t.next.Stop() {
    20  		<-t.next.C
    21  	}
    22  }
    23  
    24  func (t *throttler) updateDelay(prescale int) {
    25  	if t.bitrate <= 0 {
    26  		t.delay = 0
    27  		t.drain()
    28  		t.next = nil
    29  		return
    30  	}
    31  
    32  	if t.next != nil {
    33  		t.drain()
    34  		t.next.Reset(0)
    35  	} else {
    36  		t.next = time.NewTimer(0)
    37  	}
    38  
    39  	// delay = nanoseconds per byte
    40  	t.delay = (8 * time.Second) / time.Duration(t.bitrate)
    41  
    42  	// recalculate to the actual expected maximum bitrate
    43  	t.bitrate = int(8 * time.Second / t.delay)
    44  
    45  	if prescale > 1 {
    46  		t.delay *= time.Duration(prescale)
    47  	}
    48  }
    49  
    50  func (t *throttler) throttle(scale int) {
    51  	if t.next == nil {
    52  		return
    53  	}
    54  
    55  	<-t.next.C
    56  
    57  	if scale > 1 {
    58  		t.next.Reset(time.Duration(scale) * t.delay)
    59  		return
    60  	}
    61  
    62  	t.next.Reset(t.delay)
    63  }
    64  
    65  func (t *throttler) setBitrate(bitrate, prescale int) int {
    66  	prev := t.bitrate
    67  
    68  	t.bitrate = bitrate
    69  	t.updateDelay(prescale)
    70  
    71  	return prev
    72  }