Skip to content

Commit

Permalink
Avoid Paths with noncontiguous foreign strings
Browse files Browse the repository at this point in the history
Path relies on fast iteration of its backing _str for most of its
operations. To avoid the performance hit of repeatedly calling
-characterAtIndex: when constructed with an unfortunate string, update
clients to avoid doing this.
  • Loading branch information
saagarjha committed Feb 21, 2025
1 parent 7b9879f commit d332bd0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
5 changes: 5 additions & 0 deletions Sources/SWBUtil/Path.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ public struct Path: Serializable, Sendable {

public static var homeDirectory: Path {
var rawPath = NSHomeDirectory()
// NSHomeDirectory produces a NSPathStore2, which is not a contiguous
// UTF-8 layout. Most of Path's operations rely on efficient iteration
// of String, and we can dodge the -characterAtIndex: slow path by
// performing this conversion early.
rawPath.makeContiguousUTF8()
#if os(Windows)
if rawPath.hasPrefix("/") {
rawPath.removeFirst()
Expand Down
7 changes: 6 additions & 1 deletion Sources/SWBUtil/PropertyList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,12 @@ private func convertToPropertyListItem(_ item: Any) -> PropertyListItem {
// Expected these to fall into the NSNumber/CFNumber case (except on non-Darwin), but leaving this here in case that implicit conversion changes unexpectedly.
return .plDouble(asDouble)

case let asString as String:
case var asString as String:
// It is likely that property list decoding has produced a string that
// is not contiguous UTF-8. While this doesn't break anything, it is a
// performance footgun for most clients. Eagerly convert it to a native
// representation to ensure they hit the String fast paths.
asString.makeContiguousUTF8()
return .plString(asString)

case let asData as Data:
Expand Down

0 comments on commit d332bd0

Please sign in to comment.