Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Streaming

CborWriter can be used to incrementally write CBOR data items.

Incremental processing is ideal for large data items or when you want to avoid building the entire CBOR structure in memory.

Writing

You can use CborWriter to write CBOR objects, arrays, and values step by step, directly to a file or any output stream.

The process is similar to when you override writeValue to provide custom serialization.

Example: Writing a CBOR Array of Objects

Suppose you want to write a large array of objects to a file, one at a time:

import cbor_serialization, stew/[byteutils]

var output = memoryOutput()
var writer = Cbor.Writer.init(output)

writer.beginArray()

for i in 0 ..< 2:
  writer.beginObject()

  writer.writeField("id", i)
  writer.writeField("name", "item" & $i)

  writer.endObject()

writer.endArray()

echo output.getOutput(seq[byte]).to0xHex()

This produces the following output when the resulting CBOR blob is decoded:

@[(id: 0, name: "item0"), (id: 1, name: "item1")]

Example: Writing Nested Structures

Objects and arrays can be nested arbitrarily.

Here is the same array of CBOR objects, nested in an envelope containing an additional status field.

Instead of manually placing begin/end pairs, we're using the convenience helpers writeObject and writeArray:

writer.writeObject:
  writer.writeField("status", "ok")
  writer.writeName("data")
  writer.writeArray:
    for i in 0 ..< 2:
      writer.writeObject:
        writer.writeField("id", i)
        writer.writeField("name", "item" & $i)

This produces the following output when the resulting CBOR blob is decoded:

(status: "ok", data: @[(id: 0, name: "item0"), (id: 1, name: "item1")])