Collection+Extension.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2017 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // 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:
  10. //
  11. // - 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.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. extension Collection where Self.Element == UInt8, Self.Index == Int {
  16. // Big endian order
  17. func toUInt32Array() -> Array<UInt32> {
  18. guard !isEmpty else {
  19. return []
  20. }
  21. let c = strideCount(from: startIndex, to: endIndex, by: 4)
  22. return Array<UInt32>(unsafeUninitializedCapacity: c) { buf, count in
  23. var counter = 0
  24. for idx in stride(from: startIndex, to: endIndex, by: 4) {
  25. let val = UInt32(bytes: self, fromIndex: idx).bigEndian
  26. buf[counter] = val
  27. counter += 1
  28. }
  29. count = counter
  30. assert(counter == c)
  31. }
  32. }
  33. // Big endian order
  34. func toUInt64Array() -> Array<UInt64> {
  35. guard !isEmpty else {
  36. return []
  37. }
  38. let c = strideCount(from: startIndex, to: endIndex, by: 8)
  39. return Array<UInt64>(unsafeUninitializedCapacity: c) { buf, count in
  40. var counter = 0
  41. for idx in stride(from: startIndex, to: endIndex, by: 8) {
  42. let val = UInt64(bytes: self, fromIndex: idx).bigEndian
  43. buf[counter] = val
  44. counter += 1
  45. }
  46. count = counter
  47. assert(counter == c)
  48. }
  49. }
  50. }
  51. private func strideCount(from: Int, to: Int, by: Int) -> Int {
  52. let count = to - from
  53. return count / by + (count % by > 0 ? 1 : 0)
  54. }