github.com/moontrade/nogc@v0.1.7/collections/wormhole/demo.c (about) 1 /* 2 * Copyright (c) 2021 Wu, Xingbo <wuxb45@gmail.com> 3 * 4 * All rights reserved. No warranty, explicit or implicit, provided. 5 */ 6 #define _GNU_SOURCE 7 #include <stdio.h> 8 9 #include "lib.h" 10 #include "kv.h" 11 #include "wh.h" 12 13 int 14 wh_demo(int argc, char ** argv) 15 { 16 (void)argc; 17 (void)argv; 18 struct wormhole * const wh = wh_create(); 19 struct wormref * const ref = wh_ref(wh); 20 21 bool r; 22 23 r = wh_put(ref, "wormhole", 8, "easy", 4); 24 printf("wh_put wormhole easy %c\n", r?'T':'F'); 25 26 r = wh_put(ref, "time_travel", 11, "impossible", 10); 27 printf("wh_put time_travel impossible %c\n", r?'T':'F'); 28 29 r = wh_del(ref, "time_travel", 11); 30 printf("wh_del time_travel %c\n", r?'T':'F'); 31 32 r = wh_probe(ref, "time_travel", 11); 33 printf("wh_probe time_travel %c\n", r?'T':'F'); 34 35 u32 klen_out = 0; 36 char kbuf_out[8] = {}; 37 u32 vlen_out = 0; 38 char vbuf_out[8] = {}; 39 r = wh_get(ref, "wormhole", 8, vbuf_out, 8, &vlen_out); 40 printf("wh_get wormhole %c %u %.*s\n", r?'T':'F', vlen_out, vlen_out, vbuf_out); 41 42 // in a concurrent environment, the kvmap_api_wormhole need park&resume when a thread is about to go idle 43 // don't need park&resume if you're using the default kvmap_api_whsafe in whwh.c! 44 wh_park(ref); 45 usleep(10); 46 wh_resume(ref); 47 48 // prepare a few keys for range ops 49 wh_put(ref, "00", 2, "0_value", 7); 50 wh_put(ref, "11", 2, "1_value", 7); 51 wh_put(ref, "22", 2, "2_value", 7); 52 53 struct wormhole_iter * const iter = wh_iter_create(ref); 54 55 wh_iter_seek(iter, NULL, 0); // seek to the head 56 printf("wh_iter_seek \"\"\n"); 57 while (wh_iter_valid(iter)) { 58 r = wh_iter_peek(iter, kbuf_out, 8, &klen_out, vbuf_out, 8, &vlen_out); 59 if (r) { 60 printf("wh_iter_peek klen=%u key=%.*s vlen=%u value=%.*s\n", 61 klen_out, klen_out, kbuf_out, vlen_out, vlen_out, vbuf_out); 62 } else { 63 printf("ERROR!\n"); 64 } 65 wh_iter_skip1(iter); 66 } 67 68 // call iter_park if you will go idle but want to use the iter later 69 // don't need to call iter_park if you're actively using iter 70 wh_iter_park(iter); 71 usleep(10); 72 73 wh_iter_seek(iter, "0", 1); 74 printf("wh_iter_seek \"0\"\n"); 75 // this time we don't want to copy the value 76 r = wh_iter_peek(iter, kbuf_out, 8, &klen_out, NULL, 0, NULL); 77 if (r){ 78 printf("wh_iter_peek klen=%u key=%.*s\n", klen_out, klen_out, kbuf_out); 79 } else { 80 printf("ERROR: iter_peek failed\n"); 81 } 82 83 wh_iter_destroy(iter); 84 // there must be no active iter when calling unref() 85 wh_unref(ref); 86 87 // unsafe operations: should have released all references 88 wh_clean(wh); // just for demonstration 89 wh_destroy(wh); // destroy also calls clean interally 90 return 0; 91 }