Last active
July 30, 2018 06:43
-
-
Save ntnmrndn/b1c1f1320a3744320554699e4daf56fc to your computer and use it in GitHub Desktop.
Swift LIFO Queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// LIFOOperationQueue.swift | |
// | |
// | |
// Created by Antoine Marandon on 27/07/2018. | |
// | |
import Foundation | |
/// Last in First Out Operation queue. | |
class LIFOOperationQueue { | |
enum Priority { | |
case high | |
case low | |
} | |
private let queue: DispatchQueue | |
private var highPriorityOperations = [Operation]() | |
private var lowPriorityOperations = [Operation]() | |
init(queue: DispatchQueue) { | |
self.queue = queue | |
} | |
private func next() { | |
if let operation = highPriorityOperations.first { | |
highPriorityOperations.remove(at: 0) | |
queue.async { | |
operation.start() | |
} | |
} else if let operation = lowPriorityOperations.first { | |
lowPriorityOperations.remove(at: 0) | |
queue.async { | |
operation.start() | |
} | |
} | |
} | |
/// Add an operation to the queue. Adding a duplicate operation cause it to be bumped to the top of the queue. | |
func addOperation(operation: Operation, priority: Priority) { | |
queue.async { | |
if let index = self.highPriorityOperations.index(of: operation) { | |
self.highPriorityOperations.remove(at: index) | |
} | |
if let index = self.lowPriorityOperations.index(of: operation) { | |
self.lowPriorityOperations.remove(at: index) | |
} | |
switch priority { | |
case .high: | |
self.highPriorityOperations.insert(operation, at: 0) | |
case .low: | |
self.lowPriorityOperations.insert(operation, at: 0) | |
} | |
self.queue.async { | |
self.next() | |
} | |
} | |
} | |
/// De prioritize an operation. | |
func pushBack(operation: Operation) { | |
queue.async { | |
if let index = self.highPriorityOperations.index(of: operation) { | |
self.highPriorityOperations.remove(at: index) | |
} | |
if let index = self.lowPriorityOperations.index(of: operation) { | |
self.lowPriorityOperations.remove(at: index) | |
} | |
self.lowPriorityOperations.append(operation) | |
self.queue.async { | |
self.next() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment