forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataProtocol.swift
293 lines (248 loc) · 12.3 KB
/
DataProtocol.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 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
//
//===----------------------------------------------------------------------===//
//===--- DataProtocol -----------------------------------------------------===//
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 ----------------------------------------------===//
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 ------------------------------------------===//
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)
}
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 rangeCount = distance(from: r.lowerBound, to: r.upperBound)
if rangeCount < data.count {
return nil
}
var haystackIndex = r.lowerBound
let haystackEnd = index(r.upperBound, offsetBy: -data.count)
while haystackIndex < haystackEnd {
var compareIndex = haystackIndex
var needleIndex = data.startIndex
let needleEnd = data.endIndex
var matched = true
while compareIndex < haystackEnd && needleIndex < needleEnd {
if self[compareIndex] != data[needleIndex] {
matched = false
break
}
needleIndex = data.index(after: needleIndex)
compareIndex = index(after: compareIndex)
}
if matched {
return haystackIndex..<compareIndex
}
haystackIndex = index(after: haystackIndex)
}
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 rangeCount = distance(from: r.lowerBound, to: r.upperBound)
if rangeCount < data.count {
return nil
}
var haystackIndex = r.upperBound
let haystackStart = index(r.lowerBound, offsetBy: data.count)
while haystackIndex > haystackStart {
var compareIndex = haystackIndex
var needleIndex = data.endIndex
let needleStart = data.startIndex
var matched = true
while compareIndex > haystackStart && needleIndex > needleStart {
if self[compareIndex] != data[needleIndex] {
matched = false
break
}
needleIndex = data.index(before: needleIndex)
compareIndex = index(before: compareIndex)
}
if matched {
return compareIndex..<haystackIndex
}
haystackIndex = index(before: haystackIndex)
}
return nil
}
}
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 -----------------------------------===//
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 Conditional Conformances ----------------------------===//
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
}
}
}