forked from swiftlang/swift-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataProtocol.swift
More file actions
376 lines (314 loc) · 15.9 KB
/
DataProtocol.swift
File metadata and controls
376 lines (314 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018-2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
@preconcurrency import Glibc
#elseif canImport(Musl)
@preconcurrency import Musl
#elseif canImport(ucrt)
import ucrt
#elseif canImport(WASILibc)
@preconcurrency import WASILibc
#elseif canImport(stdlib_h)
import stdlib_h
#endif
//===--- DataProtocol -----------------------------------------------------===//
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public protocol DataProtocol : RandomAccessCollection where Element == UInt8, SubSequence : DataProtocol {
// FIXME: Remove in favor of opaque type on `regions`.
associatedtype Regions: BidirectionalCollection where Regions.Element : DataProtocol & ContiguousBytes, Regions.Element.SubSequence : ContiguousBytes
/// A `BidirectionalCollection` of `DataProtocol` elements which compose a
/// discontiguous buffer of memory. Each region is a contiguous buffer of
/// bytes.
///
/// The sum of the lengths of the associated regions must equal `self.count`
/// (such that iterating `regions` and iterating `self` produces the same
/// sequence of indices in the same number of index advancements).
var regions: Regions { get }
/// Returns the first found range of the given data buffer.
///
/// A default implementation is given in terms of `self.regions`.
func firstRange<D: DataProtocol, R: RangeExpression>(of: D, in: R) -> Range<Index>? where R.Bound == Index
/// Returns the last found range of the given data buffer.
///
/// A default implementation is given in terms of `self.regions`.
func lastRange<D: DataProtocol, R: RangeExpression>(of: D, in: R) -> Range<Index>? where R.Bound == Index
/// Copies `count` bytes from the start of the buffer to the destination
/// buffer.
///
/// A default implementation is given in terms of `copyBytes(to:from:)`.
@discardableResult
func copyBytes(to: UnsafeMutableRawBufferPointer, count: Int) -> Int
/// Copies `count` bytes from the start of the buffer to the destination
/// buffer.
///
/// A default implementation is given in terms of `copyBytes(to:from:)`.
@discardableResult
func copyBytes<DestinationType>(to: UnsafeMutableBufferPointer<DestinationType>, count: Int) -> Int
/// Copies the bytes from the given range to the destination buffer.
///
/// A default implementation is given in terms of `self.regions`.
@discardableResult
func copyBytes<R: RangeExpression>(to: UnsafeMutableRawBufferPointer, from: R) -> Int where R.Bound == Index
/// Copies the bytes from the given range to the destination buffer.
///
/// A default implementation is given in terms of `self.regions`.
@discardableResult
func copyBytes<DestinationType, R: RangeExpression>(to: UnsafeMutableBufferPointer<DestinationType>, from: R) -> Int where R.Bound == Index
}
//===--- MutableDataProtocol ----------------------------------------------===//
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
public protocol MutableDataProtocol : DataProtocol, MutableCollection, RangeReplaceableCollection {
/// Replaces the contents of the buffer at the given range with zeroes.
///
/// A default implementation is given in terms of
/// `replaceSubrange(_:with:)`.
mutating func resetBytes<R: RangeExpression>(in range: R) where R.Bound == Index
}
//===--- DataProtocol Extensions ------------------------------------------===//
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension DataProtocol {
public func firstRange<D: DataProtocol>(of data: D) -> Range<Index>? {
return self.firstRange(of: data, in: self.startIndex ..< self.endIndex)
}
public func lastRange<D: DataProtocol>(of data: D) -> Range<Index>? {
return self.lastRange(of: data, in: self.startIndex ..< self.endIndex)
}
@discardableResult
public func copyBytes(to ptr: UnsafeMutableRawBufferPointer) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.endIndex)
}
@discardableResult
public func copyBytes<DestinationType>(to ptr: UnsafeMutableBufferPointer<DestinationType>) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.endIndex)
}
@discardableResult
public func copyBytes(to ptr: UnsafeMutableRawBufferPointer, count: Int) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.index(self.startIndex, offsetBy: count))
}
@discardableResult
public func copyBytes<DestinationType>(to ptr: UnsafeMutableBufferPointer<DestinationType>, count: Int) -> Int {
return copyBytes(to: ptr, from: self.startIndex ..< self.index(self.startIndex, offsetBy: count))
}
@discardableResult
public func copyBytes<R: RangeExpression>(to ptr: UnsafeMutableRawBufferPointer, from range: R) -> Int where R.Bound == Index {
precondition(ptr.baseAddress != nil)
let concreteRange = range.relative(to: self)
let slice = self[concreteRange]
// The type isn't contiguous, so we need to copy one region at a time.
var offset = 0
let rangeCount = distance(from: concreteRange.lowerBound, to: concreteRange.upperBound)
var amountToCopy = Swift.min(ptr.count, rangeCount)
for region in slice.regions {
guard amountToCopy > 0 else {
break
}
region.withUnsafeBytes { buffer in
let offsetPtr = UnsafeMutableRawBufferPointer(rebasing: ptr[offset...])
let buf = UnsafeRawBufferPointer(start: buffer.baseAddress, count: Swift.min(buffer.count, amountToCopy))
offsetPtr.copyMemory(from: buf)
offset += buf.count
amountToCopy -= buf.count
}
}
return offset
}
@discardableResult
public func copyBytes<DestinationType, R: RangeExpression>(to ptr: UnsafeMutableBufferPointer<DestinationType>, from range: R) -> Int where R.Bound == Index {
return self.copyBytes(to: UnsafeMutableRawBufferPointer(start: ptr.baseAddress, count: ptr.count * MemoryLayout<DestinationType>.stride), from: range)
}
private func matches<D: DataProtocol>(_ data: D, from index: Index) -> Bool {
var haystackIndex = index
var needleIndex = data.startIndex
while true {
guard self[haystackIndex] == data[needleIndex] else { return false }
haystackIndex = self.index(after: haystackIndex)
needleIndex = data.index(after: needleIndex)
if needleIndex == data.endIndex {
// i.e. needle is found.
return true
} else if haystackIndex == endIndex {
return false
}
}
}
public func firstRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? where R.Bound == Index {
let r = range.relative(to: self)
let length = data.count
if length == 0 || length > distance(from: r.lowerBound, to: r.upperBound) {
return nil
}
var position = r.lowerBound
while position < r.upperBound && distance(from: position, to: r.upperBound) >= length {
if matches(data, from: position) {
return position..<index(position, offsetBy: length)
}
position = index(after: position)
}
return nil
}
public func lastRange<D: DataProtocol, R: RangeExpression>(of data: D, in range: R) -> Range<Index>? where R.Bound == Index {
let r = range.relative(to: self)
let length = data.count
if length == 0 || length > distance(from: r.lowerBound, to: r.upperBound) {
return nil
}
var position = index(r.upperBound, offsetBy: -length)
while position >= r.lowerBound {
if matches(data, from: position) {
return position..<index(position, offsetBy: length)
}
position = index(before: position)
}
return nil
}
}
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension DataProtocol where Self : ContiguousBytes {
public func copyBytes<DestinationType, R: RangeExpression>(to ptr: UnsafeMutableBufferPointer<DestinationType>, from range: R) where R.Bound == Index {
precondition(ptr.baseAddress != nil)
let concreteRange = range.relative(to: self)
withUnsafeBytes { fullBuffer in
let adv = distance(from: startIndex, to: concreteRange.lowerBound)
let delta = distance(from: concreteRange.lowerBound, to: concreteRange.upperBound)
_ = memcpy(ptr.baseAddress!, fullBuffer.baseAddress!.advanced(by: adv), delta)
}
}
}
//===--- MutableDataProtocol Extensions -----------------------------------===//
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension MutableDataProtocol {
public mutating func resetBytes<R: RangeExpression>(in range: R) where R.Bound == Index {
let r = range.relative(to: self)
let count = distance(from: r.lowerBound, to: r.upperBound)
replaceSubrange(r, with: repeatElement(UInt8(0), count: count))
}
}
//===--- DataProtocol Conformances ----------------------------------------===//
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension Data : MutableDataProtocol {
@inlinable // This is @inlinable as trivially computable.
public var regions: CollectionOfOne<Data> {
return CollectionOfOne(self)
}
}
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension Data {
/// Copy the contents of the data to a pointer.
///
/// - 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.
@inlinable // This is @inlinable as trivially forwarding.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
precondition(count >= 0, "count of bytes to copy must not be negative")
if count == 0 { return }
_copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count))
}
@inlinable // This is @inlinable as trivially forwarding.
internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
if range.isEmpty { return }
_representation.copyBytes(to: pointer, from: range)
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - 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.
@inlinable // This is @inlinable as trivially forwarding.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: range)
}
// Copy the contents of 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.
@inlinable // This is @inlinable as generic and reasonably small.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.upperBound - r.lowerBound))
} else {
copyRange = startIndex..<(startIndex + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt))
}
guard !copyRange.isEmpty else { return 0 }
_copyBytesHelper(to: buffer.baseAddress!, from: copyRange)
return copyRange.upperBound - copyRange.lowerBound
}
}
//===--- DataProtocol Conditional Conformances ----------------------------===//
@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)
extension Slice : DataProtocol where Base : DataProtocol {
public typealias Regions = [Base.Regions.Element.SubSequence]
public var regions: [Base.Regions.Element.SubSequence] {
let sliceLowerBound = startIndex
let sliceUpperBound = endIndex
var regionUpperBound = base.startIndex
return base.regions.compactMap { (region) -> Base.Regions.Element.SubSequence? in
let regionLowerBound = regionUpperBound
regionUpperBound = base.index(regionUpperBound, offsetBy: region.count)
/*
[------ Region ------]
[--- Slice ---] =>
OR
[------ Region ------]
<= [--- Slice ---]
*/
if sliceLowerBound >= regionLowerBound && sliceUpperBound <= regionUpperBound {
let regionRelativeSliceLowerBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceLowerBound))
let regionRelativeSliceUpperBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceUpperBound))
return region[regionRelativeSliceLowerBound..<regionRelativeSliceUpperBound]
}
/*
[--- Region ---] =>
[------ Slice ------]
OR
<= [--- Region ---]
[------ Slice ------]
*/
if regionLowerBound >= sliceLowerBound && regionUpperBound <= sliceUpperBound {
return region[region.startIndex..<region.endIndex]
}
/*
[------ Region ------]
[------ Slice ------]
*/
if sliceLowerBound >= regionLowerBound && sliceLowerBound <= regionUpperBound {
let regionRelativeSliceLowerBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceLowerBound))
return region[regionRelativeSliceLowerBound..<region.endIndex]
}
/*
[------ Region ------]
[------ Slice ------]
*/
if regionLowerBound >= sliceLowerBound && regionLowerBound <= sliceUpperBound {
let regionRelativeSliceUpperBound = region.index(region.startIndex, offsetBy: base.distance(from: regionLowerBound, to: sliceUpperBound))
return region[region.startIndex..<regionRelativeSliceUpperBound]
}
/*
[--- Region ---]
[--- Slice ---]
OR
[--- Region ---]
[--- Slice ---]
*/
return nil
}
}
}