Skip to content

Commit f1ad831

Browse files
committed
2025-09-09 15:40:44
1 parent 46ccf5f commit f1ad831

File tree

3 files changed

+29
-5
lines changed

3 files changed

+29
-5
lines changed

daze.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1209,7 +1209,7 @@ func LoadApnic() map[string][]*net.IPNet {
12091209
log.Println("main: load apnic data from", url)
12101210
rep := doa.Try(http.Get(url))
12111211
defer rep.Body.Close()
1212-
f := io.TeeReader(rep.Body, pretty.NewProgressWriter(rep.ContentLength))
1212+
f := io.TeeReader(rep.Body, pretty.NewProgressWriter(uint64(rep.ContentLength)))
12131213
r := map[string][]*net.IPNet{}
12141214
s := bufio.NewScanner(f)
12151215
for s.Scan() {

lib/pretty/pretty.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,14 @@ func NewProgress() *Progress {
6969
// ProgressWriter is an io.Writer that updates a progress bar as data is written.
7070
type ProgressWriter struct {
7171
p *Progress
72-
m int64
73-
n int64
72+
m uint64
73+
n uint64
7474
}
7575

7676
// Write writes data to the ProgressWriter and updates the progress bar.
7777
func (p *ProgressWriter) Write(b []byte) (int, error) {
7878
l := len(b)
79-
p.m += int64(l)
79+
p.m += uint64(l)
8080
p.p.Print(float64(p.m) / float64(p.n))
8181
return l, nil
8282
}
@@ -90,7 +90,7 @@ func (p *ProgressWriter) Write(b []byte) (int, error) {
9090
// Or to display progress while writing to a writer:
9191
//
9292
// writer := io.MultiWriter(os.Stdout, NewProgressWriter(1024))
93-
func NewProgressWriter(n int64) *ProgressWriter {
93+
func NewProgressWriter(n uint64) *ProgressWriter {
9494
p := NewProgress()
9595
p.Print(0)
9696
return &ProgressWriter{

lib/rate/rate.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,27 @@ func NewLimits(r uint64, p time.Duration) *Limits {
8989
step: p / time.Duration(gcd),
9090
}
9191
}
92+
93+
// LimitsWriter is an io.Writer that applies rate limiting to write operations.
94+
//
95+
// For example, to limit a reader's read speed to 1MB/s:
96+
//
97+
// reader := io.TeeReader(os.Stdin, NewLimitsWriter(1024*1024, time.Second))
98+
//
99+
// Or, to limit a writer's write speed to 1MB/s:
100+
//
101+
// writer := io.MultiWriter(os.Stdout, NewLimitsWriter(1024*1024, time.Second))
102+
type LimitsWriter struct {
103+
li *Limits
104+
}
105+
106+
// Write writes data to the underlying writer, applying rate limiting based on the configured limits.
107+
func (l *LimitsWriter) Write(p []byte) (int, error) {
108+
l.li.Wait(uint64(len(p)))
109+
return len(p), nil
110+
}
111+
112+
// NewLimitsWriter creates a new LimitsWriter that limits write operations to r bytes per period p.
113+
func NewLimitsWriter(limits *Limits) *LimitsWriter {
114+
return &LimitsWriter{li: limits}
115+
}

0 commit comments

Comments
 (0)