xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XUtils / System+Utils.swift
System+Utils.swift80 lines · 2.4 KiBRaw
| 1 | import Foundation |
| 2 | |
| 3 | #if canImport(System) |
| 4 | import System |
| 5 | |
| 6 | public typealias FilePath = System.FilePath |
| 7 | public typealias FileDescriptor = System.FileDescriptor |
| 8 | public typealias Errno = System.Errno |
| 9 | #else |
| 10 | import SystemPackage |
| 11 | |
| 12 | public typealias FilePath = SystemPackage.FilePath |
| 13 | public typealias FileDescriptor = SystemPackage.FileDescriptor |
| 14 | public typealias Errno = SystemPackage.Errno |
| 15 | |
| 16 | extension URL { |
| 17 | public init?(filePath: FilePath) { |
| 18 | self.init(filePath: filePath.string) |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | extension FilePath { |
| 23 | public init?(_ url: URL) { |
| 24 | guard url.isFileURL else { return nil } |
| 25 | self.init(url.path) |
| 26 | } |
| 27 | } |
| 28 | #endif |
| 29 | |
| 30 | extension FileDescriptor { |
| 31 | /// Writes every byte, waiting for capacity if the descriptor is nonblocking. |
| 32 | package func writeAllWaiting(_ bytes: UnsafeRawBufferPointer) throws { |
| 33 | var offset = 0 |
| 34 | while offset < bytes.count { |
| 35 | do { |
| 36 | // Swift System retries EINTR; retain the offset when a write is partial. |
| 37 | let count = try write(UnsafeRawBufferPointer(rebasing: bytes[offset...])) |
| 38 | guard count > 0 else { throw Errno.ioError } |
| 39 | offset += count |
| 40 | } catch let error as Errno where error == .resourceTemporarilyUnavailable || error == .wouldBlock { |
| 41 | var descriptor = pollfd(fd: rawValue, events: Int16(POLLOUT), revents: 0) |
| 42 | while true { |
| 43 | try Task.checkCancellation() |
| 44 | // periodically wake up to check for cancellation |
| 45 | let result = poll(&descriptor, 1, 100) |
| 46 | if result > 0 { break } |
| 47 | if result == -1 { |
| 48 | let error = Errno(rawValue: errno) |
| 49 | guard error != .interrupted else { continue } |
| 50 | throw error |
| 51 | } |
| 52 | } |
| 53 | // Retry write to report terminal errors (including POLLERR/POLLNVAL). |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | public enum LockMode { |
| 59 | case shared |
| 60 | case exclusive |
| 61 | |
| 62 | fileprivate var raw: CInt { |
| 63 | switch self { |
| 64 | case .shared: LOCK_SH |
| 65 | case .exclusive: LOCK_EX |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | public func tryLock(mode: LockMode) throws -> Bool { |
| 71 | if flock(rawValue, mode.raw | LOCK_NB) == 0 { |
| 72 | return true |
| 73 | } |
| 74 | let err = errno |
| 75 | if err == EWOULDBLOCK { |
| 76 | return false |
| 77 | } |
| 78 | throw Errno(rawValue: err) |
| 79 | } |
| 80 | } |