Skip to content

[StdLib] Incorrect results from String.hasPrefix and hasSuffix #67427

@natecook1000

Description

@natecook1000

As reported on the Swift forums, String.hasPrefix and String.hasSuffix sometimes have an incorrect result:

"\r\n".hasPrefix("\r")      // true
"\r\n".hasPrefix("\r"[...]) // false

"\r\n".hasSuffix("\n")      // true
"\r\n".hasSuffix("\n"[...]) // false

All four of these calls should return false, since those methods should be matching at the character level, not at the Unicode scalar level. The problem is in the String-specific overloads for hasPrefix and hasSuffix in StringLegacy.swift, which don't validate that the string passed as a parameter ends on a character boundary (when both strings are known to be NFC). The calls that pass a substring go to the StringProtocol-based overload, instead, which calls through to the Sequence method starts(with:).

Environment

  • Swift main branch

Metadata

Metadata

Labels

StringArea → standard library: The `String` typebugA deviation from expected or documented behavior. Also: expected but undesirable behavior.standard libraryArea: Standard library umbrellaswift 5.9unexpected behaviorBug: Unexpected behavior or incorrect output

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions