Sources/OrgCore/ASCIISearch.swift
33 lines · 1376 bytes
1import Foundation
2
3extension StringProtocol {
4 /// Whether the text contains `needle` ignoring ASCII case, by bytes: much faster than a
5 /// case-insensitive `range(of:)` over a whole file. `needle` is ASCII.
6 public func containsIgnoringASCIICase(_ needle: String) -> Bool {
7 let target = Array(needle.lowercased().utf8)
8 guard let first = target.first else { return true }
9 let firstUpper = first >= 97 && first <= 122 ? first - 32 : first
10 func search(_ bytes: UnsafeBufferPointer<UInt8>) -> Bool {
11 guard bytes.count >= target.count else { return false }
12 var i = 0
13 let last = bytes.count - target.count
14 while i <= last {
15 let b = bytes[i]
16 if b == first || b == firstUpper {
17 var k = 1
18 while k < target.count {
19 var c = bytes[i + k]
20 if c >= 65 && c <= 90 { c += 32 }
21 if c != target[k] { break }
22 k += 1
23 }
24 if k == target.count { return true }
25 }
26 i += 1
27 }
28 return false
29 }
30 if let found = utf8.withContiguousStorageIfAvailable(search) { return found }
31 return Array(utf8).withUnsafeBufferPointer(search)
32 }
33}