diff options
| -rw-r--r-- | cmd/progress-bar/progress-bar.go | 7 | ||||
| -rw-r--r-- | progress.go | 26 |
2 files changed, 18 insertions, 15 deletions
diff --git a/cmd/progress-bar/progress-bar.go b/cmd/progress-bar/progress-bar.go index 25e6216..19050c8 100644 --- a/cmd/progress-bar/progress-bar.go +++ b/cmd/progress-bar/progress-bar.go @@ -21,13 +21,12 @@ func run() error { return errors.New("usage error") } maxStr := args[0] - maxInt, err := strconv.Atoi(maxStr) + maxVal, err := strconv.Atoi(maxStr) if err != nil { return fmt.Errorf("max: %s", err) } - maxFloat := float64(maxInt) cmd := args[1:] - bar := new(progress.Bar) + bar := progress.New(maxVal) for i := 0; ; i++ { outputBytes, err := exec.Command(cmd[0], cmd[1:]...).Output() if err != nil { @@ -39,7 +38,7 @@ func run() error { fmt.Println(err) continue } - bar.Set(float64(output) / maxFloat) + bar.Set(output) bar.Print() time.Sleep(*n) } diff --git a/progress.go b/progress.go index ddc810a..11821c1 100644 --- a/progress.go +++ b/progress.go @@ -9,9 +9,9 @@ // ) // // func main() { -// b := new(progress.Bar) +// b := progress.New(100) // for i := range 100 { -// b.Set(float64(i)/100) +// b.Set(i) // b.Print() // time.Sleep(time.Second) // } @@ -32,20 +32,24 @@ const measurements = 20 type measurement struct { t time.Time - i float64 + i int } -// Bar is a progess bar. The zero value is ready for use. +// Bar is a progess bar. type Bar struct { + max int measurements vecdeque.DQ[measurement] cols int } -// Set sets the current value to val. val must be between 0 and 1, inclusive. -func (b *Bar) Set(val float64) { - if !(0 <= val && val <= 1) { - panic(fmt.Sprintf("progress.Bar.Set: value must be between 0 and 1 (got %f)", val)) - } +func New(max int) *Bar { + b := &Bar{max: max} + b.measurements.Grow(measurements) + return b +} + +// Set sets the current value to val. +func (b *Bar) Set(val int) { if b.measurements.Len() == measurements { b.measurements.PopFront() } @@ -64,10 +68,10 @@ func (b *Bar) Print() { delta := last.i - first.i eta := time.Duration(-1) if delta != 0 { - eta = time.Duration(float64(deltaT) * (1 - last.i) / delta) + eta = time.Duration(float64(b.max-last.i) / float64(delta) * float64(deltaT)) } - p := int(last.i * float64(b.cols)) + p := last.i * b.cols / b.max if b.cols == 0 { var err error if b.cols, _, err = term.GetSize(int(os.Stderr.Fd())); err != nil { |
