DDLogMessageFormat.swift 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Software License Agreement (BSD License)
  2. //
  3. // Copyright (c) 2010-2025, Deusty, LLC
  4. // All rights reserved.
  5. //
  6. // Redistribution and use of this software in source and binary forms,
  7. // with or without modification, are permitted provided that the following conditions are met:
  8. //
  9. // * Redistributions of source code must retain the above copyright notice,
  10. // this list of conditions and the following disclaimer.
  11. //
  12. // * Neither the name of Deusty nor the names of its contributors may be used
  13. // to endorse or promote products derived from this software without specific
  14. // prior written permission of Deusty, LLC.
  15. #if SWIFT_PACKAGE
  16. public import CocoaLumberjack
  17. #endif
  18. @frozen
  19. public struct DDLogMessageFormat: ExpressibleByStringInterpolation {
  20. public typealias StringLiteralType = String
  21. @usableFromInline
  22. struct Storage {
  23. @usableFromInline
  24. typealias VArg = any CVarArg
  25. @usableFromInline
  26. let requiresArgumentParsing: Bool
  27. @usableFromInline
  28. var format: String
  29. @usableFromInline
  30. var args: Array<VArg> {
  31. willSet {
  32. // We only assert here to let the compiler optimize it away.
  33. // The setter will be used repeatedly during string interpolation, thus should stay fast.
  34. assert(requiresArgumentParsing || newValue.isEmpty, "Non-empty arguments always require argument parsing!")
  35. }
  36. }
  37. @usableFromInline
  38. init(requiresArgumentParsing: Bool, format: String, args: Array<VArg>) {
  39. precondition(requiresArgumentParsing || args.isEmpty, "Non-empty arguments always require argument parsing!")
  40. self.requiresArgumentParsing = requiresArgumentParsing
  41. self.format = format
  42. self.args = args
  43. }
  44. @available(*, deprecated, message: "Use initializer specifying the need for argument parsing: init(requiresArgumentParsing:format:args:)")
  45. @usableFromInline
  46. init(format: String, args: Array<VArg>) {
  47. self.init(requiresArgumentParsing: !args.isEmpty, format: format, args: args)
  48. }
  49. @usableFromInline
  50. mutating func addString(_ string: String) {
  51. format.append(string.replacingOccurrences(of: "%", with: "%%"))
  52. }
  53. @inlinable
  54. mutating func addValue(_ arg: VArg, withSpecifier specifier: String) {
  55. format.append(specifier)
  56. args.append(arg)
  57. }
  58. }
  59. @frozen
  60. public struct StringInterpolation: StringInterpolationProtocol {
  61. @usableFromInline
  62. var storage: Storage
  63. @inlinable
  64. public init(literalCapacity: Int, interpolationCount: Int) {
  65. var format = String()
  66. format.reserveCapacity(literalCapacity)
  67. var args = Array<Storage.VArg>()
  68. args.reserveCapacity(interpolationCount)
  69. storage = .init(requiresArgumentParsing: true, format: format, args: args)
  70. }
  71. @inlinable
  72. public mutating func appendLiteral(_ literal: StringLiteralType) {
  73. storage.addString(literal)
  74. }
  75. @inlinable
  76. public mutating func appendInterpolation<S: StringProtocol>(_ string: S) {
  77. storage.addValue(String(string), withSpecifier: "%@")
  78. }
  79. @inlinable
  80. public mutating func appendInterpolation(_ int: Int8) {
  81. storage.addValue(int, withSpecifier: "%c")
  82. }
  83. @inlinable
  84. public mutating func appendInterpolation(_ int: UInt8) {
  85. storage.addValue(int, withSpecifier: "%c")
  86. }
  87. @inlinable
  88. public mutating func appendInterpolation(_ int: Int16) {
  89. storage.addValue(int, withSpecifier: "%i")
  90. }
  91. @inlinable
  92. public mutating func appendInterpolation(_ int: UInt16) {
  93. storage.addValue(int, withSpecifier: "%u")
  94. }
  95. @inlinable
  96. public mutating func appendInterpolation(_ int: Int32) {
  97. storage.addValue(int, withSpecifier: "%li")
  98. }
  99. @inlinable
  100. public mutating func appendInterpolation(_ int: UInt32) {
  101. storage.addValue(int, withSpecifier: "%lu")
  102. }
  103. @inlinable
  104. public mutating func appendInterpolation(_ int: Int64) {
  105. storage.addValue(int, withSpecifier: "%lli")
  106. }
  107. @inlinable
  108. public mutating func appendInterpolation(_ int: UInt64) {
  109. storage.addValue(int, withSpecifier: "%llu")
  110. }
  111. @inlinable
  112. public mutating func appendInterpolation(_ int: Int) {
  113. #if arch(arm64) || arch(x86_64)
  114. storage.addValue(int, withSpecifier: "%lli")
  115. #else
  116. storage.addValue(int, withSpecifier: "%li")
  117. #endif
  118. }
  119. @inlinable
  120. public mutating func appendInterpolation(_ int: UInt) {
  121. #if arch(arm64) || arch(x86_64)
  122. storage.addValue(int, withSpecifier: "%llu")
  123. #else
  124. storage.addValue(int, withSpecifier: "%lu")
  125. #endif
  126. }
  127. @inlinable
  128. public mutating func appendInterpolation(_ flt: Float) {
  129. storage.addValue(flt, withSpecifier: "%f")
  130. }
  131. @inlinable
  132. public mutating func appendInterpolation(_ dbl: Double) {
  133. storage.addValue(dbl, withSpecifier: "%lf")
  134. }
  135. @inlinable
  136. public mutating func appendInterpolation(_ bool: Bool) {
  137. storage.addValue(bool, withSpecifier: "%i") // bools are printed as ints
  138. }
  139. // Move printed string out of inlinable code portion
  140. @usableFromInline
  141. func _warnReferenceConvertibleCVarArgInterpolation<Convertible: ReferenceConvertible>(_ convertible: Convertible) {
  142. print("""
  143. [WARNING]: CocoaLumberjackSwift is creating a \(DDLogMessageFormat.self) with an interpolation conforming to `CVarArg` \
  144. using the overload for `ReferenceConvertible` interpolations!
  145. Please report this as a bug, including the following snippet:
  146. ```
  147. Convertible: \(Convertible.self), ReferenceType: \(Convertible.ReferenceType.self), type(of: convertible): \(type(of: convertible))
  148. ```
  149. """)
  150. }
  151. @inlinable
  152. public mutating func appendInterpolation<Convertible: ReferenceConvertible>(_ convertible: Convertible) {
  153. if convertible is Storage.VArg {
  154. _warnReferenceConvertibleCVarArgInterpolation(convertible)
  155. }
  156. // This should be safe, sine the compiler should convert it to the reference.
  157. // swiftlint:disable:next force_cast
  158. storage.addValue(convertible as? Storage.VArg ?? convertible as! Convertible.ReferenceType, withSpecifier: "%@")
  159. }
  160. @inlinable
  161. public mutating func appendInterpolation<Obj: NSObject>(_ object: Obj) {
  162. storage.addValue(object, withSpecifier: "%@")
  163. }
  164. @_disfavoredOverload
  165. public mutating func appendInterpolation(_ any: Any) {
  166. appendInterpolation(String(describing: any))
  167. }
  168. }
  169. @usableFromInline
  170. let storage: Storage
  171. @inlinable
  172. var format: String { storage.format }
  173. @inlinable
  174. var args: Array<Storage.VArg> { storage.args }
  175. @inlinable
  176. var formatted: String {
  177. guard storage.requiresArgumentParsing else { return storage.format }
  178. return String(format: storage.format, arguments: storage.args)
  179. }
  180. @inlinable
  181. public init(stringLiteral value: StringLiteralType) {
  182. storage = .init(requiresArgumentParsing: false, format: value, args: [])
  183. }
  184. @inlinable
  185. public init(stringInterpolation: StringInterpolation) {
  186. storage = stringInterpolation.storage
  187. }
  188. @inlinable
  189. internal init(_formattedMessage: String) {
  190. storage = .init(requiresArgumentParsing: false, format: _formattedMessage, args: [])
  191. }
  192. }
  193. extension DDLogMessage {
  194. @inlinable
  195. public convenience init(_ format: DDLogMessageFormat,
  196. level: DDLogLevel,
  197. flag: DDLogFlag,
  198. context: Int = 0,
  199. file: StaticString = #file,
  200. function: StaticString = #function,
  201. line: UInt = #line,
  202. tag: Any? = nil,
  203. timestamp: Date? = nil) {
  204. self.init(format: format.format,
  205. formatted: format.formatted,
  206. level: level,
  207. flag: flag,
  208. context: context,
  209. file: String(describing: file),
  210. function: String(describing: function),
  211. line: line,
  212. tag: tag,
  213. options: [.dontCopyMessage],
  214. timestamp: timestamp)
  215. }
  216. }