Set current (#37)
* atomic SetCurrent
Vladimir Bauer authored 7 years ago
GitHub committed 7 years ago
| 5 | 5 | "fmt" |
| 6 | 6 | "io" |
| 7 | 7 | "io/ioutil" |
| 8 | "runtime" | |
| 8 | 9 | "strings" |
| 9 | 10 | "sync" |
| 11 | "sync/atomic" | |
| 10 | 12 | "time" |
| 11 | 13 | "unicode/utf8" |
| 12 | 14 | |
| 45 | 47 | done chan struct{} |
| 46 | 48 | // shutdown is closed from master Progress goroutine only |
| 47 | 49 | shutdown chan struct{} |
| 50 | ||
| 51 | arbitraryCurrent struct { | |
| 52 | lock uint32 | |
| 53 | current int64 | |
| 54 | } | |
| 48 | 55 | } |
| 49 | 56 | |
| 50 | 57 | type ( |
| 181 | 188 | } |
| 182 | 189 | } |
| 183 | 190 | |
| 184 | // SetTotal sets total dynamically. | |
| 185 | // Set final to true, when total is known, it will trigger bar complete event. | |
| 186 | func (b *Bar) SetTotal(total int64, final bool) bool { | |
| 187 | select { | |
| 188 | case b.operateState <- func(s *bState) { | |
| 189 | if total > 0 { | |
| 190 | s.total = total | |
| 191 | } | |
| 192 | if final { | |
| 193 | s.current = s.total | |
| 194 | s.toComplete = true | |
| 195 | } | |
| 196 | }: | |
| 197 | return true | |
| 198 | case <-b.done: | |
| 199 | return false | |
| 200 | } | |
| 201 | } | |
| 202 | ||
| 203 | 191 | // SetRefill sets refill, if supported by underlying Filler. |
| 204 | 192 | func (b *Bar) SetRefill(upto int) { |
| 205 | 193 | b.operateState <- func(s *bState) { |
| 207 | 195 | f.SetRefill(upto) |
| 208 | 196 | } |
| 209 | 197 | } |
| 198 | } | |
| 199 | ||
| 200 | // SetTotal sets total dynamically. | |
| 201 | // Set final to true, when total is known, it will trigger bar complete event. | |
| 202 | func (b *Bar) SetTotal(total int64, final bool) bool { | |
| 203 | select { | |
| 204 | case b.operateState <- func(s *bState) { | |
| 205 | if total > 0 { | |
| 206 | s.total = total | |
| 207 | } | |
| 208 | if final { | |
| 209 | s.current = s.total | |
| 210 | s.toComplete = true | |
| 211 | } | |
| 212 | }: | |
| 213 | return true | |
| 214 | case <-b.done: | |
| 215 | return false | |
| 216 | } | |
| 217 | } | |
| 218 | ||
| 219 | // SetCurrent sets progress' current to arbitrary amount. | |
| 220 | func (b *Bar) SetCurrent(current int64, wdd ...time.Duration) { | |
| 221 | if current <= 0 { | |
| 222 | return | |
| 223 | } | |
| 224 | for !atomic.CompareAndSwapUint32(&b.arbitraryCurrent.lock, 0, 1) { | |
| 225 | runtime.Gosched() | |
| 226 | } | |
| 227 | last := b.arbitraryCurrent.current | |
| 228 | b.IncrBy(int(current-last), wdd...) | |
| 229 | b.arbitraryCurrent.current = current | |
| 230 | atomic.StoreUint32(&b.arbitraryCurrent.lock, 0) | |
| 210 | 231 | } |
| 211 | 232 | |
| 212 | 233 | // Increment is a shorthand for b.IncrBy(1). |