Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in swift: purpose of UnsafeMutableBufferPointer

Tags:

pointers

swift

Currently looking into swift pointers.

UnsafePointer and UnsafeMutablePointer provide a pointer to a byte. By using pointer arithmetic, you can access the rest of the bytes.

Something similar can be done with a UnsafeMutableBufferPointer, which has an endIndex parameter. So what is the advantage/difference of using UnsafeMutableBufferPointer over UnsafeMutablePointer when accessing for example the bytes in NSData?

like image 897
user965972 Avatar asked Jul 19 '15 12:07

user965972


1 Answers

UnsafeMutablePointer<T> is designed for accessing a single element of type T. Its interface is designed for accessing a single scalar value.

UnsafeMutableBufferPointer<T>, on the other hand, is designed to access a group of elements of type T stored in a contiguous block of memory. Its interface is designed to access individual elements of the range, and also for treating the entire collection as a single unit (e.g. the generate method).

If you access bytes inside NSData, UnsafePointer alone is not sufficient, because you need to know the length of data. In contrast, a single UnsafeBufferPointer is sufficient to represent the data, because it provides both the initial location and the number of elements.

like image 74
Sergey Kalinichenko Avatar answered Sep 27 '22 21:09

Sergey Kalinichenko