Slicing a [UInt8] into a Data without copying?


(Rick M) #1

Is it possible to make a (immutable) Data() object from a slice of a [UInt8] and avoid copying the data?

···

--
Rick Mann
rmann@latencyzero.com


(Philippe Hausler) #2

Not sure on exactly how you are wanting to use this but you could approach this like:

let bytes: [UInt8] = [ 0xC0, 0xC0, 0xA1, 0x00, 0xC0, 0xC0, 0xA1, 0x00]
let slice = bytes[0..<4]
slice.withUnsafeBytes { buffer in
    let d = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer.baseAddress!), count: buffer.count, deallocator: .none)
    // whatever you do, dont let d escape
}

···

On May 4, 2017, at 16:31, Rick Mann via swift-users <swift-users@swift.org> wrote:

Is it possible to make a (immutable) Data() object from a slice of a [UInt8] and avoid copying the data?

--
Rick Mann
rmann@latencyzero.com

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


(Rick M) #3

Thanks!

···

On May 4, 2017, at 16:44 , Philippe Hausler <phausler@apple.com> wrote:

Not sure on exactly how you are wanting to use this but you could approach this like:

let bytes: [UInt8] = [ 0xC0, 0xC0, 0xA1, 0x00, 0xC0, 0xC0, 0xA1, 0x00]
let slice = bytes[0..<4]
slice.withUnsafeBytes { buffer in
    let d = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer.baseAddress!), count: buffer.count, deallocator: .none)
    // whatever you do, dont let d escape
}

On May 4, 2017, at 16:31, Rick Mann via swift-users <swift-users@swift.org> wrote:

Is it possible to make a (immutable) Data() object from a slice of a [UInt8] and avoid copying the data?

--
Rick Mann
rmann@latencyzero.com

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

--
Rick Mann
rmann@latencyzero.com