2
0

CompressionMechanism.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /// Whether the compression flag in gRPC length-prefixed messages should be set or not.
  36. ///
  37. /// See `LengthPrefixedMessageReader` for the message format.
  38. public var requiresFlag: Bool {
  39. switch self {
  40. case .none:
  41. return false
  42. case .identity, .gzip, .deflate, .snappy, .unknown:
  43. return true
  44. }
  45. }
  46. /// Whether the given compression is supported.
  47. public var supported: Bool {
  48. switch self {
  49. case .identity, .none:
  50. return true
  51. case .gzip, .deflate, .snappy, .unknown:
  52. return false
  53. }
  54. }
  55. /// A string containing the supported compression mechanisms to list in the "grpc-accept-encoding" header.
  56. static let acceptEncodingHeader: String = {
  57. return CompressionMechanism
  58. .allCases
  59. .filter { $0.supported && $0.requiresFlag }
  60. .map { $0.rawValue }
  61. .joined(separator: ", ")
  62. }()
  63. }