forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathData.swift
2851 lines (2544 loc) · 126 KB
/
Data.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 DEPLOYMENT_RUNTIME_SWIFT
#if !canImport(Darwin)
@inlinable // This is @inlinable as trivially computable.
internal func malloc_good_size(_ size: Int) -> Int {
return size
}
#endif
import CoreFoundation
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
#if os(Windows)
UnmapViewOfFile(mem)
#else
munmap(mem, length)
#endif
}
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) {
free(mem)
}
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
return data._isCompact()
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
import _SwiftCoreFoundationOverlayShims
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) {
return data._isCompact()
} else {
var compact = true
let len = data.length
data.enumerateBytes { (_, byteRange, stop) in
if byteRange.length != len {
compact = false
}
stop.pointee = true
}
return compact
}
}
#endif
#if os(Windows)
@usableFromInline @discardableResult
internal func __withStackOrHeapBuffer(_ size: Int, _ block: (UnsafeMutablePointer<_ConditionalAllocationBuffer>) -> Void) -> Bool {
return _withStackOrHeapBuffer(size, block)
}
#else
@inlinable @inline(__always) @discardableResult
internal func __withStackOrHeapBuffer(_ size: Int, _ block: (UnsafeMutablePointer<_ConditionalAllocationBuffer>) -> Void) -> Bool {
return _withStackOrHeapBuffer(size, block)
}
#endif
// Underlying storage representation for medium and large data.
// Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial.
// NOTE: older overlays called this class _DataStorage. The two must
// coexist without a conflicting ObjC class name, so it was renamed.
// The old name must not be used in the new runtime.
@usableFromInline
internal final class __DataStorage {
@usableFromInline static let maxSize = Int.max >> 1
@usableFromInline static let vmOpsThreshold = NSPageSize() * 4
@inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
if clear {
return calloc(1, size)
} else {
return malloc(size)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
var dest = dest_
var source = source_
var num = num_
if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
let pages = NSRoundDownToMultipleOfPageSize(num)
NSCopyMemoryPages(source!, dest, pages)
source = source!.advanced(by: pages)
dest = dest.advanced(by: pages)
num -= pages
}
if num > 0 {
memmove(dest, source!, num)
}
}
@inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
static func shouldAllocateCleared(_ size: Int) -> Bool {
return (size > (128 * 1024))
}
@usableFromInline var _bytes: UnsafeMutableRawPointer?
@usableFromInline var _length: Int
@usableFromInline var _capacity: Int
@usableFromInline var _needToZero: Bool
@usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
@usableFromInline var _offset: Int
@inlinable // This is @inlinable as trivially computable.
var bytes: UnsafeRawPointer? {
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
@discardableResult
func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
@discardableResult
func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
}
@inlinable // This is @inlinable as trivially computable.
var mutableBytes: UnsafeMutableRawPointer? {
return _bytes?.advanced(by: -_offset)
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return _capacity
}
@inlinable // This is @inlinable as trivially computable.
var length: Int {
get {
return _length
}
set {
setLength(newValue)
}
}
@inlinable // This is inlinable as trivially computable.
var isExternallyOwned: Bool {
// all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation
// anything with 0 capacity means that we have not allocated this pointer and consequently mutation is not ours to make.
return _capacity == 0
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) {
guard isExternallyOwned || newLength > _capacity else { return }
if newLength == 0 {
if isExternallyOwned {
let newCapacity = malloc_good_size(_length)
let newBytes = __DataStorage.allocate(newCapacity, false)
__DataStorage.move(newBytes!, _bytes!, _length)
_freeBytes()
_bytes = newBytes
_capacity = newCapacity
_needToZero = false
}
} else if isExternallyOwned {
let newCapacity = malloc_good_size(newLength)
let newBytes = __DataStorage.allocate(newCapacity, clear)
if let bytes = _bytes {
__DataStorage.move(newBytes!, bytes, _length)
}
_freeBytes()
_bytes = newBytes
_capacity = newCapacity
_length = newLength
_needToZero = true
} else {
let cap = _capacity
var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
if Int.max - additionalCapacity < newLength {
additionalCapacity = 0
}
var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity))
let origLength = _length
var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
var newBytes: UnsafeMutableRawPointer? = nil
if _bytes == nil {
newBytes = __DataStorage.allocate(newCapacity, allocateCleared)
if newBytes == nil {
/* Try again with minimum length */
allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength)
newBytes = __DataStorage.allocate(newLength, allocateCleared)
}
} else {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
/* Where calloc/memmove/free fails, realloc might succeed */
if newBytes == nil {
allocateCleared = false
if _deallocator != nil {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
} else {
newBytes = realloc(_bytes!, newCapacity)
}
}
/* Try again with minimum length */
if newBytes == nil {
newCapacity = malloc_good_size(newLength)
allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
if newBytes == nil {
allocateCleared = false
newBytes = realloc(_bytes!, newCapacity)
}
}
}
if newBytes == nil {
/* Could not allocate bytes */
// At this point if the allocation cannot occur the process is likely out of memory
// and Bad-Things™ are going to happen anyhow
fatalError("unable to allocate memory for length (\(newLength))")
}
if origLength < newLength && clear && !allocateCleared {
memset(newBytes!.advanced(by: origLength), 0, newLength - origLength)
}
/* _length set by caller */
_bytes = newBytes
_capacity = newCapacity
/* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */
_needToZero = !allocateCleared
}
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func _freeBytes() {
if let bytes = _bytes {
if let dealloc = _deallocator {
dealloc(bytes, length)
} else {
free(bytes)
}
}
_deallocator = nil
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stopv: Bool = false
block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv)
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func setLength(_ length: Int) {
let origLength = _length
let newLength = length
if _capacity < newLength || _bytes == nil {
ensureUniqueBufferReference(growingTo: newLength, clear: true)
} else if origLength < newLength && _needToZero {
memset(_bytes! + origLength, 0, newLength - origLength)
} else if newLength < origLength {
_needToZero = true
}
_length = newLength
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func append(_ bytes: UnsafeRawPointer, length: Int) {
precondition(length >= 0, "Length of appending bytes must not be negative")
let origLength = _length
let newLength = origLength + length
if _capacity < newLength || _bytes == nil {
ensureUniqueBufferReference(growingTo: newLength, clear: false)
}
_length = newLength
__DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
}
@inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
func get(_ index: Int) -> UInt8 {
return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func set(_ index: Int, to value: UInt8) {
ensureUniqueBufferReference()
_bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))
UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer)
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
let currentLength = _length
let resultingLength = currentLength - range.length + replacementLength
let shift = resultingLength - currentLength
let mutableBytes: UnsafeMutableRawPointer
if resultingLength > currentLength {
ensureUniqueBufferReference(growingTo: resultingLength)
_length = resultingLength
} else {
ensureUniqueBufferReference()
}
mutableBytes = _bytes!
/* shift the trailing bytes */
let start = range.location
let length = range.length
if shift != 0 {
memmove(mutableBytes + start + replacementLength, mutableBytes + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if let replacementBytes = replacementBytes {
memmove(mutableBytes + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func resetBytes(in range_: Range<Int>) {
let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound)
if range.length == 0 { return }
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity <= newLength {
ensureUniqueBufferReference(growingTo: newLength, clear: false)
}
_length = newLength
} else {
ensureUniqueBufferReference()
}
memset(_bytes!.advanced(by: range.location), 0, range.length)
}
@usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer.
init(length: Int) {
precondition(length < __DataStorage.maxSize)
var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
let clear = __DataStorage.shouldAllocateCleared(length)
_bytes = __DataStorage.allocate(capacity, clear)!
_capacity = capacity
_needToZero = !clear
_length = 0
_offset = 0
setLength(length)
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(capacity capacity_: Int = 0) {
var capacity = capacity_
precondition(capacity < __DataStorage.maxSize)
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = 0
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_offset = 0
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(bytes: UnsafeRawPointer?, length: Int) {
precondition(length < __DataStorage.maxSize)
_offset = 0
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
} else if __DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = __DataStorage.allocate(length, false)!
__DataStorage.move(_bytes!, bytes, length)
} else {
var capacity = length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
__DataStorage.move(_bytes!, bytes, length)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
precondition(length < __DataStorage.maxSize)
_offset = offset
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
if let dealloc = deallocator,
let bytes_ = bytes {
dealloc(bytes_, length)
}
} else if !copy {
_capacity = length
_length = length
_needToZero = false
_bytes = bytes
_deallocator = deallocator
} else if __DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = __DataStorage.allocate(length, false)!
__DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
} else {
var capacity = length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
__DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(immutableReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_deallocator = { _, _ in
_fixLifetime(immutableReference)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(mutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_deallocator = { _, _ in
_fixLifetime(mutableReference)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(customReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: customReference.bytes)
_capacity = 0
_needToZero = false
_length = customReference.length
_deallocator = { _, _ in
_fixLifetime(customReference)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(customMutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = customMutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = customMutableReference.length
_deallocator = { _, _ in
_fixLifetime(customMutableReference)
}
}
deinit {
_freeBytes()
}
@inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
func mutableCopy(_ range: Range<Int>) -> __DataStorage {
return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound)
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed.
func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
if range.isEmpty {
return try work(NSData()) // zero length data can be optimized as a singleton
}
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false))
}
@inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients.
@usableFromInline
func bridgedReference(_ range: Range<Int>) -> NSData {
if range.isEmpty {
return NSData() // zero length data can be optimized as a singleton
}
return __NSSwiftData(backing: self, range: range)
}
}
// NOTE: older overlays called this _NSSwiftData. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
internal class __NSSwiftData : NSData {
var _backing: __DataStorage!
var _range: Range<Data.Index>!
override var classForCoder: AnyClass {
return NSData.self
}
override init() {
fatalError()
}
private init(_correctly: Void) {
super.init()
}
convenience init(backing: __DataStorage, range: Range<Data.Index>) {
self.init(_correctly: ())
_backing = backing
_range = range
}
public required init?(coder aDecoder: NSCoder) {
fatalError("This should have been encoded as NSData.")
}
override func encode(with aCoder: NSCoder) {
// This should encode this object just like NSData does, and .classForCoder should do the rest.
super.encode(with: aCoder)
}
override var length: Int {
return _range.upperBound - _range.lowerBound
}
override var bytes: UnsafeRawPointer {
// NSData's byte pointer methods are not annotated for nullability correctly
// (but assume non-null by the wrapping macro guards). This placeholder value
// is to work-around this bug. Any indirection to the underlying bytes of an NSData
// with a length of zero would have been a programmer error anyhow so the actual
// return value here is not needed to be an allocated value. This is specifically
// needed to live like this to be source compatible with Swift3. Beyond that point
// this API may be subject to correction.
guard let bytes = _backing.bytes else {
return UnsafeRawPointer(bitPattern: 0xBAD0)!
}
return bytes.advanced(by: _range.lowerBound)
}
override func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: bytes, length: length)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@objc override
func _isCompact() -> Bool {
return true
}
#endif
#if DEPLOYMENT_RUNTIME_SWIFT
override func _providesConcreteBacking() -> Bool {
return true
}
#else
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
#endif
}
@frozen
public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection, MutableDataProtocol, ContiguousBytes {
public typealias ReferenceType = NSData
public typealias ReadingOptions = NSData.ReadingOptions
public typealias WritingOptions = NSData.WritingOptions
public typealias SearchOptions = NSData.SearchOptions
public typealias Base64EncodingOptions = NSData.Base64EncodingOptions
public typealias Base64DecodingOptions = NSData.Base64DecodingOptions
public typealias Index = Int
public typealias Indices = Range<Int>
// A small inline buffer of bytes suitable for stack-allocation of small data.
// Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible.
@usableFromInline
@frozen
internal struct InlineData {
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
@usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum
@usableFromInline var bytes: Buffer
#elseif arch(i386) || arch(arm)
@usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8) //len //enum
@usableFromInline var bytes: Buffer
#else
#error("This architecture isn't known. Add it to the 32-bit or 64-bit line.")
#endif
@usableFromInline var length: UInt8
@inlinable // This is @inlinable as trivially computable.
static func canStore(count: Int) -> Bool {
return count <= MemoryLayout<Buffer>.size
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ srcBuffer: UnsafeRawBufferPointer) {
self.init(count: srcBuffer.count)
if srcBuffer.count > 0 {
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
dstBuffer.baseAddress?.copyMemory(from: srcBuffer.baseAddress!, byteCount: srcBuffer.count)
}
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(count: Int = 0) {
assert(count <= MemoryLayout<Buffer>.size)
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
#elseif arch(i386) || arch(arm)
bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
#else
#error("This architecture isn't known. Add it to the 32-bit or 64-bit line.")
#endif
length = UInt8(count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ slice: InlineSlice, count: Int) {
self.init(count: count)
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
slice.withUnsafeBytes { srcBuffer in
dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count))
}
}
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ slice: LargeSlice, count: Int) {
self.init(count: count)
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
slice.withUnsafeBytes { srcBuffer in
dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count))
}
}
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return MemoryLayout<Buffer>.size
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return Int(length)
}
set(newValue) {
assert(newValue <= MemoryLayout<Buffer>.size)
length = UInt8(newValue)
}
}
@inlinable // This is @inlinable as trivially computable.
var startIndex: Int {
return 0
}
@inlinable // This is @inlinable as trivially computable.
var endIndex: Int {
return count
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
let count = Int(length)
return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in
return try apply(UnsafeRawBufferPointer(start: rawBuffer.baseAddress, count: count))
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
let count = Int(length)
return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in
return try apply(UnsafeMutableRawBufferPointer(start: rawBuffer.baseAddress, count: count))
}
}
@inlinable // This is @inlinable as tribially computable.
mutating func append(byte: UInt8) {
let count = self.count
assert(count + 1 <= MemoryLayout<Buffer>.size)
Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte }
self.length += 1
}
@inlinable // This is @inlinable as trivially computable.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
guard buffer.count > 0 else { return }
assert(count + buffer.count <= MemoryLayout<Buffer>.size)
let cnt = count
_ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count)
}
length += UInt8(buffer.count)
}
@inlinable // This is @inlinable as trivially computable.
subscript(index: Index) -> UInt8 {
get {
assert(index <= MemoryLayout<Buffer>.size)
precondition(index < length, "index \(index) is out of bounds of 0..<\(length)")
return Swift.withUnsafeBytes(of: bytes) { rawBuffer -> UInt8 in
return rawBuffer[index]
}
}
set(newValue) {
assert(index <= MemoryLayout<Buffer>.size)
precondition(index < length, "index \(index) is out of bounds of 0..<\(length)")
Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
rawBuffer[index] = newValue
}
}
}
@inlinable // This is @inlinable as trivially computable.
mutating func resetBytes(in range: Range<Index>) {
assert(range.lowerBound <= MemoryLayout<Buffer>.size)
assert(range.upperBound <= MemoryLayout<Buffer>.size)
precondition(range.lowerBound <= length, "index \(range.lowerBound) is out of bounds of 0..<\(length)")
if count < range.upperBound {
count = range.upperBound
}
let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
memset(rawBuffer.baseAddress!.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) {
assert(subrange.lowerBound <= MemoryLayout<Buffer>.size)
assert(subrange.upperBound <= MemoryLayout<Buffer>.size)
assert(count - (subrange.upperBound - subrange.lowerBound) + replacementLength <= MemoryLayout<Buffer>.size)
precondition(subrange.lowerBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)")
precondition(subrange.upperBound <= length, "index \(subrange.upperBound) is out of bounds of 0..<\(length)")
let currentLength = count
let resultingLength = currentLength - (subrange.upperBound - subrange.lowerBound) + replacementLength
let shift = resultingLength - currentLength
Swift.withUnsafeMutableBytes(of: &bytes) { mutableBytes in
/* shift the trailing bytes */
let start = subrange.lowerBound
let length = subrange.upperBound - subrange.lowerBound
if shift != 0 {
memmove(mutableBytes.baseAddress!.advanced(by: start + replacementLength), mutableBytes.baseAddress!.advanced(by: start + length), currentLength - start - length)
}
if replacementLength != 0 {
memmove(mutableBytes.baseAddress!.advanced(by: start), replacementBytes!, replacementLength)
}
}
count = resultingLength
}
@inlinable // This is @inlinable as trivially computable.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
Swift.withUnsafeBytes(of: bytes) {
let cnt = Swift.min($0.count, range.upperBound - range.lowerBound)
guard cnt > 0 else { return }
pointer.copyMemory(from: $0.baseAddress!.advanced(by: range.lowerBound), byteCount: cnt)
}
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
// **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8)
// Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash.
//
// This affects slices, which are InlineSlice and not InlineData:
//
// let d = Data([0xFF, 0xFF]) // InlineData
// let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice
// assert(s == d)
// assert(s.hashValue == d.hashValue)
hasher.combine(count)
Swift.withUnsafeBytes(of: bytes) {
// We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage).
let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count)
hasher.combine(bytes: bytes)
}
}
}
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
@usableFromInline internal typealias HalfInt = Int32
#elseif arch(i386) || arch(arm)
@usableFromInline internal typealias HalfInt = Int16
#else
#error("This architecture isn't known. Add it to the 32-bit or 64-bit line.")
#endif
// A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words.
// Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
@usableFromInline
@frozen
internal struct InlineSlice {
// ***WARNING***
// These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
@usableFromInline var slice: Range<HalfInt>
@usableFromInline var storage: __DataStorage
@inlinable // This is @inlinable as trivially computable.
static func canStore(count: Int) -> Bool {
return count < HalfInt.max
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ buffer: UnsafeRawBufferPointer) {
assert(buffer.count < HalfInt.max)
self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(capacity: Int) {
assert(capacity < HalfInt.max)
self.init(__DataStorage(capacity: capacity), count: 0)
}
@inlinable // This is @inlinable as a convenience initializer.
init(count: Int) {
assert(count < HalfInt.max)
self.init(__DataStorage(length: count), count: count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData) {
assert(inline.count < HalfInt.max)
self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ large: LargeSlice) {
assert(large.range.lowerBound < HalfInt.max)
assert(large.range.upperBound < HalfInt.max)
self.init(large.storage, range: large.range)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ large: LargeSlice, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.init(large.storage, range: range)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
assert(count < HalfInt.max)
self.storage = storage
slice = 0..<HalfInt(count)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.storage = storage
slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound)
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func ensureUniqueReference() {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.mutableCopy(self.range)
}
}
@inlinable // This is @inlinable as trivially computable.
var startIndex: Int {
return Int(slice.lowerBound)
}
@inlinable // This is @inlinable as trivially computable.
var endIndex: Int {
return Int(slice.upperBound)
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return storage.capacity
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func reserveCapacity(_ minimumCapacity: Int) {
ensureUniqueReference()
// the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return Int(slice.upperBound - slice.lowerBound)
}
set(newValue) {
assert(newValue < HalfInt.max)
ensureUniqueReference()
storage.length = newValue
slice = slice.lowerBound..<(slice.lowerBound + HalfInt(newValue))
}
}
@inlinable // This is @inlinable as trivially computable.
var range: Range<Int> {
get {
return Int(slice.lowerBound)..<Int(slice.upperBound)
}
set(newValue) {