Collection+Extension.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. @inlinable
  18. func toUInt32Array() -> Array<UInt32> {
  19. guard !isEmpty else {
  20. return []
  21. }
  22. let c = strideCount(from: startIndex, to: endIndex, by: 4)
  23. return Array<UInt32>(unsafeUninitializedCapacity: c) { buf, count in
  24. var counter = 0
  25. for idx in stride(from: startIndex, to: endIndex, by: 4) {
  26. let val = UInt32(bytes: self, fromIndex: idx).bigEndian
  27. buf[counter] = val
  28. counter += 1
  29. }
  30. count = counter
  31. assert(counter == c)
  32. }
  33. }
  34. // Big endian order
  35. @inlinable
  36. func toUInt64Array() -> Array<UInt64> {
  37. guard !isEmpty else {
  38. return []
  39. }
  40. let c = strideCount(from: startIndex, to: endIndex, by: 8)
  41. return Array<UInt64>(unsafeUninitializedCapacity: c) { buf, count in
  42. var counter = 0
  43. for idx in stride(from: startIndex, to: endIndex, by: 8) {
  44. let val = UInt64(bytes: self, fromIndex: idx).bigEndian
  45. buf[counter] = val
  46. counter += 1
  47. }
  48. count = counter
  49. assert(counter == c)
  50. }
  51. }
  52. }
  53. @usableFromInline
  54. func strideCount(from: Int, to: Int, by: Int) -> Int {
  55. let count = to - from
  56. return count / by + (count % by > 0 ? 1 : 0)
  57. }