Skip to content

Commit

Permalink
All variables need to be modified by function because of mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
schollz committed Oct 26, 2017
1 parent fdf19f7 commit 91090f7
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions progressbar.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import (
// ProgressBar is a thread-safe, simple
// progress bar
type ProgressBar struct {
Max int // max number of the counter
Size int // size of the saucer
max int // max number of the counter
size int // size of the saucer
currentNum int
currentPercent int
lastPercent int
Expand All @@ -38,8 +38,8 @@ func New(max int) *ProgressBar {
p := new(ProgressBar)
p.Lock()
defer p.Unlock()
p.Max = max
p.Size = 40
p.max = max
p.size = 40
p.symbolFinished = "█"
p.symbolLeft = " "
p.leftBookend = "|"
Expand All @@ -59,18 +59,18 @@ func (p *ProgressBar) Reset() {
}

// Set the max of the progress bar
func (p *ProgressBar) Set(num int) {
func (p *ProgressBar) SetMax(num int) {
p.Lock()
defer p.Unlock()
p.Max = num
p.max = num
}

// Add a certain amount to the progress bar
func (p *ProgressBar) Add(num int) error {
p.Lock()
p.currentNum += num
percent := float64(p.currentNum) / float64(p.Max)
p.currentSaucerSize = int(percent * float64(p.Size))
percent := float64(p.currentNum) / float64(p.max)
p.currentSaucerSize = int(percent * float64(p.size))
p.currentPercent = int(percent * 100)
updateBar := p.currentPercent != p.lastPercent && p.currentPercent > 0
p.lastPercent = p.currentPercent
Expand All @@ -85,15 +85,15 @@ func (p *ProgressBar) Add(num int) error {
func (p *ProgressBar) Show() error {
p.RLock()
defer p.RUnlock()
if p.currentNum > p.Max {
if p.currentNum > p.max {
return errors.New("current number exceeds max")
}
secondsLeft := time.Since(p.startTime).Seconds() / float64(p.currentNum) * (float64(p.Max) - float64(p.currentNum))
secondsLeft := time.Since(p.startTime).Seconds() / float64(p.currentNum) * (float64(p.max) - float64(p.currentNum))
s := fmt.Sprintf("\r%3d%% %s%s%s%s [%s:%s] ",
p.currentPercent,
p.leftBookend,
strings.Repeat(p.symbolFinished, p.currentSaucerSize),
strings.Repeat(p.symbolLeft, p.Size-p.currentSaucerSize),
strings.Repeat(p.symbolLeft, p.size-p.currentSaucerSize),
p.rightBookend,
time.Since(p.startTime).Round(time.Second).String(),
(time.Duration(secondsLeft) * time.Second).String(),
Expand Down

0 comments on commit 91090f7

Please sign in to comment.