Guest User

Untitled

a guest
Apr 19th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. protocol ESI {
  2. // Interpolate a segment
  3. mutating func addSegment<T>(_ t: T)
  4.  
  5. // Interpolate a literal
  6. mutating func addLiteral(_ s: String)
  7.  
  8. // Compiler will produce closure to pass to this init. Closure will consist
  9. // of calls to writeSegment and writeLiteral
  10. init(performingInterpolation: (inout Self) -> ())
  11.  
  12. // Maybe: compiler can also give the literals and number of segments to the
  13. // conformer so they can estimate a reserve capacity? Or just combined literal
  14. // lengths? Too much?
  15. init(
  16. numSegments: Int,
  17. literals: String...,
  18. performingInterpolation: (inout Self) -> ()
  19. )
  20. }
  21.  
  22. extension ESI {
  23. init(
  24. numSegments: Int,
  25. literals: String...,
  26. performingInterpolation f: (inout Self) -> ()
  27. ) {
  28. self.init(performingInterpolation: f)
  29. }
  30. }
  31.  
  32. extension ESI where Self: TextOutputStream {
  33. mutating func addSegment<T>(_ t: T) {
  34. print(t, terminator: "", to: &self)
  35. }
  36. mutating func addLiteral(_ s: String) {
  37. write(s)
  38. }
  39. }
  40.  
  41. struct MyESI {
  42. var value: String = ""
  43. }
  44.  
  45. extension MyESI: TextOutputStream {
  46. mutating func write(_ string: String) {
  47. value.append(string)
  48. }
  49. }
  50.  
  51. extension MyESI: ESI {
  52. // Let's say MyESI has some setup work it wants to do
  53. init(forInterpolation:()) { /*...*/ }
  54.  
  55. // Let's say we have tear-down work we want to do
  56. mutating func finalize() { /*...*/ }
  57.  
  58. init(performingInterpolation f: (inout MyESI) -> ()) {
  59. var ret = MyESI(forInterpolation: ())
  60. f(&ret)
  61. ret.finalize()
  62. self = ret
  63. }
  64. }
  65.  
  66. // Demonstrates what the compiler would produce for arbitary segments
  67. func exampleCompilerOutput<T, U, V>(_ t: T, _ u: U, _ v: V) -> MyESI {
  68. // return "abc\(t)def\(u)ghi\(v)jkl" as ESI
  69. return MyESI(performingInterpolation: { (esi: inout MyESI) -> () in
  70. esi.addLiteral("abc")
  71. esi.addSegment(t)
  72. esi.addLiteral("def")
  73. esi.addSegment(u)
  74. esi.addLiteral("ghi")
  75. esi.addSegment(v)
  76. esi.addLiteral("jkl")
  77. })
  78.  
  79. // Alternatively: as above, but also passing in num segments and literals
  80. }
  81.  
  82. print(exampleCompilerOutput(1,2.0,3).value) // abc1def2.0ghi3jkl
Add Comment
Please, Sign In to add comment