1 //===----------------------------------------------------------------------===//
3 // This source file is part of the Swift.org open source project
5 // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
6 // Licensed under Apache License v2.0 with Runtime Library Exception
8 // See http://swift.org/LICENSE.txt for license information
9 // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
11 //===----------------------------------------------------------------------===//
15 public struct DispatchData : RandomAccessCollection {
16 public typealias Iterator = DispatchDataIterator
17 public typealias Index = Int
18 public typealias Indices = DefaultRandomAccessIndices<DispatchData>
20 public static let empty: DispatchData = DispatchData(data: _swift_dispatch_data_empty())
22 #if false /* FIXME: dragging in _TMBO (Objective-C) */
23 public enum Deallocator {
30 /// A custom deallocator
31 case custom(DispatchQueue?, @convention(block) () -> Void)
33 private var _deallocator: (DispatchQueue?, @convention(block) () -> Void) {
35 case .free: return (nil, _dispatch_data_destructor_free())
36 case .unmap: return (nil, _dispatch_data_destructor_munmap())
37 case .custom(let q, let b): return (q, b)
42 internal var __wrapped: dispatch_data_t
44 /// Initialize a `Data` with copied memory content.
46 /// - parameter bytes: A pointer to the memory. It will be copied.
47 /// - parameter count: The number of bytes to copy.
48 public init(bytes buffer: UnsafeBufferPointer<UInt8>) {
49 __wrapped = dispatch_data_create(
50 buffer.baseAddress!, buffer.count, nil, _dispatch_data_destructor_default())
52 #if false /* FIXME: dragging in _TMBO (Objective-C) */
53 /// Initialize a `Data` without copying the bytes.
55 /// - parameter bytes: A pointer to the bytes.
56 /// - parameter count: The size of the bytes.
57 /// - parameter deallocator: Specifies the mechanism to free the indicated buffer.
58 public init(bytesNoCopy bytes: UnsafeBufferPointer<UInt8>, deallocator: Deallocator = .free) {
59 let (q, b) = deallocator._deallocator
61 __wrapped = dispatch_data_create(bytes.baseAddress!, bytes.count, q?.__wrapped, b)
64 internal init(data: dispatch_data_t) {
68 public var count: Int {
69 return CDispatch.dispatch_data_get_size(__wrapped)
72 public func withUnsafeBytes<Result, ContentType>(
73 body: @noescape (UnsafePointer<ContentType>) throws -> Result) rethrows -> Result
75 var ptr: UnsafePointer<Void>? = nil
77 let data = CDispatch.dispatch_data_create_map(__wrapped, &ptr, &size)
78 defer { _fixLifetime(data) }
79 return try body(UnsafePointer<ContentType>(ptr!))
82 public func enumerateBytes(
83 block: @noescape (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Int, stop: inout Bool) -> Void)
85 _swift_dispatch_data_apply(__wrapped) { (data: dispatch_data_t, offset: Int, ptr: UnsafePointer<Void>, size: Int) in
86 let bp = UnsafeBufferPointer(start: UnsafePointer<UInt8>(ptr), count: size)
88 block(buffer: bp, byteIndex: offset, stop: &stop)
93 /// Append bytes to the data.
95 /// - parameter bytes: A pointer to the bytes to copy in to the data.
96 /// - parameter count: The number of bytes to copy.
97 public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
98 let data = dispatch_data_create(bytes, count, nil, _dispatch_data_destructor_default())
99 self.append(DispatchData(data: data))
102 /// Append data to the data.
104 /// - parameter data: The data to append to this data.
105 public mutating func append(_ other: DispatchData) {
106 let data = CDispatch.dispatch_data_create_concat(__wrapped, other.__wrapped)
110 /// Append a buffer of bytes to the data.
112 /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
113 public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
114 self.append(UnsafePointer(buffer.baseAddress!), count: buffer.count * sizeof(SourceType.self))
117 private func _copyBytesHelper(to pointer: UnsafeMutablePointer<UInt8>, from range: CountableRange<Index>) {
119 _ = CDispatch.dispatch_data_apply(__wrapped) { (data: dispatch_data_t, offset: Int, ptr: UnsafePointer<Void>, size: Int) in
120 let limit = Swift.min((range.endIndex - range.startIndex) - copiedCount, size)
121 memcpy(pointer + copiedCount, ptr, limit)
123 return copiedCount < (range.endIndex - range.startIndex)
127 /// Copy the contents of the data to a pointer.
129 /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
130 /// - parameter count: The number of bytes to copy.
131 /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
132 public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
133 _copyBytesHelper(to: pointer, from: 0..<count)
136 /// Copy a subset of the contents of the data to a pointer.
138 /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
139 /// - parameter range: The range in the `Data` to copy.
140 /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
141 public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: CountableRange<Index>) {
142 _copyBytesHelper(to: pointer, from: range)
145 /// Copy the contents of the data into a buffer.
147 /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `sizeof(DestinationType) * buffer.count` then the first N bytes will be copied into the buffer.
148 /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
149 /// - parameter buffer: A buffer to copy the data into.
150 /// - 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.
151 /// - returns: Number of bytes copied into the destination buffer.
152 public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: CountableRange<Index>? = nil) -> Int {
154 guard cnt > 0 else { return 0 }
156 let copyRange : CountableRange<Index>
158 guard !r.isEmpty else { return 0 }
159 precondition(r.startIndex >= 0)
160 precondition(r.startIndex < cnt, "The range is outside the bounds of the data")
162 precondition(r.endIndex >= 0)
163 precondition(r.endIndex <= cnt, "The range is outside the bounds of the data")
165 copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * sizeof(DestinationType.self), r.count))
167 copyRange = 0..<Swift.min(buffer.count * sizeof(DestinationType.self), cnt)
170 guard !copyRange.isEmpty else { return 0 }
172 let pointer : UnsafeMutablePointer<UInt8> = UnsafeMutablePointer<UInt8>(buffer.baseAddress!)
173 _copyBytesHelper(to: pointer, from: copyRange)
174 return copyRange.count
177 /// Sets or returns the byte at the specified index.
178 public subscript(index: Index) -> UInt8 {
180 let subdata = CDispatch.dispatch_data_copy_region(__wrapped, index, &offset)
182 var ptr: UnsafePointer<Void>? = nil
184 let map = CDispatch.dispatch_data_create_map(subdata, &ptr, &size)
185 defer { _fixLifetime(map) }
187 let pptr = UnsafePointer<UInt8>(ptr!)
188 return pptr[index - offset]
191 public subscript(bounds: Range<Int>) -> RandomAccessSlice<DispatchData> {
192 return RandomAccessSlice(base: self, bounds: bounds)
195 /// Return a new copy of the data in a specified range.
197 /// - parameter range: The range to copy.
198 public func subdata(in range: CountableRange<Index>) -> DispatchData {
199 let subrange = CDispatch.dispatch_data_create_subrange(
200 __wrapped, range.startIndex, range.endIndex - range.startIndex)
201 return DispatchData(data: subrange)
204 public func region(location: Int) -> (data: DispatchData, offset: Int) {
206 let data = CDispatch.dispatch_data_copy_region(__wrapped, location, &offset)
207 return (DispatchData(data: data), offset)
210 public var startIndex: Index {
214 public var endIndex: Index {
218 public func index(before i: Index) -> Index {
222 public func index(after i: Index) -> Index {
226 /// An iterator over the contents of the data.
228 /// The iterator will increment byte-by-byte.
229 public func makeIterator() -> DispatchData.Iterator {
230 return DispatchDataIterator(_data: self)
234 public struct DispatchDataIterator : IteratorProtocol, Sequence {
236 /// Create an iterator over the given DisaptchData
237 public init(_data: DispatchData) {
238 var ptr: UnsafePointer<Void>?
240 self._data = CDispatch.dispatch_data_create_map(_data.__wrapped, &ptr, &self._count)
241 self._ptr = UnsafePointer(ptr!)
242 self._position = _data.startIndex
245 /// Advance to the next element and return it, or `nil` if no next
248 /// - Precondition: No preceding call to `self.next()` has returned `nil`.
249 public mutating func next() -> DispatchData._Element? {
250 if _position == _count { return nil }
251 let element = _ptr[_position];
252 _position = _position + 1
256 internal let _data: dispatch_data_t
257 internal var _ptr: UnsafePointer<UInt8>
258 internal var _count: Int
259 internal var _position: DispatchData.Index
262 typealias _swift_data_applier = @convention(block) @noescape (dispatch_data_t, Int, UnsafePointer<Void>, Int) -> Bool
264 @_silgen_name("_swift_dispatch_data_apply")
265 internal func _swift_dispatch_data_apply(_ data: dispatch_data_t, _ block: _swift_data_applier)
267 @_silgen_name("_swift_dispatch_data_empty")
268 internal func _swift_dispatch_data_empty() -> dispatch_data_t
270 @_silgen_name("_swift_dispatch_data_destructor_free")
271 internal func _dispatch_data_destructor_free() -> _DispatchBlock
273 @_silgen_name("_swift_dispatch_data_destructor_munmap")
274 internal func _dispatch_data_destructor_munmap() -> _DispatchBlock
276 @_silgen_name("_swift_dispatch_data_destructor_default")
277 internal func _dispatch_data_destructor_default() -> _DispatchBlock