queue.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 (
  17. "sync"
  18. "github.com/syncthing/syncthing/internal/protocol"
  19. )
  20. type JobQueue struct {
  21. progress []*protocol.FileInfo
  22. queued []*protocol.FileInfo
  23. mut sync.Mutex
  24. }
  25. func NewJobQueue() *JobQueue {
  26. return &JobQueue{}
  27. }
  28. func (q *JobQueue) Push(file *protocol.FileInfo) {
  29. q.mut.Lock()
  30. q.queued = append(q.queued, file)
  31. q.mut.Unlock()
  32. }
  33. func (q *JobQueue) Pop() *protocol.FileInfo {
  34. q.mut.Lock()
  35. defer q.mut.Unlock()
  36. if len(q.queued) == 0 {
  37. return nil
  38. }
  39. var f *protocol.FileInfo
  40. f, q.queued[0] = q.queued[0], nil
  41. q.queued = q.queued[1:]
  42. q.progress = append(q.progress, f)
  43. return f
  44. }
  45. func (q *JobQueue) Bump(filename string) {
  46. q.mut.Lock()
  47. defer q.mut.Unlock()
  48. for i := range q.queued {
  49. if q.queued[i].Name == filename {
  50. q.queued[0], q.queued[i] = q.queued[i], q.queued[0]
  51. return
  52. }
  53. }
  54. }
  55. func (q *JobQueue) Done(file *protocol.FileInfo) {
  56. q.mut.Lock()
  57. defer q.mut.Unlock()
  58. for i := range q.progress {
  59. if q.progress[i].Name == file.Name {
  60. copy(q.progress[i:], q.progress[i+1:])
  61. q.progress[len(q.progress)-1] = nil
  62. q.progress = q.progress[:len(q.progress)-1]
  63. return
  64. }
  65. }
  66. }
  67. func (q *JobQueue) Jobs() ([]protocol.FileInfoTruncated, []protocol.FileInfoTruncated) {
  68. q.mut.Lock()
  69. defer q.mut.Unlock()
  70. progress := make([]protocol.FileInfoTruncated, len(q.progress))
  71. for i := range q.progress {
  72. progress[i] = q.progress[i].ToTruncated()
  73. }
  74. queued := make([]protocol.FileInfoTruncated, len(q.queued))
  75. for i := range q.queued {
  76. queued[i] = q.queued[i].ToTruncated()
  77. }
  78. return progress, queued
  79. }