/
PercentEncoding.swift
2351 lines (2107 loc) · 98.2 KB
/
PercentEncoding.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
// Copyright The swift-url Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// A set of ASCII code-points which should be percent-encoded.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or `0xC8`, to `"%C8"`),
/// and is most commonly used to escape special characters in URLs. Data is encoded using an _encode-set_, which
/// determines whether a particular ASCII byte should be encoded. Non-ASCII bytes are always percent-encoded.
///
/// To percent-encode a string or some data, use the `.percentEncoded(using:)` or `.lazy.percentEncoded(using:)`
/// functions respectively. Similarly, the `.percentDecoded()` function can be used to decode a percent-encoded string.
///
/// The URL Standard defines many encode-sets, and you may define your own by conforming to this protocol
/// and implementing the ``shouldPercentEncode(ascii:)`` method. The following example demonstrates an encode-set
/// which encodes single and double ASCII quotation marks:
///
/// ```swift
/// struct NoQuotes: PercentEncodeSet {
/// func shouldPercentEncode(ascii codePoint: UInt8) -> Bool {
/// codePoint == Character("\"").asciiValue! ||
/// codePoint == Character("'").asciiValue!
/// }
/// }
///
/// #"Quoth the Raven "Nevermore.""#.percentEncoded(using: NoQuotes())
/// // "Quoth the Raven %22Nevermore.%22"
/// "Quoth the Raven %22Nevermore.%22".percentDecoded()
/// // "Quoth the Raven "Nevermore.""
///
/// #""He's over there", said Mary"#.percentEncoded(using: NoQuotes())
/// // "%22He%27s over there%22, said Mary"
/// "%22He%27s over there%22, said Mary".percentDecoded()
/// // ""He's over there", said Mary"
/// ```
///
/// **Form-encoding** is a legacy variant of percent-encoding, which includes a ``SubstitutionMap`` that replaces
/// spaces with the "+" character. Whilst you may define encode-sets with custom substitution maps, doing so
/// is discouraged.
///
/// ## Topics
///
/// ### Encode Sets from the URL Standard
///
/// - ``WebURL/PercentEncodeSet/urlComponentSet``
/// - ``WebURL/PercentEncodeSet/formEncoding``
/// - ``WebURL/PercentEncodeSet/c0ControlSet``
/// - ``WebURL/PercentEncodeSet/userInfoSet``
/// - ``WebURL/PercentEncodeSet/pathSet``
/// - ``WebURL/PercentEncodeSet/querySet``
/// - ``WebURL/PercentEncodeSet/specialQuerySet``
/// - ``WebURL/PercentEncodeSet/fragmentSet``
/// - ``WebURL/URLEncodeSet``
///
/// ### Requirements for Custom Encode Sets
///
/// - ``WebURL/PercentEncodeSet/shouldPercentEncode(ascii:)``
///
/// ### Substitution Maps
///
/// - ``WebURL/PercentEncodeSet/substitutions-swift.property-fk3r``
/// - ``WebURL/PercentEncodeSet/Substitutions-swift.associatedtype``
/// - ``WebURL/NoSubstitutions``
/// - ``WebURL/SubstitutionMap``
///
public protocol PercentEncodeSet {
typealias _Member = _StaticMember<Self>
/// Whether or not an ASCII code-point should be percent-encoded.
///
/// If this function returns true, percent encoding will replace this byte with the ASCII string `"%XX"`, where
/// `XX` is the byte's value in hexadecimal.
///
/// ```swift
/// struct NoSpaces: PercentEncodeSet {
/// func shouldPercentEncode(ascii codePoint: UInt8) -> Bool {
/// codePoint == Character(" ").asciiValue!
/// }
/// }
///
/// "Hello, world!".percentEncoded(using: NoSpaces())
/// // "Hello,%20world!"
/// ```
///
/// If this function returns false and this encode-set includes a legacy substitution map,
/// the byte may be substituted. Otherwise, it will be copied to the output.
///
/// - parameters:
/// - codePoint: An ASCII code-point. Results for values > 127 are not specified.
///
func shouldPercentEncode(ascii codePoint: UInt8) -> Bool
/// A ``SubstitutionMap`` which may replace ASCII code-points that are not percent-encoded.
///
/// This is a legacy feature to support form-encoding; modern percent-encoding does not use substitutions.
/// Should you have reason to create a custom substitution map, please observe the following guidelines:
///
/// 1. No code-point may be both percent-encoded and substituted. For any code-point `x`, only one of the following
/// must be true:
///
/// - `substitutions.substitute(ascii: x) != nil`, or
/// - `shouldPercentEncode(ascii: x)`
///
/// 2. Substitute code-points _returned_ by `substitute(ascii:)` must be percent-encoded. In other words,
///
/// - If `y = substitutions.substitute(ascii: x)` and `y != nil`,
/// - `shouldPercentEncode(ascii: y)` must be `true`.
///
/// For example, form-encoding substitutes spaces with the "+" character.
/// It would be incorrect for that encode-set to say that the space character should be
/// both substituted and percent-encoded (#1 above), and it must ensure that _actual_ "+" characters
/// in the source data are percent-encoded (#2 above), so it is free to use "+" to encode spaces.
///
associatedtype Substitutions: SubstitutionMap = NoSubstitutions
/// The substitution map used by this encode-set.
///
/// This is a legacy feature to support form-encoding; modern percent-encoding does not use substitutions.
///
var substitutions: Substitutions { get }
}
extension PercentEncodeSet where Substitutions == NoSubstitutions {
@inlinable @inline(__always)
public var substitutions: NoSubstitutions {
NoSubstitutions()
}
}
/// A bidirectional map of ASCII code-points.
///
/// This is a legacy feature to support form-encoding; regular percent-encode sets do not use substitutions.
/// For example, form-encoding does not percent-encode ASCII spaces (0x20) as "%20", and instead replaces them
/// with a "+" (0x2B). The following example demonstrates a potential implementation of this encoding:
///
/// ```swift
/// struct FormEncoding: PercentEncodeSet {
///
/// func shouldPercentEncode(ascii codePoint: UInt8) -> Bool {
/// // Do not percent-encode spaces, substitute instead.
/// if codePoint == 0x20 { return false }
/// // Percent-encode actual "+"s in the source.
/// if codePoint == 0x2B { return true }
/// // other codepoints...
/// }
///
/// struct Substitutions: SubstitutionMap {
/// func substitute(ascii codePoint: UInt8) -> UInt8? {
/// // Substitute spaces with "+".
/// codePoint == 0x20 ? 0x2B : nil
/// }
/// func unsubstitute(ascii codePoint: UInt8) -> UInt8? {
/// // Unsubstitute "+" to space.
/// codePoint == 0x2B ? 0x20 : nil
/// }
/// }
///
/// var substitutions: Substitutions { .init() }
/// }
/// ```
///
/// Most percent-encode sets use ``NoSubstitutions`` as their substitution map.
///
/// ## Topics
///
/// ### Substitution Maps Used By URLs
///
/// - ``WebURL/SubstitutionMap/none``
/// - ``WebURL/SubstitutionMap/formEncoding``
///
/// ### Requirements for Creating a Custom Substitution Map
///
/// - ``WebURL/SubstitutionMap/substitute(ascii:)``
/// - ``WebURL/SubstitutionMap/unsubstitute(ascii:)``
///
public protocol SubstitutionMap {
typealias _Member = _StaticMember<Self>
/// Returns the substitute to use for an ASCII code-point.
///
/// In order to ensure accurate encoding, any code-points returned by this function must be percent-encoded by all
/// ``PercentEncodeSet``s which use this substitution map.
///
/// Some code-points must not be substituted:
///
/// | Code Point(s) | Values |
/// | ----------------------------| ------------- |
/// | Percent sign, `%` | `0x25` |
/// | Digits, `0-9` | `0x30...0x39` |
/// | Uppercase hex alphas, `A-F` | `0x41...0x46` |
/// | Lowercase hex alphas, `a-f` | `0x41...0x46` |
///
/// - parameters:
/// - codePoint: An ASCII code-point. Results for values > 127 are not specified.
///
/// - returns: The code-point to emit instead of `codePoint`, or `nil` if no substitution is required.
/// Substitute code-points must always be ASCII.
///
func substitute(ascii codePoint: UInt8) -> UInt8?
/// Restores a code-point from its substitute.
///
/// This function restores all code-points substituted by ``substitute(ascii:)``.
///
/// - parameters:
/// - codePoint: An ASCII code-point. Results for values > 127 are not specified.
///
/// - returns: The code-point restored from `codePoint`, or `nil` if `codePoint` is not a substitute.
/// Restored code-points must always be ASCII.
///
func unsubstitute(ascii codePoint: UInt8) -> UInt8?
/// Returns `true` if it can be trivially determined that the given source bytes do not require decoding.
///
/// For ``NoSubstitutions``, this means the bytes do not contain any "%" signs.
/// For ``formEncoding``, this means the bytes do not contain any "%" signs or "+" signs.
/// For custom substitution maps, this returns `false`.
///
func _canSkipDecoding(_ source: UnsafeBufferPointer<UInt8>) -> Bool
}
extension SubstitutionMap {
@inlinable @inline(__always)
public func _canSkipDecoding(_ source: UnsafeBufferPointer<UInt8>) -> Bool {
false
}
}
// --------------------------------------------
// MARK: - Encoding
// --------------------------------------------
/// A `Collection` which percent-encodes elements from its `Source` on-demand using a given `EncodeSet`.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or `0xC8`, to `"%C8"`),
/// and is most commonly used to escape special characters in URLs. Data is encoded using a ``PercentEncodeSet``, which
/// determines whether a particular ASCII byte should be encoded. Non-ASCII bytes are always percent-encoded.
/// The elements of this collection are guaranteed to be ASCII code-units, and hence valid UTF-8.
///
/// To encode a source collection, use the extension methods provided on `LazyCollectionProtocol`:
///
/// ```swift
/// // Lazy encoding is especially useful when writing data to a buffer,
/// // as it avoids allocating additional memory.
/// var buffer: Data = ...
/// let image: Data = ...
/// buffer.append(contentsOf: image.lazy.percentEncoded(using: .urlComponentSet))
/// // buffer = [...] "%BAt_%E0%11%22%EB%10%2C%7F" [...]
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// let bytes = "hello, world!".utf8
/// bytes.lazy.percentEncoded(using: .urlComponentSet)
/// .elementsEqual("hello%2C%20world!".utf8) // ✅
/// // ^^^ ^
/// bytes.lazy.percentEncoded(using: .formEncoding)
/// .elementsEqual("hello%2C+world%21".utf8) // ✅
/// // ^ ^^^
/// ```
///
/// Encode-sets may also include a ``SubstitutionMap``. If a code-point is not percent-encoded, the substitution map may
/// replace it with a different character. Content encoded with substitutions must be decoded using the same
/// substitution map it was created with.
///
public struct LazilyPercentEncoded<Source, EncodeSet>: Collection, LazyCollectionProtocol
where Source: Collection, Source.Element == UInt8, EncodeSet: PercentEncodeSet {
@usableFromInline
internal let source: Source
@usableFromInline
internal let encodeSet: EncodeSet
public let startIndex: Index
@inlinable
internal init(source: Source, encodeSet: EncodeSet) {
self.source = source
self.encodeSet = encodeSet
let sourceStartIndex = source.startIndex
if sourceStartIndex < source.endIndex {
self.startIndex = Index(sourceIndex: sourceStartIndex, sourceByte: source[sourceStartIndex], encodeSet: encodeSet)
} else {
self.startIndex = Index(endIndex: sourceStartIndex)
}
}
public struct Index: Equatable, Comparable {
@usableFromInline
internal var sourceIndex: Source.Index
@usableFromInline
internal var encodedByteOffset: UInt8
@usableFromInline
internal var encodedByte: _EncodedByte
@inlinable
internal init(sourceIndex: Source.Index, sourceByte: UInt8, encodeSet: EncodeSet) {
self.sourceIndex = sourceIndex
self.encodedByteOffset = 0
self.encodedByte = _EncodedByte(byte: sourceByte, encodeSet: encodeSet)
}
@inlinable
internal init(endIndex: Source.Index) {
self.sourceIndex = endIndex
self.encodedByteOffset = 0
self.encodedByte = _EncodedByte(_null: ())
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
// This uses 3 comparisons rather than 2, but generates smaller, faster code,
// because most of the time we're testing that an index is < endIndex.
if lhs.sourceIndex < rhs.sourceIndex {
return true
}
return lhs.sourceIndex == rhs.sourceIndex && lhs.encodedByteOffset < rhs.encodedByteOffset
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.sourceIndex == rhs.sourceIndex && lhs.encodedByteOffset == rhs.encodedByteOffset
}
}
@inlinable
public var endIndex: Index {
Index(endIndex: source.endIndex)
}
@inlinable
public var isEmpty: Bool {
source.isEmpty
}
@inlinable
public var underestimatedCount: Int {
source.underestimatedCount
}
@inlinable
public subscript(position: Index) -> UInt8 {
position.encodedByte[position.encodedByteOffset]
}
@inlinable
public func index(after i: Index) -> Index {
var copy = i
formIndex(after: ©)
return copy
}
@inlinable
public func formIndex(after i: inout Index) {
i.encodedByteOffset &+= 1
if i.encodedByteOffset < i.encodedByte.count {
return
}
i.encodedByteOffset = 0
guard i.sourceIndex < source.endIndex else {
return
}
source.formIndex(after: &i.sourceIndex)
guard i.sourceIndex < source.endIndex else {
return
}
i.encodedByte = _EncodedByte(byte: source[i.sourceIndex], encodeSet: encodeSet)
}
}
extension LazilyPercentEncoded: BidirectionalCollection where Source: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
var copy = i
formIndex(before: ©)
return copy
}
@inlinable
public func formIndex(before i: inout Index) {
guard i.encodedByteOffset == 0 else {
i.encodedByteOffset &-= 1
return
}
guard i.sourceIndex > startIndex.sourceIndex else {
return
}
source.formIndex(before: &i.sourceIndex)
i.encodedByte = _EncodedByte(byte: source[i.sourceIndex], encodeSet: encodeSet)
i.encodedByteOffset = i.encodedByte.count &- 1
}
}
/// A byte which has been encoded by a `PercentEncodeSet`.
///
@usableFromInline
internal struct _EncodedByte {
@usableFromInline
internal let byte: UInt8
@usableFromInline
internal let count: UInt8
@usableFromInline
internal let isEncodedOrSubstituted: Bool
@inlinable
internal init<EncodeSet>(byte: UInt8, encodeSet: EncodeSet) where EncodeSet: PercentEncodeSet {
if let asciiChar = ASCII(byte), encodeSet.shouldPercentEncode(ascii: asciiChar.codePoint) == false {
self.count = 1
if let substitute = encodeSet.substitutions.substitute(ascii: asciiChar.codePoint) {
self.byte = substitute & 0b01111_1111 // Ensure the substitute is ASCII.
self.isEncodedOrSubstituted = true
} else {
self.byte = byte
self.isEncodedOrSubstituted = false
}
} else {
self.byte = byte
self.count = 3
self.isEncodedOrSubstituted = true
}
}
@inlinable
internal init(_null: Void) {
self.byte = 0
self.count = 1
self.isEncodedOrSubstituted = false
}
@inlinable
internal subscript(position: UInt8) -> UInt8 {
if count == 1 {
assert(position == 0, "Invalid index")
return byte
} else {
assert((0..<3).contains(position), "Invalid index")
return percentEncodedCharacter(byte, offset: position)
}
}
}
extension LazilyPercentEncoded {
/// Calls `writer` for every byte in the source collection, providing it with a pointer
/// from which it may copy entire percent-encoded characters (1 or 3 bytes), and returning
/// whether or not any bytes were actually encoded or substituted.
///
/// This is used when writing a URL string, as we want to not only write the percent-encoded contents,
/// but determine whether or not percent-encoding was even necessary, in a single pass.
///
@inlinable
internal func write(to writer: (UnsafeBufferPointer<UInt8>) -> Void) -> Bool {
var didEncode = false
var i = startIndex
while i.sourceIndex < source.endIndex {
i.encodedByte = _EncodedByte(byte: source[i.sourceIndex], encodeSet: encodeSet)
if i.encodedByte.count == 1 {
withUnsafePointer(to: i.encodedByte.byte) {
writer(UnsafeBufferPointer(start: $0, count: 1))
}
didEncode = didEncode || i.encodedByte.isEncodedOrSubstituted
} else {
withPercentEncodedString(i.encodedByte.byte) { writer($0) }
didEncode = true
}
source.formIndex(after: &i.sourceIndex)
}
return didEncode
}
/// Returns the total length of the encoded UTF-8 bytes, and whether or not any code-units were altered
/// by the `EncodeSet`. The length is calculated using arithmetic which wraps on overflow.
///
/// This is useful for estimating an allocation size required to hold the contents, but **does not** eliminate
/// the need to bounds-check when writing to that allocation.
///
/// Ultimately, any user-supplied generic collection must be treated as potentially buggy,
/// including returning a different number of elements each time it is iterated.
/// It is unacceptable even for bugs like that to lead to memory-safety errors,
/// therefore this value must **only** be interpreted as an estimated/expected size,
/// and not relied upon for safety (although it is acceptable to `fatalError` if the actual size differs
/// from this expected size).
///
@inlinable @inline(never)
internal var unsafeEncodedLength: (count: UInt, needsEncoding: Bool) {
var count: UInt = 0
let needsEncoding = write { count &+= UInt($0.count) }
return (count, needsEncoding)
}
}
// Percent-encoding API.
//
// - The source data is raw bytes.
// It may be UTF-8 bytes stored in a String, or binary data in any storage type.
//
// - The result of encoding is an ASCII string.
// It is guaranteed to be ASCII, so there is little downside to having String be our eager storage type.
//
// Hence we need 2 APIs:
//
// 1. Lazy encoding (bytes -> bytes)
// Covers expert use-cases where result should not be a String.
// Useful for avoiding allocations, and chaining with lazy decoding.
//
// 2. Eager encoding to string (bytes -> string, string -> string)
//
// Naming:
//
// - When the source/result types are similar (bytes -> bytes, string -> string),
// use the base name "percentEncoded".
// - When the source/result types are different (bytes -> string),
// use "percentEncodedString".
// Lazy encoding to (ASCII) bytes.
extension LazyCollectionProtocol where Element == UInt8 {
/// Returns a `Collection` whose elements are computed lazily by percent-encoding this collection's elements.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or 0xC8, to the string "%C8"),
/// with bytes within the ASCII range being restricted by `encodeSet`.
///
/// Form-encoding (as used by HTML forms) is a legacy variant of percent-encoding which includes substitutions;
/// provide the appropriate ``SubstitutionMap`` when decoding form-encoded data to accurately recover the source contents.
///
/// ```swift
/// // Encode arbitrary data as an ASCII string.
/// let image: Data = ...
/// image.lazy.percentEncoded(using: .urlComponentSet) // ASCII bytes, decoding to "%BAt_%E0%11%22%EB%10%2C%7F..."
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// let bytes = "hello, world!".utf8
/// bytes.lazy.percentEncoded(using: .urlComponentSet)
/// .elementsEqual("hello%2C%20world!".utf8) // ✅
/// bytes.lazy.percentEncoded(using: .formEncoding)
/// .elementsEqual("hello%2C+world%21".utf8) // ✅
/// ```
///
@inlinable @inline(__always)
public func percentEncoded<EncodeSet>(using encodeSet: EncodeSet) -> LazilyPercentEncoded<Elements, EncodeSet> {
LazilyPercentEncoded(source: elements, encodeSet: encodeSet)
}
// _StaticMember variant for pre-5.5 toolchains.
/// Returns a `Collection` whose elements are computed lazily by percent-encoding this collection's elements.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or 0xC8, to the string "%C8"),
/// with bytes within the ASCII range being restricted by `encodeSet`.
///
/// Form-encoding (as used by HTML forms) is a legacy variant of percent-encoding which includes substitutions;
/// provide the appropriate ``SubstitutionMap`` when decoding form-encoded data to accurately recover the source contents.
///
/// ```swift
/// // Encode arbitrary data as an ASCII string.
/// let image: Data = ...
/// image.lazy.percentEncoded(using: .urlComponentSet) // ASCII bytes, decoding to "%BAt_%E0%11%22%EB%10%2C%7F..."
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// let bytes = "hello, world!".utf8
/// bytes.lazy.percentEncoded(using: .urlComponentSet)
/// .elementsEqual("hello%2C%20world!".utf8) // ✅
/// bytes.lazy.percentEncoded(using: .formEncoding)
/// .elementsEqual("hello%2C+world%21".utf8) // ✅
/// ```
///
@inlinable @inline(__always) @_disfavoredOverload
public func percentEncoded<EncodeSet>(
using encodeSet: EncodeSet._Member
) -> LazilyPercentEncoded<Elements, EncodeSet> {
percentEncoded(using: encodeSet.base)
}
}
// Eager encoding to String.
extension Collection where Element == UInt8 {
/// Returns an ASCII string formed by percent-encoding this collection's elements.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or 0xC8, to the string "%C8"),
/// with bytes within the ASCII range being restricted by `encodeSet`.
///
/// Form-encoding (as used by HTML forms) is a legacy variant of percent-encoding which includes substitutions;
/// provide the appropriate ``SubstitutionMap`` when decoding form-encoded data to accurately recover the source contents.
///
/// ```swift
/// // Encode arbitrary data as an ASCII string.
/// let image: Data = ...
/// image.percentEncodedString(using: .urlComponentSet) // "%BAt_%E0%11%22%EB%10%2C%7F..."
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// let bytes = "hello, world!".utf8
/// bytes.percentEncodedString(using: .urlComponentSet) == "hello%2C%20world!" // ✅
/// bytes.percentEncodedString(using: .formEncoding) == "hello%2C+world%21" // ✅
/// ```
///
@inlinable
public func percentEncodedString<EncodeSet: PercentEncodeSet>(using encodeSet: EncodeSet) -> String {
withContiguousStorageIfAvailable {
String(discontiguousUTF8: $0.boundsChecked.lazy.percentEncoded(using: encodeSet))
} ?? String(discontiguousUTF8: self.lazy.percentEncoded(using: encodeSet))
}
// _StaticMember variant for pre-5.5 toolchains.
/// Returns an ASCII string formed by percent-encoding this collection's elements.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or 0xC8, to the string "%C8"),
/// with bytes within the ASCII range being restricted by `encodeSet`.
///
/// Form-encoding (as used by HTML forms) is a legacy variant of percent-encoding which includes substitutions;
/// provide the appropriate ``SubstitutionMap`` when decoding form-encoded data to accurately recover the source contents.
///
/// ```swift
/// // Encode arbitrary data as an ASCII string.
/// let image: Data = ...
/// image.percentEncodedString(using: .urlComponentSet) // "%BAt_%E0%11%22%EB%10%2C%7F..."
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// let bytes = "hello, world!".utf8
/// bytes.percentEncodedString(using: .urlComponentSet) == "hello%2C%20world!" // ✅
/// bytes.percentEncodedString(using: .formEncoding) == "hello%2C+world%21" // ✅
/// ```
///
@inlinable @_disfavoredOverload
public func percentEncodedString<EncodeSet: PercentEncodeSet>(using encodeSet: EncodeSet._Member) -> String {
percentEncodedString(using: encodeSet.base)
}
}
extension StringProtocol {
/// Returns an ASCII string formed by percent-encoding this string's UTF-8 representation.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or 0xC8, to the string "%C8"),
/// with bytes within the ASCII range being restricted by `encodeSet`.
///
/// Form-encoding (as used by HTML forms) is a legacy variant of percent-encoding which includes substitutions;
/// provide the appropriate ``SubstitutionMap`` when decoding form-encoded data to accurately recover the source contents.
///
/// ```swift
/// // Percent-encoding can be used to escapes special characters, e.g. spaces.
/// "hello, world!".percentEncoded(using: .userInfoSet) // "hello,%20world!"
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// "/usr/bin/swift".percentEncoded(using: .urlComponentSet) // "%2Fusr%2Fbin%2Fswift"
/// "king of the 🦆s".percentEncoded(using: .formEncoding) // "king+of+the+%F0%9F%A6%86s"
/// ```
///
@inlinable
public func percentEncoded<EncodeSet: PercentEncodeSet>(using encodeSet: EncodeSet) -> String {
_withContiguousUTF8 { $0.percentEncodedString(using: encodeSet) }
}
// _StaticMember variant for pre-5.5 toolchains.
/// Returns an ASCII string formed by percent-encoding this string's UTF-8 representation.
///
/// Percent-encoding transforms arbitrary bytes to ASCII strings (e.g. the byte value 200, or 0xC8, to the string "%C8"),
/// with bytes within the ASCII range being restricted by `encodeSet`.
///
/// Form-encoding (as used by HTML forms) is a legacy variant of percent-encoding which includes substitutions;
/// provide the appropriate ``SubstitutionMap`` when decoding form-encoded data to accurately recover the source contents.
///
/// ```swift
/// // Percent-encoding can be used to escapes special characters, e.g. spaces.
/// "hello, world!".percentEncoded(using: .userInfoSet) // "hello,%20world!"
///
/// // Encode-sets determine which characters are encoded, and some perform substitutions.
/// "/usr/bin/swift".percentEncoded(using: .urlComponentSet) // "%2Fusr%2Fbin%2Fswift"
/// "king of the 🦆s".percentEncoded(using: .formEncoding) // "king+of+the+%F0%9F%A6%86s"
/// ```
///
@inlinable @_disfavoredOverload
public func percentEncoded<EncodeSet: PercentEncodeSet>(using encodeSet: EncodeSet._Member) -> String {
percentEncoded(using: encodeSet.base)
}
}
// --------------------------------------------
// MARK: - Decoding
// --------------------------------------------
/// A `Collection` which percent-decodes elements from its `Source` on-demand.
///
/// Percent-decoding transforms certain ASCII sequences to bytes (`"%AB"` to the byte value `0xAB`, or 171),
/// and is most commonly used to decode content from URLs. The elements of this collection are raw bytes,
/// potentially including NULL bytes or invalid UTF-8.
///
/// To decode a source collection containing a percent-encoded string,
/// use the extension methods provided on `LazyCollectionProtocol`:
///
/// ```swift
/// // Lazy decoding is especially useful for looking through decoded content.
/// // When used with WebURL's UTF8View, you can process encoded URL components
/// // without allocating additional memory.
/// let someURLs: [WebURL] = [
/// WebURL("https://root@example.com/")!,
/// WebURL("https://%72oot@example.com/")!,
/// WebURL("https://r%6F%6Ft@example.com/")!
/// ]
/// for url in someURLs {
/// guard let usernameUTF8 = url.utf8.username else {
/// continue // No username.
/// }
/// if usernameUTF8.lazy.percentDecoded().elementsEqual("root".utf8) {
/// throw InvalidUsernameError()
/// }
/// }
///
/// // Any Collection of bytes can be lazily decoded, including
/// // String's UTF8View, Foundation's Data, NIO's ByteBuffer, etc.
/// "%61%62%63".utf8
/// .lazy.percentDecoded()
/// .elementsEqual("abc".utf8) // ✅
/// ```
///
/// > Note: This type does not reverse substitutions made by form-encoding.
/// > Use ``LazilyPercentDecodedWithSubstitutions`` providing the ``SubstitutionMap/formEncoding``
/// > substitution map, to lazily decode form-encoded content.
///
public typealias LazilyPercentDecoded<Source> = LazilyPercentDecodedWithSubstitutions<Source, NoSubstitutions>
where Source: Collection, Source.Element == UInt8
/// A `Collection` which percent-decodes elements from its `Source` on-demand,
/// and reverses substitutions made by a ``SubstitutionMap``.
///
/// Percent-decoding transforms certain ASCII sequences to bytes (`"%AB"` to the byte value `0xAB`, or 171),
/// and is most commonly used to decode content from URLs. The elements of this collection are raw bytes,
/// potentially including NULL bytes or invalid UTF-8.
///
/// This type supports decoding content containing legacy substitutions (such as form-encoding).
/// To decode a source collection, use the extension methods provided on `LazyCollectionProtocol`:
///
/// ```swift
/// // Lazy decoding is especially useful for looking through decoded content.
/// // When used with WebURL's UTF8View, you can process encoded URL components
/// // without allocating additional memory.
/// let url = WebURL("https://example.com/?user=karl&the+m%65ssage=h%C2%A3llo+world")!
///
/// var buffer: [UInt8] = []
/// guard let queryUTF8 = url.utf8.query else {
/// return
/// }
/// // Splits the query in to key-value pairs, and lazily form-decodes the
/// // key and value without allocating.
/// for keyValuePairUTF8 in query.lazy.split("&") {
/// let (key, value) = keyValuePairUTF8.splitOnce(at: "=")
/// if key.lazy.percentDecoded(substitutions: .formEncoding).elementsEqual("the message") {
/// buffer.append(contentsOf: value.lazy.percentDecoded(substitutions: .formEncoding))
/// }
/// }
/// // buffer = "h£llo world"
/// ```
///
public struct LazilyPercentDecodedWithSubstitutions<Source, Substitutions>: Collection, LazyCollectionProtocol
where Source: Collection, Source.Element == UInt8, Substitutions: SubstitutionMap {
@usableFromInline
internal let source: Source
@usableFromInline
internal let substitutions: Substitutions
public let startIndex: Index
@inlinable
internal init(source: Source, substitutions: Substitutions) {
self.source = source
self.substitutions = substitutions
self.startIndex = Index(at: source.startIndex, in: source, subsMap: substitutions)
}
public typealias Element = UInt8
@inlinable
public var endIndex: Index {
Index(_endIndex: source.endIndex)
}
@inlinable
public var isEmpty: Bool {
source.isEmpty
}
@inlinable
public subscript(position: Index) -> Element {
assert(position != endIndex, "Attempt to read element at endIndex")
return position.byte
}
@inlinable
public func index(after i: Index) -> Index {
assert(i != endIndex, "Attempt to advance endIndex")
// Does not trap in release mode - just keeps returning 'endIndex'.
return Index(at: i.sourceRange.upperBound, in: source, subsMap: substitutions)
}
@inlinable
public func formIndex(after i: inout Index) {
assert(i != endIndex, "Attempt to advance endIndex")
// Does not trap in release mode - just keeps returning 'endIndex'.
i = Index(at: i.sourceRange.upperBound, in: source, subsMap: substitutions)
}
public struct Index: Comparable {
/// Always either 0, 1, or 3 bytes from the source:
/// - 0 bytes: `endIndex` only.
/// - 1 byte: non-encoded or substituted byte.
/// - 3 bytes: percent-encoded byte.
///
@usableFromInline
internal let sourceRange: Range<Source.Index>
@usableFromInline
internal let byte: UInt8
@usableFromInline
internal let isDecodedOrUnsubstituted: Bool
/// Creates an index referencing the given source collection's `endIndex`.
/// This index's `decodedValue` is always 0. It is meaningless and should not be read.
///
@inlinable
internal init(_endIndex i: Source.Index) {
self.sourceRange = Range(uncheckedBounds: (i, i))
self.byte = 0
self.isDecodedOrUnsubstituted = false
}
@inlinable @inline(__always)
internal init(_unsubstituting value: UInt8, range: Range<Source.Index>, subsMap: Substitutions) {
self.sourceRange = range
if let unsub = ASCII(value).flatMap({ subsMap.unsubstitute(ascii: $0.codePoint) }) {
self.byte = unsub
self.isDecodedOrUnsubstituted = true
} else {
self.byte = value
self.isDecodedOrUnsubstituted = false
}
}
/// Decodes the octet starting at the given index in the given `source` collection.
/// The index's successor may be obtained by creating another index starting at the index's `range.upperBound`.
///
/// The index which starts at `source.endIndex` is also given by `Index(endIndexOf:)`.
///
@inlinable
internal init(at i: Source.Index, in source: Source, subsMap: Substitutions) {
// The successor of endIndex is endIndex.
guard i < source.endIndex else {
self = .init(_endIndex: i)
return
}
let byte0 = source[i]
let byte1Index = source.index(after: i)
guard byte0 == ASCII.percentSign.codePoint else {
self = Index(_unsubstituting: byte0, range: Range(uncheckedBounds: (i, byte1Index)), subsMap: subsMap)
return
}
var cursor = byte1Index
guard cursor < source.endIndex, let decodedByte1 = ASCII(source[cursor])?.hexNumberValue else {
self.sourceRange = Range(uncheckedBounds: (i, byte1Index))
self.byte = byte0 // Percent-sign, should never be substituted.
self.isDecodedOrUnsubstituted = false
return
}
source.formIndex(after: &cursor)
guard cursor < source.endIndex, let decodedByte2 = ASCII(source[cursor])?.hexNumberValue else {
self.sourceRange = Range(uncheckedBounds: (i, byte1Index))
self.byte = byte0 // Percent-sign, should never be substituted.
self.isDecodedOrUnsubstituted = false
return
}
source.formIndex(after: &cursor)
self.sourceRange = Range(uncheckedBounds: (i, cursor))
self.byte = (decodedByte1 &* 16) &+ (decodedByte2)
self.isDecodedOrUnsubstituted = true
}
@inlinable
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.sourceRange.lowerBound == rhs.sourceRange.lowerBound
}
@inlinable
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.sourceRange.lowerBound < rhs.sourceRange.lowerBound
}
@inlinable
public static func > (lhs: Self, rhs: Self) -> Bool {
lhs.sourceRange.lowerBound > rhs.sourceRange.lowerBound
}
}
}
extension LazilyPercentDecodedWithSubstitutions.Index where Source: BidirectionalCollection {
/// Decodes the octet whose final code-unit precedes the given index in the given `source` collection.
/// The index's predecessor may be obtained by creating another index ending at the index's `range.lowerBound`.
///
@inlinable
internal init(endingAt i: Source.Index, in source: Source, startIndex: Self, subsMap: Substitutions) {
// The predecessor of startIndex is startIndex.
guard i > source.startIndex else {
self = startIndex
return
}
let byte2Index = source.index(before: i)
let byte2 = source[byte2Index]
guard
let byte0Index = source.index(byte2Index, offsetBy: -2, limitedBy: source.startIndex),
source[byte0Index] == ASCII.percentSign.codePoint
else {
self = Self(_unsubstituting: byte2, range: Range(uncheckedBounds: (byte2Index, i)), subsMap: subsMap)
return
}
guard
let decodedByte1 = ASCII(source[source.index(before: byte2Index)])?.hexNumberValue,
let decodedByte2 = ASCII(byte2)?.hexNumberValue
else {
self = Self(_unsubstituting: byte2, range: Range(uncheckedBounds: (byte2Index, i)), subsMap: subsMap)
return
}
self.sourceRange = Range(uncheckedBounds: (byte0Index, i))
self.byte = (decodedByte1 &* 16) &+ (decodedByte2)
self.isDecodedOrUnsubstituted = true
}
}
extension LazilyPercentDecodedWithSubstitutions: BidirectionalCollection where Source: BidirectionalCollection {
@inlinable
public func index(before i: Index) -> Index {
assert(i != startIndex, "Cannot decrement startIndex")
// Does not trap in release mode - just keeps returning 'startIndex'.
return Index(endingAt: i.sourceRange.lowerBound, in: source, startIndex: startIndex, subsMap: substitutions)
}
@inlinable
public func formIndex(before i: inout Index) {
assert(i != startIndex, "Cannot decrement startIndex")
// Does not trap in release mode - just keeps returning 'startIndex'.
i = Index(endingAt: i.sourceRange.lowerBound, in: source, startIndex: startIndex, subsMap: substitutions)
}
}
extension LazilyPercentDecodedWithSubstitutions {
/// Whether the byte at the given index has been percent-decoded or unsubstituted from the source contents.
///
/// The given index must be valid for this collection.
/// If `false`, the byte at this index is returned verbatim from the source collection.
/// If the index is ``endIndex``, this function returns `false`.
///
/// ```swift
/// let decoded = "h%65llo".utf8.lazy.percentDecoded()
///
/// var idx = decoded.startIndex
/// UnicodeScalar(decoded[idx]) // "h"
/// decoded.isByteDecodedOrUnsubstituted(at: idx) // false
///
/// decoded.formIndex(after: &idx)
/// UnicodeScalar(decoded[idx]) // "e"
/// decoded.isByteDecodedOrUnsubstituted(at: idx) // true
/// ```
///
@inlinable