Utils.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // Utils.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 26/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. import Foundation
  9. func rotateLeft(v:UInt8, n:UInt8) -> UInt8 {
  10. return ((v << n) & 0xFF) | (v >> (8 - n))
  11. }
  12. func rotateLeft(v:UInt16, n:UInt16) -> UInt16 {
  13. return ((v << n) & 0xFFFF) | (v >> (16 - n))
  14. }
  15. func rotateLeft(v:UInt32, n:UInt32) -> UInt32 {
  16. return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
  17. }
  18. func rotateLeft(x:UInt64, n:UInt64) -> UInt64 {
  19. return (x << n) | (x >> (64 - n))
  20. }
  21. func rotateRight(x:UInt16, n:UInt16) -> UInt16 {
  22. return (x >> n) | (x << (16 - n))
  23. }
  24. func rotateRight(x:UInt32, n:UInt32) -> UInt32 {
  25. return (x >> n) | (x << (32 - n))
  26. }
  27. func rotateRight(x:UInt64, n:UInt64) -> UInt64 {
  28. return ((x >> n) | (x << (64 - n)))
  29. }
  30. func reverseBytes(value: UInt32) -> UInt32 {
  31. // rdar://18060945 - not working since Xcode6-Beta6, need to split in two variables
  32. // return = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8) | ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24);
  33. // workaround
  34. var tmp1 = ((value & 0x000000FF) << 24) | ((value & 0x0000FF00) << 8)
  35. var tmp2 = ((value & 0x00FF0000) >> 8) | ((value & 0xFF000000) >> 24)
  36. return tmp1 | tmp2
  37. }
  38. func xor(a: [UInt8], b:[UInt8]) -> [UInt8] {
  39. var xored = [UInt8](count: a.count, repeatedValue: 0)
  40. for i in 0..<xored.count {
  41. xored[i] = a[i] ^ b[i]
  42. }
  43. return xored
  44. }
  45. func perf(text: String, closure: () -> ()) {
  46. let measurementStart = NSDate();
  47. closure()
  48. let measurementStop = NSDate();
  49. let executionTime = measurementStop.timeIntervalSinceDate(measurementStart)
  50. println("\(text) \(executionTime)");
  51. }