[swift-users] UnsafeMutablePointer on the stack?

Mike Ferenduros mike.ferenduros at gmail.com
Sun Oct 2 19:14:15 CDT 2016


You can use a local like this:
    var x: UInt32 = 0
    withUnsafePointer(to: x) { randomWordPT in
        //your existing code here
    }

Or I'm not sure if small arrays go on the heap, but

    var bytes: [UInt8] = [0,0,0,0]
    _ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
    return bytes.reduce(0) { ($0 << 8) | UInt32($1) }

reads a little nicer.

Personally I would be surprised if the malloc caused an actual measurable
performance hit tbh.

On Mon, 3 Oct 2016 at 02:15 Jean-Denis Muys via swift-users <
swift-users at swift.org> wrote:

> Hi,
>
> I have some issues using the new raw memory API. For instance, let's
> suppose I want to call the `SecRandomCopyBytes` API to generate a
> cryptographically secure random 32-bit number. The difficulty is its 3rd
> argument, which is declared as UnsafeMutablePointer<UInt8>. Here is a
> function that does that:
>
> func entropicRandom() -> UInt32 {
>
>     let randomWordPT = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
>
>
>     let _ = randomWordPT.withMemoryRebound(to: UInt8.self, capacity: 4) {
> (p: UnsafeMutablePointer<UInt8>) -> Int32 in
>
>         let result = SecRandomCopyBytes(kSecRandomDefault, MemoryLayout<
> UInt32>.size, p)
>
>         return result
>
>     }
>
>     let randomInt32 = randomWordPT[0]
>
>     randomWordPT.deallocate(capacity: 1)
>
>     return randomInt32
>
> }
>
> apparently, the calls to allocate and then deallocate suggest that there
> is some heap allocation happening behind the scene here, possibly
> malloc/free. Is that correct?
>
> If so, this is quite wasteful. Is there a way to use a local variable on
> the stack to achieve the same result?
>
> Thanks,
>
> Jean-Denis
>
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161003/5f326063/attachment.html>


More information about the swift-users mailing list