CompressionMechanism.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. public enum CompressionError: Error {
  18. case unsupported(CompressionMechanism)
  19. }
  20. /// The mechanism to use for message compression.
  21. public enum CompressionMechanism: String, CaseIterable {
  22. // No compression was indicated.
  23. case none
  24. // Compression indicated via a header.
  25. case gzip
  26. case deflate
  27. case snappy
  28. // This is the same as `.none` but was indicated via a "grpc-encoding" and may be listed
  29. // in the "grpc-accept-encoding" header. If this is the compression mechanism being used
  30. // then the compression flag should be indicated in length-prefxied messages (see
  31. // `LengthPrefixedMessageReader`).
  32. case identity
  33. // Compression indicated via a header, but not one listed in the specification.
  34. case unknown
  35. init(value: String?) {
  36. self = value.map { CompressionMechanism(rawValue: $0) ?? .unknown } ?? .none
  37. }
  38. /// Whether the compression flag in gRPC length-prefixed messages should be set or not.
  39. ///
  40. /// See `LengthPrefixedMessageReader` for the message format.
  41. public var requiresFlag: Bool {
  42. switch self {
  43. case .none:
  44. return false
  45. case .identity, .gzip, .deflate, .snappy, .unknown:
  46. return true
  47. }
  48. }
  49. /// Whether the given compression is supported.
  50. public var supported: Bool {
  51. switch self {
  52. case .identity, .none:
  53. return true
  54. case .gzip, .deflate, .snappy, .unknown:
  55. return false
  56. }
  57. }
  58. /// A string containing the supported compression mechanisms to list in the "grpc-accept-encoding" header.
  59. static let acceptEncodingHeader: String = {
  60. return CompressionMechanism
  61. .allCases
  62. .filter { $0.supported && $0.requiresFlag }
  63. .map { $0.rawValue }
  64. .joined(separator: ", ")
  65. }()
  66. }