A byte buffer in memory.
The `Data` value type allows simple byte buffers to take on the behavior of Foundation objects.
You can create empty or pre-populated buffers from a variety of sources and later add or remove bytes.
You can filter and sort the content, or compare against other buffers. You can manipulate subranges
of bytes and iterate over some or all of them.
`Data` bridges to the `NSData` class and its mutable subclass, `NSMutableData`. You can use these
interchangeably in code that interacts with Objective-C APIs.
Creates data by reading from the specified URL.
- parameter url: The `URL` to read.
- parameter options: Options for the read operation. Default value is `[]`.
- throws: An error in the Cocoa domain, if `url` cannot be read.
Sets a region of the data buffer to 0.
If `range` exceeds the bounds of the data, then the data is resized to fit.
- parameter range: The range in the data to set to `0`.
Creates a data buffer with memory content without copying the bytes.
If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.
- parameter bytes: A pointer to the bytes.
- parameter count: The size of the bytes.
- parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
Initialize a `Data` by adopting a reference type.
You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation.
If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass.
- parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`.
get · iOS 8.0+
customMirror
TypeScript
get customMirror(): SDKHandle
Swift declaration
var customMirror: Mirror { get }
The custom mirror for this instance.
If this type has value semantics, the mirror should be unaffected by
subsequent mutations of the instance.
method · iOS 8.0+
makeIterator
TypeScript
makeIterator(): Data_Iterator
Swift declaration
func makeIterator() -> Data.Iterator
Returns an iterator over the contents of the data.
The iterator will increment byte-by-byte.
Initialize a `Data` from a Base-64, UTF-8 encoded `Data`.
Returns nil when the input is not recognized as valid Base-64.
- parameter base64Data: Base-64, UTF-8 encoded input data.
- parameter options: Decoding options. Default value is `[]`.
Initialize a `Data` from a Base-64 encoded String using the given options.
Returns nil when the input is not recognized as valid Base-64.
- parameter base64String: The string to parse.
- parameter options: Encoding options. Default value is `[]`.
Enumerates the contents of the data's buffer.
In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontinuously. In those cases, this function invokes the closure for each contiguous region of bytes.
- parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`.
Removes the specified subrange of elements from the collection.
var bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"]
bugs.removeSubrange(1...3)
print(bugs)
// Prints "["Aphid", "Earwig"]"
Calling this method may invalidate any existing indices for use with this
collection.
- Parameter bounds: The subrange of the collection to remove. The bounds
of the range must be valid indices of the collection.
- Complexity: O(*n*), where *n* is the length of the collection.
mutating func replaceSubrange<SourceType>(_ subrange: Range<Data.Index>, with buffer: UnsafeBufferPointer<SourceType>)
Replaces a region of bytes in the data with new bytes from a buffer.
This will resize the data if required, to fit the entire contents of `buffer`.
- precondition: The bounds of `subrange` must be valid indices of the collection.
- parameter subrange: The range in the data to replace.
- parameter buffer: The replacement bytes.
func withUnsafeBytes<E, ResultType>(_ body: (UnsafeRawBufferPointer) throws(E) -> ResultType) throws(E) -> ResultType where E : Error, ResultType : ~Copyable
Calls the given closure with the contents of underlying storage.
- note: Calling `withUnsafeBytes` multiple times does not guarantee that
the same buffer pointer will be passed in every time.
- warning: The buffer argument to the body should not be stored or used
outside of the lifetime of the call to the closure.
Clients should prefer the `withBytes` function to this one, because
`withBytes` uses the non-escapable type `RawSpan` to ensure that the
buffer argument is not stored outside of the closure.
Returns a Base-64 encoded string.
- parameter options: The options to use for the encoding. Default value is `[]`.
- returns: The Base-64 encoded string.
Mutate the bytes in the data.
This function assumes that you are mutating the contents.
- warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
func withContiguousStorageIfAvailable<E, ResultType>(_ body: (UnsafeBufferPointer<UInt8>) throws(E) -> ResultType) throws(E) -> ResultType? where E : Error, ResultType : ~Copyable
Executes a closure on the sequence’s contiguous storage.
This method calls `body(buffer)`, where `buffer` is a pointer to the
collection’s contiguous storage. If the contiguous storage doesn't exist,
the collection creates it. If the collection doesn’t support an internal
representation in a form of contiguous storage, the method doesn’t call
`body` --- it immediately returns `nil`.
The optimizer can often eliminate bounds- and uniqueness-checking
within an algorithm. When that fails, however, invoking the same
algorithm on the `buffer` argument may let you trade safety for speed.
Successive calls to this method may provide a different pointer on each
call. Don't store `buffer` outside of this method.
A `Collection` that provides its own implementation of this method
must provide contiguous storage to its elements in the same order
as they appear in the collection. This guarantees that it's possible to
generate contiguous mutable storage to any of its subsequences by slicing
`buffer` with a range formed from the distances to the subsequence's
`startIndex` and `endIndex`, respectively.
- Parameters:
- body: A closure that receives an `UnsafeBufferPointer` to the
sequence's contiguous storage.
- Returns: The value returned from `body`, unless the sequence doesn't
support contiguous storage, in which case the method ignores `body` and
returns `nil`.
Creates data with copied memory content.
- parameter bytes: A pointer to the memory. It will be copied.
- parameter count: The number of bytes to copy.
Find the given `Data` in the content of this `Data`.
- parameter dataToFind: The data to be searched for.
- parameter options: Options for the search. Default value is `[]`.
- parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
- returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
- precondition: `range` must be in the bounds of the Data.
Writes the contents of the data buffer to a location.
- parameter url: The location to write the data into.
- parameter options: Options for writing the data. Default value is `[]`.
- throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
Append a buffer of bytes to the data.
- parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
method · iOS 8.0+
append
TypeScript
append88050(byte: number): void
Swift declaration
mutating func append(_ byte: UInt8)
Adds an element to the end of the collection.
If the collection does not have sufficient capacity for another element,
additional storage is allocated before appending `newElement`. The
following example adds a new number to an array of integers:
var numbers = [1, 2, 3, 4, 5]
numbers.append(100)
print(numbers)
// Prints "[1, 2, 3, 4, 5, 100]"
- Parameter newElement: The element to append to the collection.
- Complexity: O(1) on average, over many calls to `append(_:)` on the
same collection.
Creates a data buffer with copied memory content using a buffer pointer.
- parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
Creates a data buffer with copied memory content using a mutable buffer pointer.
- parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
method · iOS 8.0+
insert
TypeScript
insert(newElement: number, i: number): void
Swift declaration
mutating func insert(_ newElement: UInt8, at i: Data.Index)
Inserts a new element into the collection at the specified position.
The new element is inserted before the element currently at the
specified index. If you pass the collection's `endIndex` property as
the `index` parameter, the new element is appended to the
collection.
var numbers = [1, 2, 3, 4, 5]
numbers.insert(100, at: 3)
numbers.insert(200, at: numbers.endIndex)
print(numbers)
// Prints "[1, 2, 3, 100, 4, 5, 200]"
Calling this method may invalidate any existing indices for use with this
collection.
- Parameter newElement: The new element to insert into the collection.
- Parameter i: The position at which to insert the new element.
`index` must be a valid index into the collection.
- Complexity: O(*n*), where *n* is the length of the collection. If
`i == endIndex`, this method is equivalent to `append(_:)`.
Removes and returns the element at the specified position.
All the elements following the specified position are moved to close the
gap. This example removes the middle element from an array of
measurements.
var measurements = [1.2, 1.5, 2.9, 1.2, 1.6]
let removed = measurements.remove(at: 2)
print(measurements)
// Prints "[1.2, 1.5, 1.2, 1.6]"
Calling this method may invalidate any existing indices for use with this
collection.
- Parameter i: The position of the element to remove. `index` must be
a valid index of the collection that is not equal to the collection's
end index.
- Returns: The removed element.
- Complexity: O(*n*), where *n* is the length of the collection.
get · iOS 8.0+
indices
TypeScript
get indices(): SDKHandle
Swift declaration
var indices: Range<Int> { get }
The indices that are valid for subscripting the collection, in ascending
order.
A collection's `indices` property can hold a strong reference to the
collection itself, causing the collection to be nonuniquely referenced.
If you mutate the collection while iterating over its indices, a strong
reference can result in an unexpected copy of the collection. To avoid
the unexpected copy, use the `index(after:)` method starting with
`startIndex` to produce indices instead.
var c = MyFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex {
c[i] /= 5
i = c.index(after: i)
}
// c == MyFancyCollection([2, 4, 6, 8, 10])
get · iOS 8.0+
regions
TypeScript
get regions(): "count" | SDKHandle
Swift declaration
var regions: CollectionOfOne<Data> { get }
A collection of buffers that make up the whole of the type conforming to a data protocol.
method · iOS 8.0+
subdata
TypeScript
subdata(range: SDKHandle): ArrayBuffer
Swift declaration
func subdata(in range: Range<Data.Index>) -> Data
Returns a new copy of the data in a specified range.
- parameter range: The range to copy.
method · iOS 8.0+
advanced
TypeScript
advanced(amount: number): ArrayBuffer
Swift declaration
func advanced(by amount: Int) -> Data
Returns a new data buffer created by removing the given number of bytes from the front of the original data.
Creates an empty data buffer of a specified size.
This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
This method sets the `count` of the data to 0.
If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
- parameter capacity: The size of the data.
get · iOS 8.0+
endIndex
TypeScript
get endIndex(): number
Swift declaration
var endIndex: Data.Index { get }
The end `Index` into the data.
This is the "one-past-the-end" position—that is, the position one greater than the last valid subscript argument.
method · iOS 8.0+
copyBytes
TypeScript
copyBytesToFrom(buffer: unknown[], range?: (SDKHandle) | null): number
Swift declaration
func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Data.Index>? = nil) -> Int
Copies the bytes in a range from the data into a buffer.
This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
- precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
- parameter buffer: A buffer to copy the data into.
- parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
- returns: Number of bytes copied into the destination buffer.
func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Data.Index>)
Copies a subset of the contents of the data to memory.
- parameter pointer: A pointer to the buffer you wish to copy the bytes into.
- parameter range: The range in the `Data` to copy.
- warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
Copies the contents of the data to memory.
- parameter pointer: A pointer to the buffer you wish to copy the bytes into.
- parameter count: The number of bytes to copy.
- warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
Removes all elements from the collection.
Calling this method may invalidate any existing indices for use with this
collection.
- Parameter keepCapacity: Pass `true` to request that the collection
avoid releasing its storage. Retaining the collection's storage can
be a useful optimization when you're planning to grow the collection
again. The default value is `false`.
- Complexity: O(*n*), where *n* is the length of the collection.
Initialize a `Data` with a repeating byte pattern
- parameter repeatedValue: A byte to initialize the pattern
- parameter count: The number of bytes the data initially contains initialized to the repeatedValue
init · iOS 8.0+
init
TypeScript
static init(): ArrayBuffer
Swift declaration
init()
Creates an empty data buffer.
init · iOS 8.0+
init
TypeScript
static init77651(data: ArrayBuffer): ArrayBuffer
Swift declaration
init(_ data: Data)
subscript · iOS 8.0+
subscript
TypeScript
subscript(bounds: SDKHandle): ArrayBuffer
Swift declaration
subscript(bounds: Range<Data.Index>) -> Data { get set }
Accesses the bytes at the specified range of indexes.