title: Custom sort by value using tokyo cabinet in C
body: <p>I'm implementing a btree using tokyo cabinet, but I'd like to know if it's possible to keep the values sorted. I know I can use a <code>tcbdbsetcmpfunc</code> to set the custom comparison function for the keys, but not sure about the values?</p>
  
  <p>I ask this because most of the time I only need the first 1000 records assuming my values are sorted. Otherwise I will have to loop over millions of records sort them and get the first 1000, which can be slow.</p>
  
  <p>For instance:</p>
  
  <pre><code>#include &lt;tcutil.h&gt;
  #include &lt;tcbdb.h&gt;
  #include &lt;stdbool.h&gt;
  #include &lt;stdint.h&gt;
  
  struct foo {
      int one;
      double two;
      char *three;
  };
  
  // sort by three field
  static int val_cmp(const char *aptr, int asiz, const char *bptr, int bsiz, void *op) {
      return 1;
  }
  
  int main() {
      int ecode; 
      TCBDB *db;
      db = tcbdbnew();
      struct foo *f;
  
      tcbdbsetcmpfunc(db, val_cmp, f); // sort by struct-&gt;three?
  
      // open the database
      if(!tcbdbopen(db, "struct.tcb", BDBOWRITER | BDBOCREAT)){
          ecode = tcbdbecode(db);
          fprintf(stderr, "open error: %s\n", tcbdberrmsg(ecode));
      }
  
      f = malloc(sizeof(struct foo));
      f-&gt;one = 100;
      f-&gt;two = 1.1111;
      f-&gt;three = "Hello World";
      printf("put: %d\n", tcbdbput(db, "foo", 3, f, sizeof(struct foo)));
  
      f = malloc(sizeof(struct foo));
      f-&gt;one = 100;
      f-&gt;two = 1.1111;
      f-&gt;three = "Hello Planet";
      printf("put: %d\n", tcbdbput(db, "bar", 3, f, sizeof(struct foo)));
  
      char *key;
      BDBCUR *cursor;
      cursor = tcbdbcurnew(db);
      tcbdbcurfirst(cursor);
      while ((key = tcbdbcurkey2(cursor)) != NULL) {
          struct foo *val;
          int size;
          val = tcbdbcurval(cursor, &amp;size);
          printf("%s: one=%d\n", key, val-&gt;one);
          printf("%s: two=%f\n", key, val-&gt;two);
          tcbdbcurnext(cursor);
      }
      tcbdbdel(db);
      return 0;
  }
  </code></pre>