Collection+Extension.swift 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // Collection+Extension.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 02/08/16.
  6. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. extension Collection where Self.Iterator.Element == UInt8, Self.Index == Int {
  9. func toUInt32Array() -> Array<UInt32> {
  10. var result = Array<UInt32>()
  11. result.reserveCapacity(16)
  12. for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt32>.size) {
  13. var val: UInt32 = 0
  14. val |= self.count > 3 ? UInt32(self[idx.advanced(by: 3)]) << 24 : 0
  15. val |= self.count > 2 ? UInt32(self[idx.advanced(by: 2)]) << 16 : 0
  16. val |= self.count > 1 ? UInt32(self[idx.advanced(by: 1)]) << 8 : 0
  17. val |= self.count > 0 ? UInt32(self[idx]) : 0
  18. result.append(val)
  19. }
  20. return result
  21. }
  22. func toUInt64Array() -> Array<UInt64> {
  23. var result = Array<UInt64>()
  24. result.reserveCapacity(32)
  25. for idx in stride(from: self.startIndex, to: self.endIndex, by: MemoryLayout<UInt64>.size) {
  26. var val:UInt64 = 0
  27. val |= self.count > 7 ? UInt64(self[idx.advanced(by: 7)]) << 56 : 0
  28. val |= self.count > 6 ? UInt64(self[idx.advanced(by: 6)]) << 48 : 0
  29. val |= self.count > 5 ? UInt64(self[idx.advanced(by: 5)]) << 40 : 0
  30. val |= self.count > 4 ? UInt64(self[idx.advanced(by: 4)]) << 32 : 0
  31. val |= self.count > 3 ? UInt64(self[idx.advanced(by: 3)]) << 24 : 0
  32. val |= self.count > 2 ? UInt64(self[idx.advanced(by: 2)]) << 16 : 0
  33. val |= self.count > 1 ? UInt64(self[idx.advanced(by: 1)]) << 8 : 0
  34. val |= self.count > 0 ? UInt64(self[idx.advanced(by: 0)]) << 0 : 0
  35. result.append(val)
  36. }
  37. return result
  38. }
  39. /// Initialize integer from array of bytes. Caution: may be slow!
  40. @available(*, deprecated: 0.6.0, message: "Dont use it. Too generic to be fast")
  41. func toInteger<T:Integer>() -> T where T: ByteConvertible, T: BitshiftOperationsType {
  42. if self.count == 0 {
  43. return 0;
  44. }
  45. let size = MemoryLayout<T>.size
  46. var bytes = self.reversed() //FIXME: check it this is equivalent of Array(...)
  47. if bytes.count < size {
  48. let paddingCount = size - bytes.count
  49. if (paddingCount > 0) {
  50. bytes += Array<UInt8>(repeating: 0, count: paddingCount)
  51. }
  52. }
  53. if size == 1 {
  54. return T(truncatingBitPattern: UInt64(bytes[0]))
  55. }
  56. var result: T = 0
  57. for byte in bytes.reversed() {
  58. result = result << 8 | T(byte)
  59. }
  60. return result
  61. }
  62. }