Array+Extension.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. //
  2. // ArrayExtension.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 10/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. extension Array {
  9. /** split in chunks with given chunk size */
  10. func chunks(size chunksize: Int) -> Array<Array<Element>> {
  11. var words = Array<Array<Element>>()
  12. words.reserveCapacity(self.count / chunksize)
  13. for idx in stride(from: chunksize, through: self.count, by: chunksize) {
  14. words.append(Array(self[idx - chunksize..<idx])) // slow for large table
  15. }
  16. let reminder = self.suffix(self.count % chunksize)
  17. if !reminder.isEmpty {
  18. words.append(Array(reminder))
  19. }
  20. return words
  21. }
  22. }
  23. extension Array where Element: Integer, Element.IntegerLiteralType == UInt8 {
  24. public init(hex: String) {
  25. self.init()
  26. let utf8 = Array<Element.IntegerLiteralType>(hex.utf8)
  27. let skip0x = hex.hasPrefix("0x") ? 2 : 0
  28. for idx in stride(from: utf8.startIndex.advanced(by: skip0x), to: utf8.endIndex, by: utf8.startIndex.advanced(by: 2)) {
  29. let byteHex = "\(UnicodeScalar(utf8[idx]))\(UnicodeScalar(utf8[idx.advanced(by: 1)]))"
  30. if let byte = UInt8(byteHex, radix: 16) {
  31. self.append(byte as! Element)
  32. }
  33. }
  34. }
  35. }