scale.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package progress
  14. type scaledReport struct {
  15. Report
  16. n int
  17. i int
  18. }
  19. func (r scaledReport) Percentage() float32 {
  20. b := 100 * float32(r.i) / float32(r.n)
  21. return b + (r.Report.Percentage() / float32(r.n))
  22. }
  23. type scaleOne struct {
  24. s Sinker
  25. n int
  26. i int
  27. }
  28. func (s scaleOne) Sink() chan<- Report {
  29. upstream := make(chan Report)
  30. downstream := s.s.Sink()
  31. go s.loop(upstream, downstream)
  32. return upstream
  33. }
  34. func (s scaleOne) loop(upstream <-chan Report, downstream chan<- Report) {
  35. defer close(downstream)
  36. for r := range upstream {
  37. downstream <- scaledReport{
  38. Report: r,
  39. n: s.n,
  40. i: s.i,
  41. }
  42. }
  43. }
  44. type scaleMany struct {
  45. s Sinker
  46. n int
  47. i int
  48. }
  49. func Scale(s Sinker, n int) Sinker {
  50. return &scaleMany{
  51. s: s,
  52. n: n,
  53. }
  54. }
  55. func (s *scaleMany) Sink() chan<- Report {
  56. if s.i == s.n {
  57. s.n++
  58. }
  59. ch := scaleOne{s: s.s, n: s.n, i: s.i}.Sink()
  60. s.i++
  61. return ch
  62. }