io.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2016 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. // The I/O code below is derived from Apple's swift-protobuf project.
  16. // https://github.com/apple/swift-protobuf
  17. // BEGIN swift-protobuf derivation
  18. #if os(Linux)
  19. import Glibc
  20. #else
  21. import Darwin.C
  22. #endif
  23. enum PluginError: Error {
  24. /// Raised for any errors reading the input
  25. case readFailure
  26. }
  27. // Alias clib's write() so Stdout.write(bytes:) can call it.
  28. private let _write = write
  29. class Stdin {
  30. static func readall() throws -> Data {
  31. let fd: Int32 = 0
  32. let buffSize = 32
  33. var buff = [UInt8]()
  34. while true {
  35. var fragment = [UInt8](repeating: 0, count: buffSize)
  36. let count = read(fd, &fragment, buffSize)
  37. if count < 0 {
  38. throw PluginError.readFailure
  39. }
  40. if count < buffSize {
  41. buff += fragment[0..<count]
  42. return Data(bytes: buff)
  43. }
  44. buff += fragment
  45. }
  46. }
  47. }
  48. class Stdout {
  49. static func write(bytes: Data) {
  50. bytes.withUnsafeBytes { (p: UnsafePointer<UInt8>) -> () in
  51. _ = _write(1, p, bytes.count)
  52. }
  53. }
  54. }
  55. struct CodePrinter {
  56. private(set) var content = ""
  57. private var currentIndentDepth = 0
  58. private var currentIndent = ""
  59. private var atLineStart = true
  60. mutating func print(_ text: String...) {
  61. for t in text {
  62. for c in t.characters {
  63. if c == "\n" {
  64. content.append(c)
  65. atLineStart = true
  66. } else {
  67. if atLineStart {
  68. content.append(currentIndent)
  69. atLineStart = false
  70. }
  71. content.append(c)
  72. }
  73. }
  74. }
  75. }
  76. mutating private func resetIndent() {
  77. currentIndent = (0..<currentIndentDepth).map { Int -> String in return " " } .joined(separator:"")
  78. }
  79. mutating func indent() {
  80. currentIndentDepth += 1
  81. resetIndent()
  82. }
  83. mutating func outdent() {
  84. currentIndentDepth -= 1
  85. resetIndent()
  86. }
  87. }
  88. // END swift-protobuf derivation