0

I'm using a simple extension to pack and unpack data, the code below currently still works but it's throwing me a warning and I'd like to update it to prevent issues down the line.

There are two similar questions asked about this, but I haven't been able to successfully apply what has been discusses there. So I was hoping someone could give me some insight.

The extension that's throwing the warning:

extension Data {
    var unsafeBytes : UnsafePointer<UInt8> {
        return self.withUnsafeBytes { return $0 } //'withUnsafeBytes' is deprecated: use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
    }
}

One of the functions that uses it:

func upack(_ bin: Data) -> Data {
        let unsafeBin = bin.unsafeBytes
        let output = UnsafeMutablePointer<UInt8>.allocate(capacity: 540)
        
        if (!nfc_upack(key, unsafeBin, output)) {
            log.warning("Unpacking failed")
        }
        
        return Data(bytes: output, count: 540)
    }

Edit: nfc_upack leads to https://github.com/socram8888/amiitool/blob/master/amiibo.c#L73

Like I said, currently it's working fine, but I'd like to solve this before it becomes an issue.

Prolix
  • 169
  • 7
  • Can you share api of nfc_upack, what it's parameters. – Ankit Thakur Jul 06 '20 at 17:01
  • @AnkitThakur It refers back to line 73 in this GitHub file (only difference is the name): https://github.com/socram8888/amiitool/blob/master/amiibo.c#L73 The function is part of a struct that contains `var key : UnsafeMutablePointer = UnsafeMutablePointer.allocate(capacity: 1) ` – Prolix Jul 06 '20 at 19:09

1 Answers1

0

So to resolve this warning, the actual way of implementation is like this:

let data = Data()
var output = Data(count: 540)

var satus:Bool = false
satus = output.withUnsafeMutableBytes { outputBytes in
    data.withUnsafeBytes { dataBytes in
        nfc_upack(key, unsafeBin, output)
    }
}

status is the output bool value shared by nfc_upack api. then you can check if the status is true, then output parameter will have valid value.

Ankit Thakur
  • 4,739
  • 1
  • 19
  • 35