btest.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <db.h>
  4. #include <fcntl.h>
  5. #include <limits.h>
  6. #include <unistd.h>
  7. #include <err.h>
  8. #include <string.h>
  9. #include <sys/types.h>
  10. #include <malloc_np.h>
  11. #include <getopt.h>
  12. #include <sys/stat.h>
  13. #include "bcompare.h"
  14. /* MALLOC_CONF=stats_print:true,junk:true */
  15. static DB * btreedb;
  16. #define KEYDATA_MAX 64
  17. static struct option longopts[] = {
  18. { "db", required_argument, NULL, 'd' },
  19. { "size", required_argument, NULL, 's' },
  20. { NULL, 0, NULL, 0 }
  21. };
  22. __attribute__((noreturn)) static int usage(void)
  23. {
  24. fputs("btest [--db filename]\n", stderr);
  25. exit (EXIT_SUCCESS);
  26. }
  27. int main(int argc, char *argv[])
  28. {
  29. char *dbname = NULL;
  30. size_t loops = 100;
  31. char buf[PATH_MAX];
  32. BTREEINFO type = {};
  33. DBT key = {};
  34. key.data = malloc(sizeof (size_t));
  35. DBT data = {};
  36. data.data = malloc(KEYDATA_MAX);
  37. size_t j;
  38. key.data = &j;
  39. key.size = sizeof j;
  40. int ch;
  41. while ((ch = getopt_long(argc, argv, "s:d:", longopts, NULL)) != -1) {
  42. switch (ch) {
  43. case 's':
  44. loops = strtoul(optarg, NULL, 10);
  45. break;
  46. case 'd':
  47. dbname = optarg;
  48. break;
  49. case 0:
  50. /* long option */
  51. break;
  52. default:
  53. usage();
  54. }
  55. }
  56. if (optind != argc)
  57. usage();
  58. if (dbname == NULL) {
  59. const char *t = getenv("TMPDIR");
  60. if (t == NULL)
  61. t = "/tmp";
  62. (void)snprintf(buf, sizeof(buf), "%s/david", t);
  63. dbname = buf;
  64. }
  65. type.compare = compare;
  66. btreedb= dbopen(dbname, O_CREAT | O_RDWR | O_SYNC , S_IRUSR | S_IWUSR, DB_BTREE, &type);
  67. if (!btreedb)
  68. err(EXIT_FAILURE, "Database unreachable:");
  69. for (j = 0; j < loops; ++j) {
  70. data.size = (size_t)snprintf(data.data, KEYDATA_MAX, "coucou %zu", j);
  71. if (btreedb->put(btreedb, &key, &data, R_NOOVERWRITE)) {
  72. warnx("Failed to insert data: %zu", j);
  73. }
  74. }
  75. free(data.data);
  76. btreedb->close(btreedb);
  77. printf("Data stored into %s.\n", dbname);
  78. }