Updatable.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // Updatable.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 06/05/16.
  6. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. public protocol Updatable {
  9. /// Update given bytes in chunks.
  10. ///
  11. /// - parameter bytes: Bytes to process
  12. /// - parameter isLast: (Optional) Given chunk is the last one. No more updates after this call.
  13. /// - returns: Processed data or empty array.
  14. mutating func update<T: Sequence>(withBytes bytes:T, isLast: Bool) throws -> Array<UInt8> where T.Iterator.Element == UInt8
  15. /// Update given bytes in chunks.
  16. ///
  17. /// - parameter bytes: Bytes to process
  18. /// - parameter isLast: (Optional) Given chunk is the last one. No more updates after this call.
  19. /// - parameter output: Resulting data
  20. /// - returns: Processed data or empty array.
  21. mutating func update<T: Sequence>(withBytes bytes:T, isLast: Bool, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8
  22. /// Finish updates. This may apply padding.
  23. /// - parameter bytes: Bytes to process
  24. /// - returns: Processed data.
  25. mutating func finish<T: Sequence>(withBytes bytes:T) throws -> Array<UInt8> where T.Iterator.Element == UInt8
  26. /// Finish updates. This may apply padding.
  27. /// - parameter bytes: Bytes to process
  28. /// - parameter output: Resulting data
  29. /// - returns: Processed data.
  30. mutating func finish<T: Sequence>(withBytes bytes:T, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8
  31. }
  32. extension Updatable {
  33. mutating public func update<T: Sequence>(withBytes bytes:T, isLast: Bool = false, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8 {
  34. let processed = try self.update(withBytes: bytes, isLast: isLast)
  35. if (!processed.isEmpty) {
  36. output(processed)
  37. }
  38. }
  39. mutating public func finish<T: Sequence>(withBytes bytes:T) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
  40. return try self.update(withBytes: bytes, isLast: true)
  41. }
  42. mutating public func finish() throws -> Array<UInt8> {
  43. return try self.update(withBytes: [], isLast: true)
  44. }
  45. mutating public func finish<T: Sequence>(withBytes bytes:T, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8 {
  46. let processed = try self.update(withBytes: bytes, isLast: true)
  47. if (!processed.isEmpty) {
  48. output(processed)
  49. }
  50. }
  51. mutating public func finish(output: (Array<UInt8>) -> Void) throws {
  52. try self.finish(withBytes: [], output: output)
  53. }
  54. }