DecompressionLimit.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright 2020, 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. public struct DecompressionLimit: Equatable, Sendable {
  17. private enum Limit: Equatable, Sendable {
  18. case ratio(Int)
  19. case absolute(Int)
  20. }
  21. private let limit: Limit
  22. /// Limits decompressed payloads to be no larger than the product of the compressed size
  23. /// and `ratio`.
  24. ///
  25. /// - Parameter ratio: The decompression ratio.
  26. /// - Precondition: `ratio` must be greater than zero.
  27. public static func ratio(_ ratio: Int) -> DecompressionLimit {
  28. precondition(ratio > 0, "ratio must be greater than zero")
  29. return DecompressionLimit(limit: .ratio(ratio))
  30. }
  31. /// Limits decompressed payloads to be no larger than the given `size`.
  32. ///
  33. /// - Parameter size: The absolute size limit of decompressed payloads.
  34. /// - Precondition: `size` must not be negative.
  35. public static func absolute(_ size: Int) -> DecompressionLimit {
  36. precondition(size >= 0, "absolute size must be non-negative")
  37. return DecompressionLimit(limit: .absolute(size))
  38. }
  39. }
  40. extension DecompressionLimit {
  41. /// The largest allowed decompressed size for this limit.
  42. func maximumDecompressedSize(compressedSize: Int) -> Int {
  43. switch self.limit {
  44. case let .ratio(ratio):
  45. return ratio * compressedSize
  46. case let .absolute(size):
  47. return size
  48. }
  49. }
  50. }