Skip to content

Commit 351cc73

Browse files
fixed a chunking bug that caused a crash during macro expansion
1 parent ff8459f commit 351cc73

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

Sources/HTMLKitParse/ExpandHTMLMacro.swift

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -232,13 +232,18 @@ extension HTMLKitUtilities {
232232
var endIndex = encodedResult.index(encodedResult.startIndex, offsetBy: endingIndex, limitedBy: encodedResult.endIndex) ?? encodedResult.endIndex
233233
let range = encodedResult.index(encodedResult.startIndex, offsetBy: i)..<endIndex
234234
var slice = encodedResult[range]
235-
var interpolation:String?
235+
var interpolation:String? = nil
236236
if let interp = interpolationMatches.first, range.contains(interp.range.lowerBound) { // chunk contains interpolation
237-
let normalized = normalizeInterpolation(encodedResult[interp.range], withQuotationMarks: false)
238-
interpolation = normalized
237+
var normalized = normalizeInterpolation(encodedResult[interp.range], withQuotationMarks: false)
239238
if !range.contains(interp.range.upperBound) {
240239
endIndex = encodedResult.index(before: interp.range.lowerBound)
241-
slice = slice[slice.startIndex..<endIndex]
240+
if slice.startIndex < endIndex {
241+
slice = slice[slice.startIndex..<endIndex]
242+
} else {
243+
slice = ""
244+
normalized = "\"\(normalized)\""
245+
}
246+
interpolation = normalized
242247
i += encodedResult.distance(from: range.upperBound, to: interp.range.upperBound)
243248
} else {
244249
interpolation = nil
@@ -251,7 +256,7 @@ extension HTMLKitUtilities {
251256
interpolation = nil
252257
}
253258
i += chunkSize + offset
254-
if slice.isEmpty || encoding == .string && slice.count == 1 && slice[slice.startIndex] == "\"" {
259+
if slice.isEmpty && interpolation == nil || encoding == .string && slice.count == 1 && slice[slice.startIndex] == "\"" {
255260
continue
256261
}
257262
var string = ""

Tests/HTMLKitTests/HTMLKitTests.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,9 @@ extension HTMLKitTests {
108108
let _:[StaticString] = #html(resultType: .chunks()) {
109109
div("oh yeah")
110110
}
111-
/*let _:[String] = #html(resultType: .chunks(chunkSize: 3)) { // TODO: fix
111+
let _:[String] = #html(resultType: .chunks(chunkSize: 3)) {
112112
div("oh \(yeah)")
113-
}*/
113+
}
114114

115115
let _:AsyncStream<String> = #html(resultType: .stream()) {
116116
div("oh yeah")

0 commit comments

Comments
 (0)