Skip to content
Hokusai2.2.2
ivantokar.com

SwiftNIO buffers

HokusaiNIO is an optional product that bridges Hokusai and SwiftNIO’s ByteBuffer. It is what Hokusai Vapor and Hokusai Hummingbird use under the hood, and it is useful directly in any NIO-based server.

Package.swift
.product(name: "HokusaiNIO", package: "hokusai")
let bytes = try Data(contentsOf: URL(fileURLWithPath: "scene.png"))
var buffer = ByteBuffer(bytes: bytes)
// A ByteBuffer in: the readable bytes are adopted, so the buffer may be reused or released at once.
let image = try Hokusai(buffer: buffer)
buffer.clear()
// A ByteBuffer out, all at once...
let whole = try await image.resize(width: 400).webp().byteBuffer()
print("byteBuffer:", whole.buffer.readableBytes, "bytes,", whole.info.width, "×", whole.info.height)
// ...or streamed, one buffer at a time, with the backpressure of writeChunks.
var received = 0, count = 0
let info = try await image.resize(width: 400).jpeg().writeByteBuffers(chunkSize: 4096) { chunk in
received += chunk.readableBytes
count += 1
}
print("writeByteBuffers:", count, "buffers,", received, "bytes; info says", info.byteCount)
// Output.byteBuffer wraps bytes you already have in a fresh buffer.
let output = try await image.resize(width: 100).png().data()
print("Output.byteBuffer:", output.byteBuffer.readableBytes, "bytes")
API Does
Hokusai(buffer:options:byteTransferStrategy:) Adopts the readable bytes of a ByteBuffer as an immutable input, so the buffer can be released, reused or mutated before the asynchronous evaluation.
byteBuffer(allocator:) Evaluates and encodes into a buffer from allocator; returns NIOOutput (buffer, info). The complete result is held in memory: a convenience, not a streaming path. The encoded bytes are copied once, straight into the allocator’s buffer.
writeByteBuffers(allocator:chunkSize:_:) The core writeChunks with each chunk copied into a buffer from allocator. No queue of its own: the next buffer is not produced until consume returns, which is how a slow ResponseBodyWriter or channel slows encoding down. The same call works for PDF.
Hokusai(spooling:options:memoryLimit:spoolDirectory:) with ByteBuffers The spooled-upload initializer for the body type of NIO servers (Large uploads); each buffer is copied once, transiently, to Data.
Output.byteBuffer Owned output bytes in a fresh buffer.

The program printed: byteBuffer produced 5,036 bytes (400 × 250); writeByteBuffers delivered 9,660 bytes in 3 buffers of at most 4,096 bytes and OutputInfo.byteCount agreed; Output.byteBuffer wrapped a 7,072-byte PNG. Errors, cancellation and partial-stream behavior are those of writeChunks (terminals).