-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: thread safety for Manual functions (#1)
Signed-off-by: Keith Zantow <[email protected]>
- Loading branch information
Showing
2 changed files
with
64 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,71 @@ | ||
package progress | ||
|
||
import ( | ||
"sync" | ||
"sync/atomic" | ||
) | ||
|
||
type Manual struct { | ||
N int64 | ||
Total int64 | ||
Err error | ||
n int64 | ||
total int64 | ||
err error | ||
errMutex sync.Mutex | ||
} | ||
|
||
func NewManual(size int64) *Manual { | ||
return &Manual{ | ||
total: size, | ||
} | ||
} | ||
|
||
func (p Manual) Current() int64 { | ||
return int64(p.N) | ||
func (p *Manual) Current() int64 { | ||
return atomic.LoadInt64(&p.n) | ||
} | ||
|
||
func (p Manual) Size() int64 { | ||
return int64(p.Total) | ||
func (p *Manual) Size() int64 { | ||
return atomic.LoadInt64(&p.total) | ||
} | ||
|
||
func (p Manual) Error() error { | ||
return p.Err | ||
func (p *Manual) Error() error { | ||
p.errMutex.Lock() | ||
defer p.errMutex.Unlock() | ||
return p.err | ||
} | ||
|
||
func (p Manual) Progress() Progress { | ||
func (p *Manual) SetError(err error) { | ||
p.errMutex.Lock() | ||
defer p.errMutex.Unlock() | ||
p.err = err | ||
} | ||
|
||
func (p *Manual) Progress() Progress { | ||
return Progress{ | ||
current: p.N, | ||
size: p.Total, | ||
err: p.Err, | ||
current: p.Current(), | ||
size: p.Size(), | ||
err: p.Error(), | ||
} | ||
} | ||
|
||
func (p *Manual) Add(n int64) { | ||
atomic.AddInt64(&p.n, n) | ||
} | ||
|
||
func (p *Manual) Increment() { | ||
atomic.AddInt64(&p.n, 1) | ||
} | ||
|
||
func (p *Manual) Set(n int64) { | ||
atomic.StoreInt64(&p.n, n) | ||
} | ||
|
||
func (p *Manual) SetTotal(total int64) { | ||
atomic.StoreInt64(&p.total, total) | ||
} | ||
|
||
func (p *Manual) SetCompleted() { | ||
p.Err = ErrCompleted | ||
if p.N > 0 && p.Total <= 0 { | ||
p.Total = p.N | ||
p.SetError(ErrCompleted) | ||
if p.Current() > 0 && p.Size() <= 0 { | ||
p.SetTotal(p.Current()) | ||
return | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters