test with nest union

This commit is contained in:
Rongsong Shen 2025-05-08 09:42:09 +08:00
parent dd65178724
commit 6c0fbc4bbd
3 changed files with 51 additions and 25 deletions

View file

@ -20,6 +20,13 @@ struct Nulldata $C.mapname("nulldata_t") {
null @0: UInt32 $C.mapname("null_"); null @0: UInt32 $C.mapname("null_");
} }
struct Buy $C.mapname("buy_t") {
from @0: Text;
u :union $C.mapname("u") $C.mapuniontag("with_recipe") {
norecipe @1: Void;
recipeAddr @2: Text $C.mapname("recipe_addr");
}
}
struct Book $C.mapname("book_t") { struct Book $C.mapname("book_t") {
title @0: Text; title @0: Text;
authors @1: List(Text) $C.mapname("authors") $C.maplistcount("n_authors"); authors @1: List(Text) $C.mapname("authors") $C.maplistcount("n_authors");
@ -29,7 +36,7 @@ struct Book $C.mapname("book_t") {
magic1 @2: List(UInt32) $C.mapname("magic_1") $C.maplistcount("n_magic1"); magic1 @2: List(UInt32) $C.mapname("magic_1") $C.maplistcount("n_magic1");
description @8: Text; description @8: Text;
acquire :union $C.mapuniontag("acquire_method") { acquire :union $C.mapuniontag("acquire_method") {
buy @3: Text; buy @3: Buy;
donation @4: Text; donation @4: Text;
} }
} }

View file

@ -20,6 +20,14 @@ typedef struct {
int null_; int null_;
} nulldata_t; } nulldata_t;
typedef struct {
char *from;
int with_recipe;
union {
char *recipe_addr;
} u;
} buy_t;
typedef struct { typedef struct {
char *title; char *title;
int n_authors; int n_authors;
@ -33,7 +41,7 @@ typedef struct {
char *description; char *description;
int acquire_method; int acquire_method;
union { union {
char *buy; buy_t *buy;
char *donation; char *donation;
} acquire; } acquire;
} book_t; } book_t;

View file

@ -38,6 +38,13 @@ int encode() {
.isbn = 335677, .isbn = 335677,
.year =2001 .year =2001
}; };
buy_t buy = {
.from = "Xinghua Book store",
.with_recipe = Buy_u_recipeAddr,
.u = {
.recipe_addr = "Xinghua Street"
}
};
struct capn_segment *cs; struct capn_segment *cs;
struct Book b; struct Book b;
Book_ptr p; Book_ptr p;
@ -53,7 +60,7 @@ int encode() {
book.magic_1 = &magic1[0]; book.magic_1 = &magic1[0];
book.description = NULL; book.description = NULL;
book.acquire_method = Book_acquire_buy; book.acquire_method = Book_acquire_buy;
book.acquire.buy = "bought from Xinhua book store"; book.acquire.buy = &buy;
capn_init_malloc(&c); capn_init_malloc(&c);
cs = capn_root(&c).seg; cs = capn_root(&c).seg;
@ -106,7 +113,11 @@ int decode() {
} }
if (book->acquire_method == Book_acquire_buy) { if (book->acquire_method == Book_acquire_buy) {
printf("%s\n", book->acquire.buy); printf("buy from %s\n", book->acquire.buy->from);
if (book->acquire.buy->with_recipe == Buy_u_recipeAddr) {
printf("recipe address %s\n",
book->acquire.buy->u.recipe_addr);
}
} }
else { else {
printf("%s\n", book->acquire.donation); printf("%s\n", book->acquire.donation);