Generics.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. /** build bit pattern from array of bits */
  16. @_specialize(exported: true, where T == UInt8)
  17. func integerFrom<T: FixedWidthInteger>(_ bits: Array<Bit>) -> T {
  18. var bitPattern: T = 0
  19. for idx in bits.indices {
  20. if bits[idx] == Bit.one {
  21. let bit = T(UInt64(1) << UInt64(idx))
  22. bitPattern = bitPattern | bit
  23. }
  24. }
  25. return bitPattern
  26. }
  27. /// Array of bytes. Caution: don't use directly because generic is slow.
  28. ///
  29. /// - parameter value: integer value
  30. /// - parameter length: length of output array. By default size of value type
  31. ///
  32. /// - returns: Array of bytes
  33. @_specialize(exported: true, where T == Int)
  34. @_specialize(exported: true, where T == UInt)
  35. @_specialize(exported: true, where T == UInt8)
  36. @_specialize(exported: true, where T == UInt16)
  37. @_specialize(exported: true, where T == UInt32)
  38. @_specialize(exported: true, where T == UInt64)
  39. func arrayOfBytes<T: FixedWidthInteger>(value: T, length totalBytes: Int = MemoryLayout<T>.size) -> Array<UInt8> {
  40. let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
  41. valuePointer.pointee = value
  42. let bytesPointer = UnsafeMutablePointer<UInt8>(OpaquePointer(valuePointer))
  43. var bytes = Array<UInt8>(repeating: 0, count: totalBytes)
  44. for j in 0..<min(MemoryLayout<T>.size, totalBytes) {
  45. bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
  46. }
  47. valuePointer.deinitialize(count: 1)
  48. valuePointer.deallocate()
  49. return bytes
  50. }