Array+Extension.swift 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. init(reserveCapacity: Int) {
  10. self = Array<Element>()
  11. self.reserveCapacity(reserveCapacity)
  12. }
  13. }
  14. extension Array {
  15. /** split in chunks with given chunk size */
  16. func chunks(size chunksize: Int) -> Array<Array<Element>> {
  17. var words = Array<Array<Element>>()
  18. words.reserveCapacity(self.count / chunksize)
  19. for idx in stride(from: chunksize, through: self.count, by: chunksize) {
  20. words.append(Array(self[idx - chunksize ..< idx])) // slow for large table
  21. }
  22. let reminder = self.suffix(self.count % chunksize)
  23. if !reminder.isEmpty {
  24. words.append(Array(reminder))
  25. }
  26. return words
  27. }
  28. }
  29. extension Array where Element: Integer, Element.IntegerLiteralType == UInt8 {
  30. public init(hex: String) {
  31. self.init()
  32. let utf8 = Array<Element.IntegerLiteralType>(hex.utf8)
  33. let skip0x = hex.hasPrefix("0x") ? 2 : 0
  34. for idx in stride(from: utf8.startIndex.advanced(by: skip0x), to: utf8.endIndex, by: utf8.startIndex.advanced(by: 2)) {
  35. let byteHex = "\(UnicodeScalar(utf8[idx]))\(UnicodeScalar(utf8[idx.advanced(by: 1)]))"
  36. if let byte = UInt8(byteHex, radix: 16) {
  37. self.append(byte as! Element)
  38. }
  39. }
  40. }
  41. }