From 1b21b68ac1380869915e3f084117cc394cc49f7e Mon Sep 17 00:00:00 2001 From: p-x9 <50244599+p-x9@users.noreply.github.com> Date: Thu, 13 Jun 2024 15:09:46 +0900 Subject: [PATCH] Refactor null terminated string reading --- Sources/MachOKit/Extension/UnsafePointer+.swift | 9 +++++++++ Sources/MachOKit/MachOFile+Strings.swift | 9 +++------ Sources/MachOKit/MachOImage+Strings.swift | 5 ++--- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/Sources/MachOKit/Extension/UnsafePointer+.swift b/Sources/MachOKit/Extension/UnsafePointer+.swift index fd0cb11..61ed842 100644 --- a/Sources/MachOKit/Extension/UnsafePointer+.swift +++ b/Sources/MachOKit/Extension/UnsafePointer+.swift @@ -62,3 +62,12 @@ extension UnsafePointer { return (string, offset) } } + +extension UnsafePointer { + func readString() -> (String, Int) { + let offset = Int(bitPattern: strchr(self, 0)) + 1 - Int(bitPattern: self) + let string = String(cString: self) + + return (string, offset) + } +} diff --git a/Sources/MachOKit/MachOFile+Strings.swift b/Sources/MachOKit/MachOFile+Strings.swift index 5013e3c..946e075 100644 --- a/Sources/MachOKit/MachOFile+Strings.swift +++ b/Sources/MachOKit/MachOFile+Strings.swift @@ -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 } diff --git a/Sources/MachOKit/MachOImage+Strings.swift b/Sources/MachOKit/MachOImage+Strings.swift index 6a28caf..93a9bdc 100644 --- a/Sources/MachOKit/MachOImage+Strings.swift +++ b/Sources/MachOKit/MachOImage+Strings.swift @@ -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) }