queue.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package model
  16. import "sync"
  17. type jobQueue struct {
  18. progress []string
  19. queued []string
  20. mut sync.Mutex
  21. }
  22. func newJobQueue() *jobQueue {
  23. return &jobQueue{}
  24. }
  25. func (q *jobQueue) Push(file string) {
  26. q.mut.Lock()
  27. q.queued = append(q.queued, file)
  28. q.mut.Unlock()
  29. }
  30. func (q *jobQueue) Pop() (string, bool) {
  31. q.mut.Lock()
  32. defer q.mut.Unlock()
  33. if len(q.queued) == 0 {
  34. return "", false
  35. }
  36. var f string
  37. f = q.queued[0]
  38. q.queued = q.queued[1:]
  39. q.progress = append(q.progress, f)
  40. return f, true
  41. }
  42. func (q *jobQueue) BringToFront(filename string) {
  43. q.mut.Lock()
  44. defer q.mut.Unlock()
  45. for i, cur := range q.queued {
  46. if cur == filename {
  47. if i > 0 {
  48. // Shift the elements before the selected element one step to
  49. // the right, overwriting the selected element
  50. copy(q.queued[1:i+1], q.queued[0:])
  51. // Put the selected element at the front
  52. q.queued[0] = cur
  53. }
  54. return
  55. }
  56. }
  57. }
  58. func (q *jobQueue) Done(file string) {
  59. q.mut.Lock()
  60. defer q.mut.Unlock()
  61. for i := range q.progress {
  62. if q.progress[i] == file {
  63. copy(q.progress[i:], q.progress[i+1:])
  64. q.progress = q.progress[:len(q.progress)-1]
  65. return
  66. }
  67. }
  68. }
  69. func (q *jobQueue) Jobs() ([]string, []string) {
  70. q.mut.Lock()
  71. defer q.mut.Unlock()
  72. progress := make([]string, len(q.progress))
  73. copy(progress, q.progress)
  74. queued := make([]string, len(q.queued))
  75. copy(queued, q.queued)
  76. return progress, queued
  77. }