Swift & ldquo; Array & rdquo; memory allocation, plus toggle display

advertisements

NOTE: See amended post below re: Hardware mirroring

I have written two Swift functions that toggle the display mirroring in OSX. Both work; the difference between them is just syntax when dealing with pointers. For the convenience of those interested in learning how to toggle mirroring in Swift, I have included the text of the playground file below.

My question is about memory allocation. Here is the section of interest:

toggleMirroringUgly

    // allocate space for array
    let displayListPtr = displayIDListPtr.alloc(Int(displayCount)) //see typealias above
    // fill the list
    postError(CGGetActiveDisplayList(displayCount, displayListPtr, &activeCount))

toggleMirroring

    // allocate space for list of displays
    var displayIDList = Array<CGDirectDisplayID>(count: Int(displayCount), repeatedValue: kCGNullDirectDisplay)
    // fill the list
    postError(CGGetActiveDisplayList(displayCount, &displayIDList, &activeCount))

CGGetActiveDisplayList is a low-level function call that relies on data being arranged in consecutive memory locations. I am reasonably confident that “alloc” from the ugly version is contiguous. Empirically, it seems that the “Array(…)” call is also contiguous, but can I rely on that always being true (e.g., if the number of displays grows)? Is this assumption about the Swift array initializer poor form?


Here’s all the code; apologies for formatting issues. Note that only one of the two functions should be called; otherwise, you’ll end up where you started.

//: Playground - noun: a place where people can play

import Cocoa

// apparently not defined in Swift version of SDK 10.11 (XCode 7.3.1), so add manually
let kCGNullDirectDisplay = CGDirectDisplayID(0)
let kCGDirectMainDisplay = CGMainDisplayID()        // not used here, just for the record

let maxDisplays:UInt32 = 20    // not used
var onlineCount:UInt32 = 0     // not used

func postError(error : CGError){
    if error != CGError.Success {
        print("got an error")
    }
}

// this toggles all active displays, online or not
func toggleMirroring(){
    var displayCount:UInt32 = 0
    var activeCount:UInt32 = 0
    //var onlineCount:UInt32 = 0      //not used

    //get count of active displays (by passing nil to CGGetActiveDisplayList
    postError(CGGetActiveDisplayList(0, nil, &displayCount))

    if displayCount < 2 { return }  // no point in any mirroring functions

    //***
    // allocate space for list of displays
    var displayIDList = Array<CGDirectDisplayID>(count: Int(displayCount), repeatedValue: kCGNullDirectDisplay)

    // fill the list
    postError(CGGetActiveDisplayList(displayCount, &displayIDList, &activeCount))
    //***

    // determine if mirroring is active
    // hack to convert from boolean_t (aka UInt32) to swift's bool
    let displaysMirrored = CGDisplayIsInMirrorSet(CGMainDisplayID()) != 0

    // set master based on current mirroring state
    // if mirroring, master = null, if not, master = main display
    let master = (true == displaysMirrored) ? kCGNullDirectDisplay : CGMainDisplayID()

    // start the configuration
    var configRef:CGDisplayConfigRef = nil  //swift 3 syntax

    postError(CGBeginDisplayConfiguration(&configRef));

    for i in 0..<Int(displayCount) {
        let currentDisplay = CGDirectDisplayID(displayIDList[i])
        if CGMainDisplayID() != currentDisplay {
        CGConfigureDisplayMirrorOfDisplay(configRef, currentDisplay, master);
        }
    }

    if (false){     // change to true in order to execute the toggle
        postError(CGCompleteDisplayConfiguration (configRef,CGConfigureOption.Permanently))
    }

// The first entry in the list of active displays is the main display. In case of mirroring, the first entry is the largest drawable display or, if all are the same size, the display with the greatest pixel depth.
// The "Permanently" option might not survive reboot when run from playground, but does when run in an application
}

func toggleMirroringUgly(){
// just to decrease eye strain
typealias displayIDListPtr = UnsafeMutablePointer<CGDirectDisplayID>
typealias configurationRefPtr = UnsafeMutablePointer<CGDisplayConfigRef>

//get count of active displays (by passing nil to CGGetActiveDisplayList
postError(CGGetActiveDisplayList(0, nil, &displayCount))

if displayCount < 2 { return }  // no point in any mirroring functions

// ***
// allocate space for array
let displayListPtr = displayIDListPtr.alloc(Int(displayCount)) //see typealias above
// fill the list
postError(CGGetActiveDisplayList(displayCount, displayListPtr, &activeCount))
// ***

// determine if mirroring is active
// hack to convert from boolean_t (aka UInt32) to swift's bool
let displaysMirrored = CGDisplayIsInMirrorSet(CGMainDisplayID()) != 0
// set master based on current mirroring state
// if mirroring master = null, if not, master = main display
let master = (true == displaysMirrored) ? kCGNullDirectDisplay : CGMainDisplayID()

// make room for the configuration reference
let configRefPtr = configurationRefPtr.alloc(1)     //see typealias above
// start the configuration
postError(CGBeginDisplayConfiguration (configRefPtr));

for i in 0..<displayCount {
    let currentDisplay = CGDirectDisplayID(displayListPtr[Int(i)])
    if CGMainDisplayID() != currentDisplay {
        CGConfigureDisplayMirrorOfDisplay(configRefPtr[0], currentDisplay, master);
    }
}

if (false){         //change to true in order to flip the mirroring
    // make it happen
    postError(CGCompleteDisplayConfiguration (configRefPtr[0],CGConfigureOption.Permanently));
}
// The first entry in the list of active displays is the main display. In case of mirroring, the first entry is the largest drawable display or, if all are the same size, the display with the greatest pixel depth.
// The "Permanently" option might not survive reboot when run from playground, but does when run in an application
}

toggleMirroring()


Arrays don't necessarily use contiguous storage. There is a ContiguousArray type which you can use if you are so inclined, but you'll still need to deal with the possible difference between your maximum size and the actual size returned after the final call to CGGetActiveDisplayList.

One way of cleaning this up might be to make a custom convenience initializer for Array:

extension Array {

    init<Size: IntegerType>(
        fillingBufferOfSize maxSize: Size,
        @noescape fillBuffer: (buffer: UnsafeMutablePointer<Element>, count: inout Size) throws -> ()) rethrows
    {
        let maxSizeAsInt = Int(maxSize.toIntMax())
        let buf = UnsafeMutablePointer<Element>.alloc(maxSizeAsInt)
        defer { buf.dealloc(maxSizeAsInt) }

        var actualCount: Size = 0
        try fillBuffer(buffer: buf, count: &actualCount)

        self.init(UnsafeBufferPointer(start: buf, count: Int(actualCount.toIntMax())))
    }

}

Then you can use Array(fillingBufferOfSize: ...):

var maxActive: UInt32 = 0
CGGetActiveDisplayList(0, nil, &maxActive)

let displays = Array(fillingBufferOfSize: maxActive) { (buffer, count) in
    CGGetActiveDisplayList(maxActive, buffer, &count)
}