解包可选值(由data.withUnsafeBytes(_ :)返回)有时不适用于保护性释放

时间:2018-10-25 12:59:17

标签: ios swift optional

我的卫兵let语句有问题,行为奇怪。整个代码如下。即使在guard let data = readData, let size = sizeOfData else ...readActivity(subdata: Data)不是readData的情况下,方法sizeOfData中语句nil的其他语句块也被错误执行。

代码

import Foundation

enum ActivityDataReaderError: Error {
    case activityIsReadingOtherCentral
    case bluetooth(Error?)
    case staleData
}

protocol ActivityDataReaderDelegate: class {
    func didReadActivity(data: Data)
    func didFailToReadActivity(error: ActivityDataReaderError)
}

final class ActivityDataReader {
    private var sizeOfData: Int?
    private var isOtherDeviceReading: Bool {
        // 0xFFFF
        return sizeOfData == 65535
    }
    private var readData: Data?

    var isEmpty: Bool {
        return sizeOfData == nil
    }

    weak var delegate: ActivityDataReaderDelegate?

    static func timestampValue(_ timestamp: UInt32) -> Data {
        var value = timestamp
        return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }

    func reset() {
        readData = nil
        sizeOfData = nil
        NSLog("reset() -- \(Thread.current)")
    }

    func readActivity(data: Data?, error: Error? = nil) {
        guard let data = data else {
            delegate?.didFailToReadActivity(error: .bluetooth(error))
            return
        }
        let isFirstChunk = readData == nil
        if isFirstChunk {
            let sizeData = data.subdata(in: 0..<2)
            sizeOfData = sizeData.withUnsafeBytes { $0.pointee }
            guard !isOtherDeviceReading else {
                delegate?.didFailToReadActivity(error: .activityIsReadingOtherCentral)
                return
            }
            NSLog(String("readActivity() Size of data: \(String(describing: sizeOfData))"))
            let subdata = data.subdata(in: 2..<data.count)
            readActivity(subdata: subdata)
        } else {
            readActivity(subdata: data)
        }
    }

    private func readActivity(subdata: Data) {
        if let lastReadData = readData {
            readData = lastReadData + subdata
        } else {
            readData = subdata
        }
        guard let data = readData, let size = sizeOfData else {
            NSLog("WTF? data:\(String(describing: readData)), "
                + "sizeOfData: \(String(describing: sizeOfData)), "
                + "thread: \(Thread.current)")
            assertionFailure("WTF")
            return
        }
        NSLog("subdata: \(String(describing: subdata)), "
            + "totalReadBytes: \(data.count), "
            + "size: \(size)")
        if data.count == size {
            delegate?.didReadActivity(data: data)
            reset()
        }
    }
}

测试

有时由于assertionFailure("WTF")而通过但有时崩溃的测试。

class ActivityDataServiceReaderTests: XCTestCase {
    var service: ActivityDataReader?

    override func setUp() {
        super.setUp()
        service = ActivityDataReader()
    }

    override func tearDown() {
        service = nil
        super.tearDown()
    }

    func testBufferIsNotEmpty() {
        NSLog("testBufferIsNotEmpty thread: \(Thread.current)")
        guard let service = service else { fatalError() }
        let firstDataBytes = [UInt8.min]
        let data1 = Data(bytes: [7, 0] + firstDataBytes)
        service.readActivity(data: data1)
        XCTAssertFalse(service.isEmpty)

        service.reset()
        XCTAssertTrue(service.isEmpty)
    }
}

崩溃时控制台的日志

2018-10-25 14:53:30.033573+0200 GuardBug[84042:11188210] WTF? data:Optional(1 bytes), sizeOfData: Optional(7), thread: <NSThread: 0x600003399d00>{number = 1, name = main}

环境

  • Xcode10
  • 带有旧版构建系统的swift 4.1
  • 迅速4.2

我认为,没有方法可以在方法readActivity(subdata: Data)的警卫让其他块中的其他块中执行代码。一切都在主线程上运行。我想念什么吗?有时可能会通过测试,有时会崩溃?

谢谢您的帮助。

编辑:

警卫让+ data.withUnsafeBytes的问题更狭窄:

func testGuardLet() {
    let data = Data(bytes: [7, 0, UInt8.min])
    let sizeData = data.subdata(in: 0 ..< 2)
    let size: Int? = sizeData.withUnsafeBytes { $0.pointee }
    guard let unwrappedSize = size else {
        NSLog("failure: \(size)")
        XCTFail()
        return
    }
    NSLog("success: \(unwrappedSize)")
}

日志:

2018-10-25 16:32:19.497540+0200 GuardBug[90576:11351167] failure: Optional(7)

2 个答案:

答案 0 :(得分:1)

感谢帮助:https://forums.swift.org/t/unwrapping-value-with-guard-let-sometimes-does-not-work-with-result-from-data-withunsafebytes-0-pointee/17357该行出现问题:

let size: Int? = sizeData.withUnsafeBytes { $0.pointee }

读取的数据被向下转换为可选的Int(8字节长),而sizeData本身仅2字节长。我不知道它有时可能如何工作,但是解决方案(似乎正常工作)是以一种休闲方式使用方法withUnsafeBytes

let size = sizeData.withUnsafeBytes { (pointer: UnsafePointer<UInt16>) in pointer.pointee }

返回值不是可选的,并且具有正确的类型UInt16(2字节长)。

答案 1 :(得分:0)

如果您选中Documentation,则会出现警告:

  

警告字节指针参数不应存储和使用   在调用关闭的有效期之外。

似乎您应该处理封闭体内的大小

func testGuardLet() {
        let data = Data(bytes: [7, 0, UInt8.min])
        var sizeData = data.subdata(in: 0 ..< 2)
        withUnsafeBytes(of: &sizeData) { bytes in
            print(bytes.count)
            for byte in bytes {
                print(byte)
            }
        }

        let bytes = withUnsafeBytes(of: &sizeData) { bytes in
            return bytes // BUGS ☠️☠️☠️
        }
    }