io.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // END swift-protobuf derivation