String+Haneke.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //
  2. // String+Haneke.swift
  3. // Haneke
  4. //
  5. // Created by Hermes Pique on 8/30/14.
  6. // Copyright (c) 2014 Haneke. All rights reserved.
  7. //
  8. import Foundation
  9. extension String {
  10. func escapedFilename() -> String {
  11. return [ "\0":"%00", ":":"%3A", "/":"%2F" ]
  12. .reduce(self.components(separatedBy: "%").joined(separator: "%25")) {
  13. str, m in str.components(separatedBy: m.0).joined(separator: m.1)
  14. }
  15. }
  16. func MD5String() -> String {
  17. guard let data = self.data(using: String.Encoding.utf8) else {
  18. return self
  19. }
  20. let MD5Calculator = MD5(Array(data))
  21. let MD5Data = MD5Calculator.calculate()
  22. let resultBytes = UnsafeMutablePointer<CUnsignedChar>(mutating: MD5Data)
  23. let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.count)
  24. let MD5String = NSMutableString()
  25. for c in resultEnumerator {
  26. MD5String.appendFormat("%02x", c)
  27. }
  28. return MD5String as String
  29. }
  30. func MD5Filename() -> String {
  31. let MD5String = self.MD5String()
  32. // NSString.pathExtension alone could return a query string, which can lead to very long filenames.
  33. let pathExtension = URL(string: self)?.pathExtension ?? (self as NSString).pathExtension
  34. if pathExtension.count > 0 {
  35. return (MD5String as NSString).appendingPathExtension(pathExtension) ?? MD5String
  36. } else {
  37. return MD5String
  38. }
  39. }
  40. }