tst-obstack.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* Test case by Alexandre Duret-Lutz <duret_g@epita.fr>.
  2. * test_obstack_printf() added by Anthony G. Basile <blueness.gentoo.org>.
  3. */
  4. #include <features.h>
  5. #include <obstack.h>
  6. #include <stdint.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #define obstack_chunk_alloc verbose_malloc
  10. #define obstack_chunk_free verbose_free
  11. #define ALIGN_BOUNDARY 64
  12. #define ALIGN_MASK (ALIGN_BOUNDARY - 1)
  13. #define OBJECT_SIZE 1000
  14. static void *
  15. verbose_malloc (size_t size)
  16. {
  17. void *buf = malloc (size);
  18. printf ("malloc (%zu) => %p\n", size, buf);
  19. return buf;
  20. }
  21. static void
  22. verbose_free (void *buf)
  23. {
  24. free (buf);
  25. printf ("free (%p)\n", buf);
  26. }
  27. int
  28. test_obstack_alloc (void)
  29. {
  30. int result = 0;
  31. int align = 2;
  32. while (align <= 64)
  33. {
  34. struct obstack obs;
  35. int i;
  36. int align_mask = align - 1;
  37. printf ("\n Alignment mask: %d\n", align_mask);
  38. obstack_init (&obs);
  39. obstack_alignment_mask (&obs) = align_mask;
  40. /* finish an empty object to take alignment into account */
  41. obstack_finish (&obs);
  42. /* let's allocate some objects and print their addresses */
  43. for (i = 15; i > 0; --i)
  44. {
  45. void *obj = obstack_alloc (&obs, OBJECT_SIZE);
  46. printf ("obstack_alloc (%u) => %p \t%s\n", OBJECT_SIZE, obj,
  47. ((uintptr_t) obj & align_mask) ? "(not aligned)" : "");
  48. result |= ((uintptr_t) obj & align_mask) != 0;
  49. }
  50. /* clean up */
  51. obstack_free (&obs, 0);
  52. align <<= 1;
  53. }
  54. return result;
  55. }
  56. int
  57. test_obstack_printf (void)
  58. {
  59. int result = 0;
  60. int n;
  61. char *s;
  62. struct obstack ob;
  63. obstack_init (&ob);
  64. n = obstack_printf (&ob, "%s%d%c", "testing 1 ... 2 ... ", 3, '\n');
  65. result |= (n != 22);
  66. printf("obstack_printf => %d\n", n);
  67. n = obstack_printf (&ob, "%s%d%c", "testing 3 ... 2 ... ", 1, '\0');
  68. result |= (n != 22);
  69. printf("obstack_printf => %d\n", n);
  70. s = obstack_finish (&ob);
  71. printf("obstack_printf => %s\n", s);
  72. obstack_free (&ob, NULL);
  73. return result;
  74. }
  75. int
  76. main (void)
  77. {
  78. int result = 0;
  79. result |= test_obstack_alloc();
  80. result |= test_obstack_printf();
  81. return result;
  82. }