SocketAckManager.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // SocketAckManager.swift
  3. // Socket.IO-Client-Swift
  4. //
  5. // Created by Erik Little on 4/3/15.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import Foundation
  25. private struct SocketAck : Hashable, Equatable {
  26. let ack: Int
  27. var callback: AckCallback!
  28. var hashValue: Int {
  29. return ack.hashValue
  30. }
  31. init(ack: Int) {
  32. self.ack = ack
  33. }
  34. init(ack: Int, callback: AckCallback) {
  35. self.ack = ack
  36. self.callback = callback
  37. }
  38. }
  39. private func <(lhs: SocketAck, rhs: SocketAck) -> Bool {
  40. return lhs.ack < rhs.ack
  41. }
  42. private func ==(lhs: SocketAck, rhs: SocketAck) -> Bool {
  43. return lhs.ack == rhs.ack
  44. }
  45. struct SocketAckManager {
  46. private var acks = Set<SocketAck>(minimumCapacity: 1)
  47. mutating func addAck(ack: Int, callback: AckCallback) {
  48. acks.insert(SocketAck(ack: ack, callback: callback))
  49. }
  50. mutating func executeAck(ack: Int, items: [AnyObject]) {
  51. let callback = acks.remove(SocketAck(ack: ack))
  52. dispatch_async(dispatch_get_main_queue()) {
  53. callback?.callback(items)
  54. }
  55. }
  56. mutating func timeoutAck(ack: Int) {
  57. let callback = acks.remove(SocketAck(ack: ack))
  58. dispatch_async(dispatch_get_main_queue()) {
  59. callback?.callback(["NO ACK"])
  60. }
  61. }
  62. }