Skip to content

Commit fc1f264

Browse files
authored
Merge pull request #236 from p-x9/feature/string-at-offset
Add method to retrieve a string at a specified offset from string table
2 parents 5dee989 + 8f61c68 commit fc1f264

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed

Sources/MachOKit/MachOFile+Strings.swift

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ extension MachOFile {
4949
}
5050

5151
extension MachOFile.UnicodeStrings {
52-
init(
52+
@_spi(Support)
53+
public init(
5354
machO: MachOFile,
5455
offset: Int,
5556
size: Int,
@@ -74,6 +75,18 @@ extension MachOFile.UnicodeStrings {
7475
}
7576
}
7677

78+
extension MachOFile.UnicodeStrings {
79+
public func string(at offset: Int) -> Element? {
80+
guard 0 <= offset, offset < fileSlice.size else { return nil }
81+
let string = String(
82+
cString: fileSlice.ptr
83+
.advanced(by: offset)
84+
.assumingMemoryBound(to: CChar.self)
85+
)
86+
return .init(string: string, offset: offset)
87+
}
88+
}
89+
7790
extension MachOFile.UnicodeStrings {
7891
public struct Iterator: IteratorProtocol {
7992
public typealias Element = StringTableEntry

Sources/MachOKit/MachOImage+Strings.swift

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ extension MachOImage {
1616
public let basePointer: UnsafePointer<Encoding.CodeUnit>
1717
public let tableSize: Int
1818

19-
init(
19+
@_spi(Support)
20+
public init(
2021
basePointer: UnsafePointer<Encoding.CodeUnit>,
2122
tableSize: Int
2223
) {
@@ -63,6 +64,18 @@ extension MachOImage.UnicodeStrings {
6364
}
6465
}
6566

67+
extension MachOImage.UnicodeStrings {
68+
public func string(at offset: Int) -> Element? {
69+
guard 0 <= offset, offset < tableSize else { return nil }
70+
let string = String(
71+
cString: UnsafeRawPointer(basePointer)
72+
.advanced(by: offset)
73+
.assumingMemoryBound(to: CChar.self)
74+
)
75+
return .init(string: string, offset: offset)
76+
}
77+
}
78+
6679
extension MachOImage.UnicodeStrings {
6780
public struct Iterator: IteratorProtocol {
6881
public typealias Element = StringTableEntry

Sources/MachOKit/Protocol/StringTable.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,11 @@
88

99
public protocol StringTable<Encoding>: Sequence<StringTableEntry> {
1010
associatedtype Encoding: _UnicodeEncoding
11+
12+
/// Returns the string entry located at the specified offset within the string table.
13+
///
14+
/// - Parameter offset: The byte offset from the start of the string table.
15+
/// - Returns: A `StringTableEntry` containing the string and its offset,
16+
/// or `nil` if the offset is out of bounds or invalid.
17+
func string(at offset: Int) -> Element?
1118
}

0 commit comments

Comments
 (0)