Tutorial#
Build#
$ pixi install
$ pixi run configure
$ pixi run build
$ pixi run test
Bare Meson: meson setup build && meson compile -C build && meson test -C build.
Janet: arena builder#
The arena builder writes nested values without rebuilding the message. After
(import capnp) (or after the host calls capnp_janet_register):
(import capnp)
(def builder (capnp/new-builder))
(def body (capnp/init-root builder 1 2))
(capnp/set-u32 body 0 42)
(capnp/set-text body 0 "hello")
(capnp/set-list-text body 1 @["a" "bb"])
(def buf (capnp/finish-builder builder))
(def msg (capnp/message-from-buffer buf))
(def root (capnp/root msg))
(print (capnp/get-u32 root 0)) # 42
(print (capnp/get-text root 0)) # hello
(def items (capnp/getp root 1))
(print (capnp/list-get-text items 1)) # bb
message-from-buffer copies so the Janet buffer may be reused.
message-view-buffer aliases the caller’s buffer and keeps it GC-marked
for the view lifetime.
The typed setters take the schema default as an optional final argument and
store value XOR default, matching Cap’n Proto’s data-field encoding. Use
init-struct, init-struct-list, and struct-list-at for nested structs.
Generated helpers#
capnpc-janet consumes the standard CodeGeneratorRequest from capnp compile. The plugin emits an importable Janet module with typed readers,
builders, union selectors, group initializers, scalar defaults, interfaces,
and list helpers:
$ cp schema/codegen-features.capnp build/
$ cd build
$ capnp compile -o./capnpc-janet codegen-features.capnp
With build on JANET_PATH:
(import capnp)
(import codegen-features)
(def builder (capnp/new-builder))
(def root (codegen-features/CodegenFeatures-init-root builder))
(codegen-features/CodegenFeatures-set-count root -70001)
(def decoded
(:root (capnp/message-from-buffer (capnp/finish-builder builder))))
(assert (= -70001
(codegen-features/CodegenFeatures-get-count decoded)))
test/test_codegen.sh generates modules from the shipped schemas and executes
test/generated_builder_smoke.janet when Janet and capnp.so are present.
AddressBook#
test/test_addressbook.c sets fields in schema order and memcmp=s =test/fixtures/addressbook_alice_bob.bin from official capnp encode.
Regenerate goldens with ./scripts/gen-sample-fixtures.sh (needs
capnp on PATH).
Schema: schema/addressbook.capnp (Alice / Bob, phones, employment
union). Packed and canonical goldens sit next to the unpacked .bin.
C embed#
#include <capnp-janet/capnp_message.h>
#include <capnp-janet/capnp_janet.h>
/* after janet_init(env): */
capnp_janet_register(env);
capnp_message_t msg;
capnp_message_view_flat(&msg, bytes, len);
capnp_ptr_t root;
capnp_root(&msg, &root);
uint32_t id = capnp_get_u32(&root, 0, 0);
Link libcapnp_janet (pkg-config: capnp-janet). Compiled .jimage
packs cannot store the native capnp/* CFUNS; the host re-registers
them, then unmarshals. See architecture.