queue.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package model
  7. import "sync"
  8. type jobQueue struct {
  9. progress []string
  10. queued []string
  11. mut sync.Mutex
  12. }
  13. func newJobQueue() *jobQueue {
  14. return &jobQueue{}
  15. }
  16. func (q *jobQueue) Push(file string) {
  17. q.mut.Lock()
  18. q.queued = append(q.queued, file)
  19. q.mut.Unlock()
  20. }
  21. func (q *jobQueue) Pop() (string, bool) {
  22. q.mut.Lock()
  23. defer q.mut.Unlock()
  24. if len(q.queued) == 0 {
  25. return "", false
  26. }
  27. var f string
  28. f = q.queued[0]
  29. q.queued = q.queued[1:]
  30. q.progress = append(q.progress, f)
  31. return f, true
  32. }
  33. func (q *jobQueue) BringToFront(filename string) {
  34. q.mut.Lock()
  35. defer q.mut.Unlock()
  36. for i, cur := range q.queued {
  37. if cur == filename {
  38. if i > 0 {
  39. // Shift the elements before the selected element one step to
  40. // the right, overwriting the selected element
  41. copy(q.queued[1:i+1], q.queued[0:])
  42. // Put the selected element at the front
  43. q.queued[0] = cur
  44. }
  45. return
  46. }
  47. }
  48. }
  49. func (q *jobQueue) Done(file string) {
  50. q.mut.Lock()
  51. defer q.mut.Unlock()
  52. for i := range q.progress {
  53. if q.progress[i] == file {
  54. copy(q.progress[i:], q.progress[i+1:])
  55. q.progress = q.progress[:len(q.progress)-1]
  56. return
  57. }
  58. }
  59. }
  60. func (q *jobQueue) Jobs() ([]string, []string) {
  61. q.mut.Lock()
  62. defer q.mut.Unlock()
  63. progress := make([]string, len(q.progress))
  64. copy(progress, q.progress)
  65. queued := make([]string, len(q.queued))
  66. copy(queued, q.queued)
  67. return progress, queued
  68. }