UnicodeScalar+Extensions.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Sources/SwiftProtobufPluginLibrary/UnicodeScalar+Extensions.swift - Utilities for working with UnicodeScalars
  2. //
  3. // Copyright (c) 2014 - 2017 Apple Inc. and the project authors
  4. // Licensed under Apache License v2.0 with Runtime Library Exception
  5. //
  6. // See LICENSE.txt for license information:
  7. // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
  8. //
  9. // -----------------------------------------------------------------------------
  10. ///
  11. /// Internal utility functions and properties for working with UnicodeScalars.
  12. ///
  13. /// NOTE: This is a purely internal extension that provides the limited
  14. /// functionality needed to manipulate ASCII characters that are represented as
  15. /// UnicodeScalars. It does not support the full range of Unicode code points.
  16. ///
  17. // -----------------------------------------------------------------------------
  18. extension UnicodeScalar {
  19. /// True if the receiver is a numeric digit.
  20. var isASCDigit: Bool {
  21. if case "0"..."9" = self { return true }
  22. return false
  23. }
  24. /// True if the receiver is a lowercase character.
  25. var isASCLowercase: Bool {
  26. if case "a"..."z" = self { return true }
  27. return false
  28. }
  29. /// True if the receiver is an uppercase character.
  30. var isASCUppercase: Bool {
  31. if case "A"..."Z" = self { return true }
  32. return false
  33. }
  34. /// Returns the lowercased version of the receiver, or the receiver itself if
  35. /// it is not a cased character.
  36. ///
  37. /// - Precondition: The receiver is 7-bit ASCII.
  38. /// - Returns: The lowercased version of the receiver, or `self`.
  39. func ascLowercased() -> UnicodeScalar {
  40. if isASCUppercase { return UnicodeScalar(value + 0x20)! }
  41. return self
  42. }
  43. /// Returns the uppercased version of the receiver, or the receiver itself if
  44. /// it is not a cased character.
  45. ///
  46. /// - Precondition: The receiver is 7-bit ASCII.
  47. /// - Returns: The uppercased version of the receiver, or `self`.
  48. func ascUppercased() -> UnicodeScalar {
  49. if isASCLowercase { return UnicodeScalar(value - 0x20)! }
  50. return self
  51. }
  52. }