MyArchive.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // Archive.swift
  3. // Runner
  4. //
  5. // Created by Yayan Dwi on 16/04/20.
  6. // Copyright © 2020 The Chromium Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import Compression
  10. public class MyArchive {
  11. public static func zip(sourceString: String) -> [UInt8] {
  12. var sourceBuffer = Array(sourceString.utf8)
  13. let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: sourceString.count)
  14. let compressedSize = compression_encode_buffer(destinationBuffer, sourceString.count,
  15. &sourceBuffer, sourceString.count,
  16. nil,
  17. COMPRESSION_ZLIB)
  18. if compressedSize == 0 {
  19. fatalError("Encoding failed.")
  20. }
  21. let data = NSData(bytesNoCopy: destinationBuffer, length: compressedSize)
  22. var buffer = [UInt8](repeating: 0, count: data.length)
  23. data.getBytes(&buffer, length: data.length)
  24. return buffer
  25. }
  26. public static func unzip(bytes: [UInt8]) -> String {
  27. let decodedCapacity = 8_000_000
  28. let decodedDestinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: decodedCapacity)
  29. let data = Data(bytes)
  30. let decodedString = data.withUnsafeBytes {
  31. (encodedSourceBuffer: UnsafePointer<UInt8>) -> String in
  32. let decodedCharCount = compression_decode_buffer(decodedDestinationBuffer,
  33. decodedCapacity,
  34. encodedSourceBuffer,
  35. data.count,
  36. nil,
  37. COMPRESSION_ZLIB)
  38. if decodedCharCount == 0 {
  39. fatalError("Decoding failed.")
  40. }
  41. return String(cString: decodedDestinationBuffer)
  42. }
  43. return decodedString
  44. }
  45. }