2
0

GRPCStatusMessageMarshaller.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 struct GRPCStatusMessageMarshaller {
  18. // See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
  19. // 0x20-0x24 and 0x26-0x7e inclusive.
  20. public static let allowedCharacters: CharacterSet = {
  21. var allowed = CharacterSet(charactersIn: Unicode.Scalar(0x20)...Unicode.Scalar(0x7e))
  22. // Remove '%' (0x25)
  23. allowed.remove(Unicode.Scalar(0x25))
  24. return allowed
  25. }()
  26. /// Adds percent encoding to the given message.
  27. ///
  28. /// - Parameter message: Message to percent encode.
  29. /// - Returns: Percent encoded string, or `nil` if it could not be encoded.
  30. public static func marshall(_ message: String) -> String? {
  31. return message.addingPercentEncoding(withAllowedCharacters: GRPCStatusMessageMarshaller.allowedCharacters)
  32. }
  33. /// Removes percent encoding from the given message.
  34. ///
  35. /// - Parameter message: Message to remove encoding from.
  36. /// - Returns: The string with percent encoding removed, or the input string if the encoding
  37. /// could not be removed.
  38. public static func unmarshall(_ message: String) -> String {
  39. return message.removingPercentEncoding ?? message
  40. }
  41. }