Array+Extension.swift 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // ArrayExtension.swift
  3. // CryptoSwift
  4. //
  5. // Copyright (C) 2014-2017 Krzyżanowski <marcin@krzyzanowskim.com>
  6. // This software is provided 'as-is', without any express or implied warranty.
  7. //
  8. // In no event will the authors be held liable for any damages arising from the use of this software.
  9. //
  10. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  11. //
  12. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  13. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  14. // - This notice may not be removed or altered from any source or binary distribution.
  15. //
  16. extension Array {
  17. init(reserveCapacity: Int) {
  18. self = Array<Element>()
  19. self.reserveCapacity(reserveCapacity)
  20. }
  21. }
  22. extension Array {
  23. /** split in chunks with given chunk size */
  24. public func chunks(size chunksize: Int) -> Array<Array<Element>> {
  25. var words = Array<Array<Element>>()
  26. words.reserveCapacity(self.count / chunksize)
  27. for idx in stride(from: chunksize, through: self.count, by: chunksize) {
  28. words.append(Array(self[idx - chunksize ..< idx])) // slow for large table
  29. }
  30. let remainder = self.suffix(self.count % chunksize)
  31. if !remainder.isEmpty {
  32. words.append(Array(remainder))
  33. }
  34. return words
  35. }
  36. }
  37. extension Array where Element == UInt8 {
  38. public init(hex: String) {
  39. self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount)
  40. var buffer:UInt8?
  41. var skip = hex.hasPrefix("0x") ? 2 : 0
  42. for char in hex.unicodeScalars.lazy {
  43. guard skip == 0 else {
  44. skip -= 1
  45. continue
  46. }
  47. guard char.value >= 48 && char.value <= 102 else {
  48. self.removeAll()
  49. return
  50. }
  51. let v:UInt8
  52. let c:UInt8 = UInt8(char.value)
  53. switch c{
  54. case let c where c <= 57:
  55. v = c - 48
  56. case let c where c >= 65 && c <= 70:
  57. v = c - 55
  58. case let c where c >= 97:
  59. v = c - 87
  60. default:
  61. self.removeAll()
  62. return
  63. }
  64. if let b = buffer {
  65. self.append(b << 4 | v)
  66. buffer = nil
  67. } else {
  68. buffer = v
  69. }
  70. }
  71. if let b = buffer {
  72. self.append(b)
  73. }
  74. }
  75. }