How do you copy bytes into an UnsafeMutableRawBufferPointer at a specific offset?

UnsafeMutableRawBufferPointer has three specific methods for reading and writing memory:

  • load(fromByteOffset:as:)
  • storeBytes(of:toByteOffset:as:)
  • copyMemory(from:)

Why does copyMemory not take a byteOffset or have an equivalent that does?

How do I copy all or part of the memory referenced by an UnsafeBufferPointer<UInt8>, UnsafeRawBufferPointer, UnsafePointer<UInt8> or UnsafeRawPointer into another buffer at a given offset?

e.x.: I want to concatenate specific ranges of multiple buffers into a single, contiguous buffer.

I'm able to achieve the outcome I want by using a for loop and subscript indexing to copy elements over byte-by-byte but figure there must be better way.

Unfortunately, UnsafeMutableRawBufferPointer is not its own Slice-type. However, you can use the UMRBP.init(rebasing: Slice<UMRBP>) initialiser to make a new buffer over a slice of an existing one.

let slice = UnsafeMutableRawBufferPointer(rebasing: x[5...10])
slice.copyMemory(...)
1 Like

Just create a new one:

let pointer = UnsafeMutableRawBufferPointer(rebasing: originalPointer[offset...])
3 Likes