Skip to content

NSRange uses character count (runtime crash risk) #123

@leogdion

Description

@leogdion

⚠️ Potential issue | 🔴 Critical

NSRange uses character count (runtime crash risk)

Line 116 feeds string.count into an NSRange, but NSRegularExpression expects UTF‑16 lengths. Any non-ASCII input can produce an out-of-bounds range and crash. Switch to the safe initializer that bridges indices correctly.

   public func matches(in string: String) -> [NSTextCheckingResult] {
-    matches(in: string, range: NSRange(location: 0, length: string.count))
+    let range = NSRange(string.startIndex..<string.endIndex, in: string)
+    return matches(in: string, range: range)
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

  public func matches(in string: String) -> [NSTextCheckingResult] {
    let range = NSRange(string.startIndex..<string.endIndex, in: string)
    return matches(in: string, range: range)
  }
🤖 Prompt for AI Agents
In Sources/MistKit/Utilities/NSRegularExpression+CommonPatterns.swift around
lines 115–117, the current code builds an NSRange using string.count which uses
Swift character counts and can be out-of-bounds for UTF‑16 based APIs; replace
that with a UTF‑16‑correct range such as creating the range via
NSRange(string.startIndex..<string.endIndex, in: string) (or using (string as
NSString).length) and pass that to matches(in:range:) so the NSRegularExpression
call uses the correct bridged range.

Originally posted by @coderabbitai[bot] in #105 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions