Skip to content

Commit d9fe9aa

Browse files
committed
Fix HtmlAsyncRenderer never flushing when the chunk size has been exceeded
1 parent a9029bc commit d9fe9aa

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

Sources/Elementary/Rendering/HtmlAsyncRenderer.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ struct AsyncHTMLRenderer<Writer: HTMLStreamWriter>: _AsyncHTMLRendering {
1515
mutating func appendToken(_ token: consuming _HTMLRenderToken) async throws {
1616
// let value = token.renderedValue.utf8
1717
buffer.appendToken(token)
18-
if buffer.count >= buffer.capacity {
18+
if buffer.count >= self.chunkSize {
1919
try await flush()
2020
buffer.replaceSubrange(0...buffer.count - 1, with: [])
2121
}

Tests/ElementaryTests/AsyncRenderingTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,24 @@ final class AsyncRenderingTests: XCTestCase {
7070
"<p>late response foo</p><p>late response bar</p>"
7171
)
7272
}
73+
74+
func testBufferFlushesWhenChunkSizeExceeded() async throws {
75+
let writer = TestBufferWriter()
76+
try await div { "This is some content" }
77+
.render(into: writer, chunkSize: 1)
78+
79+
XCTAssertEqual("<div>This is some content</div>", String(decoding: writer.result, as: UTF8.self), file: #filePath, line: #line)
80+
XCTAssertGreaterThan(writer.writeCount, 1)
81+
}
82+
83+
func testBufferFlushesExactlyOnceOnSmallInput() async throws {
84+
let writer = TestBufferWriter()
85+
try await div { "This is some content" }
86+
.render(into: writer, chunkSize: 1024)
87+
88+
XCTAssertEqual("<div>This is some content</div>", String(decoding: writer.result, as: UTF8.self), file: #filePath, line: #line)
89+
XCTAssertEqual(writer.writeCount, 1)
90+
}
7391
}
7492

7593
private struct AwaitedP: HTML {

Tests/ElementaryTests/Utilities.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,13 @@ func HTMLAssertEqualAsyncOnly(_ html: some HTML, _ expected: String, file: Stati
1515
func HTMLFormattedAssertEqual(_ html: some HTML, _ expected: String, file: StaticString = #filePath, line: UInt = #line) {
1616
XCTAssertEqual(expected, html.renderFormatted(), file: file, line: line)
1717
}
18+
19+
final class TestBufferWriter: HTMLStreamWriter {
20+
var result: [UInt8] = []
21+
var writeCount: Int = 0
22+
23+
func write(_ bytes: ArraySlice<UInt8>) async throws {
24+
writeCount += 1
25+
result.append(contentsOf: bytes)
26+
}
27+
}

0 commit comments

Comments
 (0)