Skip to content

Commit 09fa0ef

Browse files
committed
Add support for string reading from fields.
Related-To: #19
1 parent 22bacec commit 09fa0ef

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

gguf/src/commonMain/kotlin/sk/ai/net/gguf/GGUFReader.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,35 @@ class GGUFReader(source: Source) {
7979
GGUFValueType.BOOL to Boolean::class
8080
)
8181

82+
/** Retrieve a metadata field as a String, if it exists and is of type string */
83+
fun getString(key: String): String? {
84+
val field = this.fields[key] ?: return null // key not present
85+
// Ensure it's a singular string (not an array)
86+
if (field.types.size == 1 && field.types[0] == GGUFValueType.STRING) {
87+
// The actual string bytes are at the index specified by data[0]
88+
val byteList = field.parts[field.data[0]] as? List<UByte> ?: return null
89+
return byteList.toUByteArray().toByteArray().decodeToString() // UTF-8 decoding
90+
}
91+
return null // Not a single string field
92+
}
93+
94+
/** Retrieve a metadata field as a list of Strings (for array-of-string fields) */
95+
fun getStringList(key: String): List<String>? {
96+
val field = this.fields[key] ?: return null
97+
// Expect an array of strings: types[0] == ARRAY and types[1] == STRING (per format)
98+
if (field.types.size >= 2 &&
99+
field.types[0] == GGUFValueType.ARRAY && field.types[1] == GGUFValueType.STRING
100+
) {
101+
// Each entry in data corresponds to one string's bytes in parts
102+
return field.data.map { idx ->
103+
val byteList = field.parts[idx] as List<UByte>
104+
byteList.toUByteArray().toByteArray().decodeToString()
105+
}
106+
}
107+
return null // Not an array-of-strings field
108+
}
109+
110+
82111
init {
83112
data = source.readByteArray()
84113

0 commit comments

Comments
 (0)