fillBar bug fixes
Vladimir Bauer
9 years ago
| 1 | 1 | |
| 2 | 2 | import ( |
| 3 | 3 | "io" |
| 4 | "math" | |
| 4 | 5 | "sync" |
| 5 | 6 | "time" |
| 6 | 7 | "unicode/utf8" |
| 432 | 433 | } |
| 433 | 434 | |
| 434 | 435 | func fillBar(total, current int64, width int, fmtBytes barFmtBytes, rf *refill) []byte { |
| 435 | if width < 2 { | |
| 436 | if width < 2 || total <= 0 { | |
| 436 | 437 | return []byte{} |
| 437 | 438 | } |
| 438 | 439 | |
| 439 | 440 | // bar width without leftEnd and rightEnd runes |
| 440 | barWidth := width - 1 | |
| 441 | barWidth := width - 2 | |
| 441 | 442 | |
| 442 | 443 | completedWidth := percentage(total, current, barWidth) |
| 443 | 444 | |
| 452 | 453 | for i := 0; i < till; i++ { |
| 453 | 454 | buf = append(buf, rbytes...) |
| 454 | 455 | } |
| 455 | for i := till; i < completedWidth-1; i++ { | |
| 456 | for i := till; i < completedWidth; i++ { | |
| 456 | 457 | buf = append(buf, fmtBytes[rFill]...) |
| 457 | 458 | } |
| 458 | 459 | } else { |
| 459 | for i := 0; i < completedWidth-1; i++ { | |
| 460 | for i := 0; i < completedWidth; i++ { | |
| 460 | 461 | buf = append(buf, fmtBytes[rFill]...) |
| 461 | 462 | } |
| 462 | 463 | } |
| 463 | 464 | |
| 464 | if completedWidth > 0 && completedWidth < barWidth { | |
| 465 | if completedWidth < barWidth && completedWidth > 0 { | |
| 466 | _, size := utf8.DecodeLastRune(buf) | |
| 467 | buf = buf[:len(buf)-size] | |
| 465 | 468 | buf = append(buf, fmtBytes[rTip]...) |
| 466 | 469 | } |
| 467 | 470 | |
| 468 | for i := completedWidth + 1; i < barWidth; i++ { | |
| 471 | for i := completedWidth; i < barWidth; i++ { | |
| 469 | 472 | buf = append(buf, fmtBytes[rEmpty]...) |
| 470 | 473 | } |
| 471 | 474 | |
| 500 | 503 | } |
| 501 | 504 | |
| 502 | 505 | func percentage(total, current int64, ratio int) int { |
| 503 | if total <= 0 { | |
| 506 | if current > total { | |
| 504 | 507 | return 0 |
| 505 | 508 | } |
| 506 | return int(float64(ratio) * float64(current) / float64(total)) | |
| 509 | num := float64(ratio) * float64(current) / float64(total) | |
| 510 | ceil := math.Ceil(num) | |
| 511 | diff := ceil - num | |
| 512 | // num = 2.34 will return 2 | |
| 513 | // num = 2.44 will return 3 | |
| 514 | if math.Max(diff, 0.6) == diff { | |
| 515 | return int(num) | |
| 516 | } | |
| 517 | return int(ceil) | |
| 507 | 518 | } |
| 508 | 519 | |
| 509 | 520 | func getSpinner() func() byte { |