File: URL_ObjC.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (781 lines) | stat: -rw-r--r-- 31,151 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024-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 FOUNDATION_FRAMEWORK

internal import _ForSwiftFoundation

@objc
extension NSURL {

    /// `encodingInvalidCharacters: false` is equivalent to `CFURLCreateWithString`.
    ///
    /// `encodingInvalidCharacters: true` is equivalent to `CFURLCreateWithBytes`.
    ///
    /// `forceBaseURL` is used for compatibility-mode `CFURLCreateAbsoluteURLWithBytes`.
    /// Usually, we drop the base URL if the relative string contains a scheme, but in this specific case,
    /// we need to keep the base URL around until with call `.compatibilityAbsoluteURL`,
    /// which has special behavior for a relative and base URL with the same scheme.
    static func _cfurlWith(string: String, encoding: CFStringEncoding, relativeToURL base: URL?, encodingInvalidCharacters: Bool, forceBaseURL: Bool) -> NSURL? {
        let encoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(encoding))
        guard let url = _SwiftURL(stringOrEmpty: string, relativeTo: base, encodingInvalidCharacters: encodingInvalidCharacters, encoding: encoding, compatibility: true, forceBaseURL: forceBaseURL) else { return nil }
        return _NSSwiftURL(url: url)
    }

    /// Equivalent to `+[NSURL URLWithString:relativeToURL:encodingInvalidCharacters:]`
    static func _urlWith(string: String, relativeToURL base: URL?, encodingInvalidCharacters: Bool) -> NSURL? {
        guard let url = _SwiftURL(stringOrEmpty: string, relativeTo: base, encodingInvalidCharacters: encodingInvalidCharacters) else { return nil }
        return _NSSwiftURL(url: url)
    }

    /// Equivalent to `+[NSURL URLWithDataRepresentation:relativeToURL:]` or
    /// `+[NSURL absoluteURLWithDataRepresentation:relativeToURL:]` based
    /// on the value of `isAbsolute`.
    ///
    /// Uses the same parsing logic as `CFURLCreateWithBytes`.
    static func _urlWith(dataRepresentation: Data, relativeToURL base: URL?, isAbsolute: Bool) -> NSURL? {
        guard let url = _SwiftURL(dataRepresentation: dataRepresentation, relativeTo: base, isAbsolute: isAbsolute) else { return nil }
        return _NSSwiftURL(url: url)
    }

    /// Equivalent to `+[NSURL fileURLWithPath:relativeToURL:]`
    static func _fileURLWith(path: String, relativeToURL base: URL?) -> NSURL? {
        if path.isEmpty {
            return base as NSURL?
        }
        let directoryHint: URL.DirectoryHint = path.utf8.last == ._slash ? .isDirectory : .checkFileSystem
        let url = _SwiftURL(filePath: path, directoryHint: directoryHint, relativeTo: base)
        return _NSSwiftURL(url: url)
    }

    /// Equivalent to `+[NSURL fileURLWithPath:isDirectory:relativeToURL:]`
    static func _fileURLWith(path: String, isDirectory: Bool, relativeToURL base: URL?) -> NSURL? {
        if path.isEmpty {
            return base as NSURL?
        }
        let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
        let url = _SwiftURL(filePath: path, directoryHint: directoryHint, relativeTo: base)
        return _NSSwiftURL(url: url)
    }

    /// Equivalent to `CFURLCreateWithFileSystemPathRelativeToBase`.
    static func _fileURLWith(path: String, pathStyle: CFURLPathStyle, isDirectory: Bool, relativeToURL base: URL?) -> NSURL? {
        if path.isEmpty {
            return base as NSURL?
        }
        let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
        let url = _SwiftURL(filePath: path, pathStyle: pathStyle.swiftValue, directoryHint: directoryHint, relativeTo: base)
        return _NSSwiftURL(url: url)
    }

}


@objc(_NSSwiftURL)
internal class _NSSwiftURL: _NSURLBridge, @unchecked Sendable {
    let url: _SwiftURL
    let string: String

    // Important flags for NS/CFURL-specific logic
    let isDecomposable: Bool
    let hasNetLocation: Bool
    let hasPath: Bool

    init(url: _SwiftURL) {
        self.url = url

        // Store the string here to prevent a premature
        // release when it's bridged to an NS or CFString.
        self.string = url._parseInfo.urlString

        self.isDecomposable = url.isDecomposable
        self.hasNetLocation = (url._parseInfo.netLocationRange?.isEmpty == false)
        self.hasPath = self.isDecomposable && (!url._parseInfo.path.isEmpty || self.hasNetLocation)
        super.init()
    }

    override var classForCoder: AnyClass {
        NSURL.self
    }

    override static var supportsSecureCoding: Bool { true }

    required init?(coder: NSCoder) {
        fatalError("Only NSURL should be encoded in an archive")
    }

    override func isEqual(_ object: Any?) -> Bool {
        if let other = object as? _NSSwiftURL {
            return url == other.url
        } else if let other = object as? NSURL {
            return url == other._trueSelf()._swiftURL
        } else {
            return false
        }
    }

    // Note: copy(with:) is just a retain in NSURL

    override var hash: Int {
        return url.hashValue
    }

    override var description: String {
        return url.description
    }

    override var dataRepresentation: Data {
        return url.dataRepresentation
    }

    override var absoluteString: String? {
        guard !relativeString.isEmpty else { return baseURL?.absoluteString ?? "" } // Compatibility behavior
        return url.absoluteString
    }

    override var relativeString: String {
        return string
    }

    override var baseURL: URL? {
        return url.baseURL
    }

    override var absoluteURL: URL? {
        guard baseURL != nil else { return URL(self) }
        guard !relativeString.isEmpty else { return baseURL } // Compatibility behavior
        #if !NO_FILESYSTEM
        if let baseURL, baseURL.isFileReferenceURL(), !baseURL.hasDirectoryPath {
            guard let baseFilePathURL = (baseURL as NSURL).filePathURL else {
                return nil
            }
            return _SwiftURL(string: relativeString, relativeTo: baseFilePathURL)?.absoluteURL
        }
        #endif
        return url.absoluteURL
    }

    override var scheme: String? {
        url.scheme
    }

    // Note: This is NOT the same as CFURLCopyResourceSpecifier.
    override var resourceSpecifier: String? {
        guard scheme != nil && baseURL == nil else {
            return relativeString
        }
        // We have a scheme and no base
        guard isDecomposable else {
            return _cfurlResourceSpecifier
        }
        var result: String?
        if let _netLocation {
            result = "//" + _netLocation
        }
        if let path = _relativePath(true) {
            result = (result ?? "") + path
        }
        if let _cfurlResourceSpecifier {
            result = (result ?? "") + _cfurlResourceSpecifier
        }
        return result
    }

    override var user: String? {
        url.user
    }

    override var password: String? {
        url.password
    }

    override var host: String? {
        url.host
    }

    override var port: NSNumber? {
        url.port as NSNumber?
    }

    override var path: String? {
        guard isDecomposable else {
            return nil
        }
        if isFileURL {
            return _fileSystemPath()
        } else {
            return url.path
        }
    }

    #if !NO_FILESYSTEM
    private func filePath(for fileReferencePath: String) -> String? {
        var fileReferencePath = fileReferencePath
        return fileReferencePath.withUTF8 { buffer -> String? in
            guard buffer.starts(with: URL.fileIDPrefix) else {
                return nil
            }
            let volumeIDStart = URL.fileIDPrefix.count
            guard let volumeIDEnd = buffer[volumeIDStart...].firstIndex(of: ._dot) else {
                return nil
            }
            let volumeIDStr = String(decoding: buffer[volumeIDStart..<volumeIDEnd], as: UTF8.self)
            guard let volumeID = Int64(volumeIDStr) else {
                return nil
            }
            let fileIDStart = volumeIDEnd + 1
            let fileIDEnd = buffer[fileIDStart...].firstIndex(of: ._slash) ?? buffer.endIndex
            let fileIDStr = String(decoding: buffer[fileIDStart..<fileIDEnd], as: UTF8.self)
            let fileID = Int64(fileIDStr) ?? Int64(0)
            guard let path = __CFURLCreatePathForFileID(volumeID, fileID) as String?, !path.isEmpty else {
                return nil
            }
            guard let urlPath = RFC3986Parser.percentEncode(path, component: .path) else {
                return nil
            }
            let fullPath = urlPath + String(decoding: buffer[fileIDEnd...], as: UTF8.self)
            if let resolveFlags = query?._queryResolveFlags(),
               resolveFlags != 0 {
                return fullPath._insertingPathResolveFlags(resolveFlags)
            }
            return fullPath
        }
    }
    #endif

    private func _fileSystemPath(_ pathStyle: URL.PathStyle = URL.defaultPathStyle, resolveAgainstBase: Bool = true) -> String? {
        guard hasPath else {
            return resolveAgainstBase ? baseURL?.fileSystemPath(style: pathStyle, resolveAgainstBase: true, compatibility: true) : nil
        }
        guard !url._parseInfo.path.isEmpty else {
            if resolveAgainstBase, let baseURL {
                return baseURL.fileSystemPath(style: pathStyle, resolveAgainstBase: true, compatibility: true).deletingLastPathComponent()
            }
            return ""
        }
        #if !NO_FILESYSTEM
        if (!resolveAgainstBase || baseURL == nil) && isFileReferenceURL() {
            guard let fileReferencePath = filePath(for: url.relativePath(percentEncoded: true)) else {
                return nil
            }
            return _SwiftURL.fileSystemPath(for: fileReferencePath, style: pathStyle, compatibility: true)
        }
        #endif
        return url.fileSystemPath(style: pathStyle, resolveAgainstBase: resolveAgainstBase, compatibility: true)
    }

    override var relativePath: String? {
        return _fileSystemPath(resolveAgainstBase: false)
    }

    override var query: String? {
        guard isDecomposable else {
            return nil
        }
        return url.query
    }

    override var fragment: String? {
        guard isDecomposable else {
            return nil
        }
        return url.fragment
    }

    override var hasDirectoryPath: Bool {
        if url.hasDirectoryPath {
            return true
        }
        return url.path.isEmpty && baseURL?.hasDirectoryPath ?? false
    }

    override var isFileURL: Bool {
        url.isFileURL
    }

    override var standardized: URL? {
        return url.standardized ?? URL(self)
    }

    #if !NO_FILESYSTEM
    override func isFileReferenceURL() -> Bool {
        url.isFileReferenceURL()
    }
    #endif

    // Note: fileReferenceURL() calls into NSURL since CFURL is needed

    // Note: filePathURL calls into NSURL since CFURL is needed

    // Used by CFURL, which expects "" on empty path
    override var _lastPathComponent: String? {
        #if !NO_FILESYSTEM
        if isFileReferenceURL(), let filePathURL {
            return (filePathURL as NSURL)._lastPathComponent
        }
        #endif
        guard hasPath else {
            return ""
        }
        let result = url.lastPathComponent
        if result == "/" && url._parseInfo.path != "/" { return "" }
        return result
    }

    // NSURL and CFURL share exact behavior for this method.
    override var deletingLastPathComponent: URL? {
        #if !NO_FILESYSTEM
        if isFileReferenceURL() {
            return filePathURL?.deletingLastPathComponent()
        }
        #endif
        guard hasPath else {
            return nil
        }
        if url.path == "/" || url.path == "/." || url.lastPathComponent == ".." {
            return url.appending(path: "../", directoryHint: .isDirectory)
        }
        if url.lastPathComponent == "." {
            var comp = URLComponents(parseInfo: url._parseInfo)
            let newPath = comp.percentEncodedPath._droppingTrailingSlashes.dropLast() + "../"
            comp.percentEncodedPath = String(newPath)
            if let result = comp.url(relativeTo: baseURL) {
                return result
            }
        }
        return url.deletingLastPathComponent() ?? URL(self)
    }

    // NSURL and CFURL share exact behavior for this method.
    override var deletingPathExtension: URL? {
        #if !NO_FILESYSTEM
        if isFileReferenceURL() {
            return filePathURL?.deletingPathExtension()
        }
        #endif
        guard hasPath else {
            return nil
        }
        return url.deletingPathExtension() ?? URL(self)
    }

}

// MARK: - Internal overrides for NSURL

extension _NSSwiftURL {

    // Don't override these appending methods directly so we can
    // check input and throw an exception in ObjC if necessary.

    // NSURL and CFURL share exact behavior for this method.
    override func _URL(byAppendingPathComponent pathComponent: String, isDirectory: Bool, encodingSlashes: Bool) -> URL? {
        if let nulIndex = pathComponent.utf8.firstIndex(of: 0),
           !pathComponent[nulIndex...].utf8.allSatisfy({ $0 == 0 }) {
            return nil
        }
        guard hasPath else {
            return nil
        }
        var url = url
        #if !NO_FILESYSTEM
        if isFileReferenceURL(), let filePathSwiftURL = filePathURL?._swiftURL  {
            url = filePathSwiftURL
        }
        #endif
        let directoryHint: URL.DirectoryHint = isDirectory ? .isDirectory : .notDirectory
        return url.appending(path: pathComponent, directoryHint: directoryHint, encodingSlashes: encodingSlashes, compatibility: true)
    }

    // NSURL and CFURL share exact behavior for this method.
    override func _URL(byAppendingPathExtension pathExtension: String) -> URL? {
        guard !pathExtension.isEmpty else {
            return self as URL
        }
        guard hasPath else {
            return nil
        }
        var url = url
        #if !NO_FILESYSTEM
        if isFileReferenceURL() {
            guard let filePathSwiftURL = filePathURL?._swiftURL else {
                return nil
            }
            url = filePathSwiftURL
        }
        #endif
        return url.appendingPathExtension(pathExtension, compatibility: true) ?? URL(self)
    }

}

// MARK: - Internal overrides for CFURL

extension CFURLPathStyle {
    var swiftValue: URL.PathStyle {
        return switch self {
        case .cfurlposixPathStyle: .posix
        case .cfurlWindowsPathStyle: .windows
        case .cfurlhfsPathStyle: fatalError("HFS path style is deprecated")
        default: URL.defaultPathStyle
        }
    }
}

extension _NSSwiftURL {

    override var _originalString: String {
        return url.originalString
    }

    override var _encoding: CFStringEncoding {
        CFStringConvertNSStringEncodingToEncoding(url._encoding.rawValue)
    }

    override var _resourceInfoPtr: UnsafeMutableRawPointer? {
        get {
            url._resourceInfo.ref.withLock {
                guard let cf = $0 else { return nil }
                return Unmanaged<CFTypeRef>.passUnretained(cf).toOpaque()
            }
        }
        set {
            url._resourceInfo.ref.withLockUnchecked {
                guard let newValue else {
                    $0 = nil
                    return
                }
                // URL._resourceInfo is responsible for releasing this on deinit
                $0 = Unmanaged<CFTypeRef>.fromOpaque(newValue).takeUnretainedValue()
            }
        }
    }

    override var _compatibilityAbsolute: URL {
        return url.compatibilityAbsoluteURL ?? URL(self)
    }

    override var _isDecomposable: Bool {
        return isDecomposable
    }

    override var _netLocation: String? {
        guard let netLocation = url.netLocation,
              !netLocation.isEmpty else {
            return nil
        }
        return netLocation
    }

    override var _cfurlResourceSpecifier: String? {
        guard isDecomposable else {
            // Return everything after the scheme
            guard let colonIndex = relativeString.utf8.firstIndex(where: { $0 == ._colon }) else {
                return nil
            }
            let start = relativeString.utf8.index(after: colonIndex)
            return String(relativeString[start...])
        }
        var result: String?
        if let query = url._parseInfo.query {
            result = "?\(query)"
        }
        if let fragment = url._parseInfo.fragment {
            result = (result ?? "") + "#\(fragment)"
        }
        return result
    }

    override func _user(_ percentEncoded: Bool) -> String? {
        url.user(percentEncoded: percentEncoded)
    }

    override func _password(_ percentEncoded: Bool) -> String? {
        url.password(percentEncoded: percentEncoded)
    }

    override func _host(_ percentEncoded: Bool) -> String? {
        url.host(percentEncoded: percentEncoded)
    }

    override func _relativePath(_ percentEncoded: Bool) -> String? {
        guard hasPath else {
            return nil
        }
        return url.relativePath(percentEncoded: percentEncoded)
    }

    override func _fileSystemPath(_ pathStyle: CFURLPathStyle, resolveAgainstBase: Bool) -> String? {
        let path = _fileSystemPath(pathStyle.swiftValue, resolveAgainstBase: resolveAgainstBase)
        if pathStyle == .cfurlWindowsPathStyle {
            return path?.replacing(._slash, with: ._backslash)
        }
        return path
    }

    override func _query(_ charsToLeaveEscaped: String?) -> String? {
        guard isDecomposable, let query else {
            return nil
        }
        guard let charsToLeaveEscaped else {
            return query
        }
        return RFC3986Parser.percentDecode(query, excluding: Set(charsToLeaveEscaped.utf8))
    }

    override func _fragment(_ charsToLeaveEscaped: String?) -> String? {
        guard isDecomposable, let fragment else {
            return nil
        }
        guard let charsToLeaveEscaped else {
            return fragment
        }
        return RFC3986Parser.percentDecode(fragment, excluding: Set(charsToLeaveEscaped.utf8))
    }

    private func _nonDecomposableRange(for component: CFURLComponentType, rangeIncludingSeparators: UnsafeMutablePointer<CFRange>) -> CFRange {
        // URL must be of the form "scheme:resource-specifier".
        guard let scheme else {
            rangeIncludingSeparators.pointee = CFRange(location: kCFNotFound, length: 0)
            return CFRange(location: kCFNotFound, length: 0)
        }
        // Scheme must be ASCII, so UTF-8 length can be used.
        let schemeLength = scheme.utf8.count
        switch component {
        case .scheme:
            rangeIncludingSeparators.pointee = CFRange(location: 0, length: schemeLength + 1)
            return CFRange(location: 0, length: schemeLength)
        case .resourceSpecifier:
            let stringLength = url.originalString.lengthOfBytes(using: url._encoding)
            if schemeLength + 1 == stringLength {
                rangeIncludingSeparators.pointee = CFRange(location: stringLength, length: 0)
                return CFRange(location: kCFNotFound, length: 0)
            }
            rangeIncludingSeparators.pointee = CFRange(location: schemeLength, length: stringLength - schemeLength)
            return CFRange(location: schemeLength + 1, length: stringLength - schemeLength - 1)
        default:
            rangeIncludingSeparators.pointee = CFRange(location: kCFNotFound, length: 0)
            return CFRange(location: kCFNotFound, length: 0)
        }
    }

    private func _decomposableRange(for component: CFURLComponentType, rangeIncludingSeparators: UnsafeMutablePointer<CFRange>) -> CFRange {
        let parseInfo = if url.encodedComponents.isEmpty {
            url._parseInfo
        } else {
            RFC3986Parser.rawParse(urlString: url.originalString)
        }
        guard let parseInfo else {
            rangeIncludingSeparators.pointee = CFRange(location: kCFNotFound, length: 0)
            return CFRange(location: kCFNotFound, length: 0)
        }
        let string = url.originalString
        let encoding = url._encoding
        switch component {
        case .scheme:
            if let scheme = parseInfo.scheme {
                // Scheme must be ASCII, so we can use UTF8 length.
                let schemeLength = scheme.utf8.count
                var afterSeparatorLength = parseInfo.hasAuthority ? 3 : 1
                if !hasNetLocation && !hasPath {
                    afterSeparatorLength = 0
                }
                rangeIncludingSeparators.pointee = CFRange(location: 0, length: schemeLength + afterSeparatorLength)
                return CFRange(location: 0, length: schemeLength)
            }
        case .netLocation:
            if let netLocationRange = parseInfo.netLocationRange,
               !netLocationRange.isEmpty {
                let beforeLength = string[..<netLocationRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[netLocationRange].lengthOfBytes(using: encoding)
                let separatorLength = 2 + (parseInfo.schemeRange == nil ? 0 : 1)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - separatorLength, length: componentLength + separatorLength)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .path:
            if let pathRange = parseInfo.pathRange, hasPath {
                let beforeLength = string[..<pathRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[pathRange].lengthOfBytes(using: encoding)
                var beforeSeparatorLength = (parseInfo.schemeRange != nil) ? 1 : 0
                if parseInfo.hasAuthority {
                    if parseInfo.netLocationRange?.isEmpty == true {
                        beforeSeparatorLength += 2
                    } else {
                        beforeSeparatorLength = 0
                    }
                }
                let afterSeparatorLength = (parseInfo.queryRange != nil || parseInfo.fragmentRange != nil) ? 1 : 0
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - beforeSeparatorLength, length: beforeSeparatorLength + componentLength + afterSeparatorLength)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .resourceSpecifier:
            if let resourceSpecifierRange = parseInfo.cfResourceSpecifierRange {
                let beforeLength = string[..<resourceSpecifierRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[resourceSpecifierRange].lengthOfBytes(using: encoding)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - 1, length: componentLength + 1)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .user:
            if let userRange = parseInfo.userRange {
                let beforeLength = string[..<userRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[userRange].lengthOfBytes(using: encoding)
                let beforeSeparatorLength = 2 + (parseInfo.schemeRange == nil ? 0 : 1)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - beforeSeparatorLength, length: beforeSeparatorLength + componentLength + 1)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .password:
            if let passwordRange = parseInfo.passwordRange {
                let beforeLength = string[..<passwordRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[passwordRange].lengthOfBytes(using: encoding)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - 1, length: componentLength + 2)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .userInfo:
            if let startIndex = parseInfo.userRange?.lowerBound
                ?? parseInfo.passwordRange?.lowerBound,
               let endIndex = parseInfo.passwordRange?.upperBound
                ?? parseInfo.userRange?.upperBound {
                let beforeLength = string[..<startIndex].lengthOfBytes(using: encoding)
                let componentLength = string[startIndex..<endIndex].lengthOfBytes(using: encoding)
                let beforeSeparatorLength = 2 + (parseInfo.schemeRange == nil ? 0 : 1)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - beforeSeparatorLength, length: beforeSeparatorLength + componentLength + 1)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .host:
            if let hostRange = parseInfo.hostRange,
               host != nil {
                let beforeLength = string[..<hostRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[hostRange].lengthOfBytes(using: encoding)
                let beforeSeparatorLength = if parseInfo.userRange == nil && parseInfo.passwordRange == nil {
                    2 + (parseInfo.schemeRange == nil ? 0 : 1)
                } else {
                    1
                }
                let afterSeparatorLength = if parseInfo.portRange == nil {
                    0
                } else {
                    1
                }
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - beforeSeparatorLength, length: beforeSeparatorLength + componentLength + afterSeparatorLength)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .port:
            if let portRange = parseInfo.portRange {
                let beforeLength = string[..<portRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[portRange].lengthOfBytes(using: encoding)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - 1, length: componentLength + 1)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .parameterString:
            break
        case .query:
            if let queryRange = parseInfo.queryRange {
                let beforeLength = string[..<queryRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[queryRange].lengthOfBytes(using: encoding)
                let afterSeparatorLength = parseInfo.fragmentRange == nil ? 0 : 1
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - 1, length: 1 + componentLength + afterSeparatorLength)
                return CFRange(location: beforeLength, length: componentLength)
            }
        case .fragment:
            if let fragmentRange = parseInfo.fragmentRange {
                let beforeLength = string[..<fragmentRange.lowerBound].lengthOfBytes(using: encoding)
                let componentLength = string[fragmentRange].lengthOfBytes(using: encoding)
                rangeIncludingSeparators.pointee = CFRange(location: beforeLength - 1, length: componentLength + 1)
                return CFRange(location: beforeLength, length: componentLength)
            }
        default:
            break
        }
        return CFRange(location: kCFNotFound, length: 0)
    }

    private func _locationToInsert(component: CFURLComponentType) -> Int {
        let parseInfo = if url.encodedComponents.isEmpty {
            url._parseInfo
        } else {
            RFC3986Parser.rawParse(urlString: url.originalString)
        }
        guard let parseInfo else {
            return 0
        }
        let string = parseInfo.urlString
        let encoding = url._encoding

        var index = string.startIndex
        if component == .scheme {
            return 0
        }
        if let schemeEnd = parseInfo.schemeRange?.upperBound {
            index = string.utf8.index(after: schemeEnd)
        }
        if component == .netLocation {
            let result = string[..<index].lengthOfBytes(using: encoding)
            return parseInfo.netLocationRange == nil ? result : result + 2
        }
        if parseInfo.hasAuthority {
            index = string.utf8.index(index, offsetBy: 2)
        }
        if component == .user || component == .userInfo {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        if let userEnd = parseInfo.userRange?.upperBound {
            index = userEnd
        }
        if component == .password {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        if let passwordEnd = parseInfo.passwordRange?.upperBound {
            index = passwordEnd
        }
        if component == .host {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        if let hostEnd = parseInfo.hostRange?.upperBound {
            index = hostEnd
        }
        if component == .port {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        if let portEnd = parseInfo.portRange?.upperBound {
            index = portEnd
        }
        if component == .path {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        if let pathEnd = parseInfo.pathRange?.upperBound {
            index = pathEnd
        }
        if component == .query || component == .resourceSpecifier {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        if let queryEnd = parseInfo.queryRange?.upperBound {
            index = queryEnd
        }
        if component == .fragment {
            return string[..<index].lengthOfBytes(using: encoding)
        }
        return kCFNotFound
    }

    override func _range(for component: CFURLComponentType, rangeIncludingSeparators: UnsafeMutablePointer<CFRange>) -> CFRange {
        guard isDecomposable else {
            return _nonDecomposableRange(for: component, rangeIncludingSeparators: rangeIncludingSeparators)
        }
        let range = _decomposableRange(for: component, rangeIncludingSeparators: rangeIncludingSeparators)
        if range.location == kCFNotFound {
            rangeIncludingSeparators.pointee = CFRange(location: _locationToInsert(component: component), length: 0)
        }
        return range
    }
}

#endif // FOUNDATION_FRAMEWORK