Skip to content

Commit

Permalink
Refactor null terminated string reading
Browse files Browse the repository at this point in the history
  • Loading branch information
p-x9 committed Jun 13, 2024
1 parent 657891c commit 1b21b68
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
9 changes: 9 additions & 0 deletions Sources/MachOKit/Extension/UnsafePointer+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,12 @@ extension UnsafePointer<UInt8> {
return (string, offset)
}
}

extension UnsafePointer<CChar> {
func readString() -> (String, Int) {
let offset = Int(bitPattern: strchr(self, 0)) + 1 - Int(bitPattern: self)
let string = String(cString: self)

return (string, offset)
}
}
9 changes: 3 additions & 6 deletions Sources/MachOKit/MachOFile+Strings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,12 @@ extension MachOFile.Strings {

let ptr = baseAddress
.advanced(by: nextOffset)
.assumingMemoryBound(to: CChar.self)
let string = String(cString: ptr)

let nextPointer = UnsafePointer(strchr(ptr, 0))
.advanced(by: 1)
.assumingMemoryBound(to: UInt8.self)
let (string, offset) = ptr.readString()

let result = Element(string: string, offset: nextOffset)

nextOffset += Int(bitPattern: nextPointer) - Int(bitPattern: ptr)
nextOffset += offset

return result
}
Expand Down
5 changes: 2 additions & 3 deletions Sources/MachOKit/MachOImage+Strings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,8 @@ extension MachOImage.Strings {
if offset >= tableSize {
return nil
}
let string = String(cString: nextPointer)
nextPointer = UnsafePointer(strchr(nextPointer, 0))
.advanced(by: 1)
let (string, nextOffset) = nextPointer.readString()
nextPointer = nextPointer.advanced(by: nextOffset)

return .init(string: string, offset: offset)
}
Expand Down

0 comments on commit 1b21b68

Please sign in to comment.