io.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2017, 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. // The I/O code below is derived from Apple's swift-protobuf project.
  18. // https://github.com/apple/swift-protobuf
  19. // BEGIN swift-protobuf derivation
  20. #if os(Linux)
  21. import Glibc
  22. #else
  23. import Darwin.C
  24. #endif
  25. enum PluginError: Error {
  26. /// Raised for any errors reading the input
  27. case readFailure
  28. }
  29. // Alias clib's write() so Stdout.write(bytes:) can call it.
  30. private let _write = write
  31. class Stdin {
  32. static func readall() throws -> Data {
  33. let fd: Int32 = 0
  34. let buffSize = 32
  35. var buff = [UInt8]()
  36. while true {
  37. var fragment = [UInt8](repeating: 0, count: buffSize)
  38. let count = read(fd, &fragment, buffSize)
  39. if count < 0 {
  40. throw PluginError.readFailure
  41. }
  42. if count < buffSize {
  43. buff += fragment[0 ..< count]
  44. return Data(buff)
  45. }
  46. buff += fragment
  47. }
  48. }
  49. }
  50. class Stdout {
  51. static func write(bytes: Data) {
  52. bytes.withUnsafeBytes { (p: UnsafeRawBufferPointer) -> Void in
  53. _ = _write(1, p.baseAddress, p.count)
  54. }
  55. }
  56. }
  57. // END swift-protobuf derivation