I'm still new to Swift, and using the methods with “Unsafe” in the title still bothers me, but I'm sure this is a useful method to call memcpy () and specify an offset for the destination and / or source address. But this only works for byte arrays, i.e. [UInt8]. Definitely not for strings, as @zaph explains.
public class SystemMisc {
public static func memoryCopy(_ destPointer : UnsafeRawPointer, _ destOffset : Int,
_ sourcePointer : UnsafeRawPointer, _ sourceOffset : Int,
_ byteLength : Int) {
memoryCopy(UnsafeMutableRawPointer(mutating: destPointer), destOffset,
sourcePointer, sourceOffset, byteLength)
}
public static func memoryCopy(_ destPointer : UnsafeMutableRawPointer, _ destOffset : Int,
_ sourcePointer : UnsafeRawPointer, _ sourceOffset : Int,
_ byteLength : Int) {
memcpy(destPointer.advanced(by: destOffset),
sourcePointer.advanced(by: sourceOffset),
byteLength)
}
}
And here is some kind of test code:
let destArray1 : [UInt8] = [ 0, 1, 2, 3 ]
let sourceArray1 : [UInt8] = [ 42, 43, 44, 45 ]
SystemMisc.memoryCopy(destArray1, 1, sourceArray1, 1, 2)
assert(destArray1[0] == 0 && destArray1[1] == 43 && destArray1[2] == 44 && destArray1[3] == 3)
var destArray2 : [UInt8] = [ 0, 1, 2, 3 ]
let sourceArray2 : [UInt8] = [ 42, 43, 44, 45 ]
let destArray2Pointer = UnsafeMutableRawPointer(&destArray2)
SystemMisc.memoryCopy(destArray2Pointer, 1, sourceArray2, 1, 2)
assert(destArray2[0] == 0 && destArray2[1] == 43 && destArray2[2] == 44 && destArray2[3] == 3)