Skip to content

CBOR decoding crashes when Data startIndex is non-zero #84

@Jerry-Carter

Description

@Jerry-Carter

Data operations often do not copy the underlying bytes but simple adjust the startIndex and endIndex. The CBORDecoder expects a startIndex of zero. The workaround is easy, but should be unnecessary.

let cborPlusTwoHeaderBytes = Data("F00DA3010203262001".hex)  // two extra bytes before the CBOR
let cborData = cborPlusTwoHeaderBytes[2...]  // trim off the two extra bytes; this fails
let cborSimple = Data(cborData)  // copy operation resets startIndex; this works

Here is a simple test case.

// swift-tools-version: 6.0
import PackageDescription

let package = Package(
    name: "FidoTest",
    platforms: [.macOS(.v15)],
    products: [ .executable(name: "SimpleTest", targets: ["Exercise1"]) ],
    dependencies: [ .package(url: "https://github.com/outfoxx/PotentCodables.git", from: "3.5.0") ],
    targets: [
        .executableTarget(name: "Exercise1", dependencies: [ .product(name: "PotentCodables", package: "PotentCodables")]),
    ]
)
import Foundation
import PotentCBOR

extension String {
    var hex: some Sequence<UInt8> {
        self[...].hex
    }

    var hexData: Data {
        return Data(hex)
    }
}

extension Substring {
    var hex: some Sequence<UInt8> {
        sequence(state: self, next: { remainder in
            guard remainder.count >= 2 else { return nil }
            let nextTwo = remainder.prefix(2)
            remainder.removeFirst(2)
            return UInt8(nextTwo, radix: 16)
        })
    }
}

let cborPlusTwoHeaderBytes = Data("F00DA3010203262001".hex)
let cborData = cborPlusTwoHeaderBytes[2...]

struct DecodedCBOR: Decodable {
    let x:Int
    let y:Int
    let ref:Int
    
    enum CodingKeys: String, CodingKey {
        case x = "1", y = "3", ref = "-1"
    }
}

let coordinates:DecodedCBOR
do {
    coordinates = try CBORDecoder().decode(DecodedCBOR.self, from: cborData)
} catch {
    print("EXCEPTION: \(error.localizedDescription)")
    throw error
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions