Files
zhy200308 eae24000e9 优化IOS
2026-08-19 09:31:21 +08:00

42 lines
1.4 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Foundation
import CryptoKit
func sha256Hex(_ data: Data) -> String {
SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
extension Data {
/// 十六进制字符串转字节。只在测试里造光学清单时用。
init?(hexString: String) {
guard hexString.count % 2 == 0 else { return nil }
var bytes = [UInt8]()
bytes.reserveCapacity(hexString.count / 2)
var index = hexString.startIndex
while index < hexString.endIndex {
let next = hexString.index(index, offsetBy: 2)
guard let byte = UInt8(hexString[index..<next], radix: 16) else { return nil }
bytes.append(byte)
index = next
}
self.init(bytes)
}
}
/// 从管道里读一行,带超时。用来等 MockPCServer 打印 `READY <port>`。
func readReadyLine(from handle: FileHandle, timeout: TimeInterval) -> String? {
let deadline = Date().addingTimeInterval(timeout)
var buffer = Data()
while Date() < deadline {
let available = handle.availableData
if available.isEmpty {
Thread.sleep(forTimeInterval: 0.02)
continue
}
buffer.append(available)
if let index = buffer.firstIndex(of: 0x0a) {
return String(data: buffer[buffer.startIndex..<index], encoding: .utf8)
}
}
return nil
}