test-hashing.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Copyright 2022-2023
  2. Free Software Foundation, Inc.
  3. This file is part of Guile.
  4. Guile is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Lesser General Public License as published
  6. by the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. Guile is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  11. License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with Guile. If not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #if HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include <libguile.h>
  19. #include <stdio.h>
  20. static void
  21. test_hashing ()
  22. {
  23. // Make sure a utf-8 symbol has the expected hash. In addition to
  24. // catching algorithmic regressions, this would have caught a
  25. // long-standing buffer overflow.
  26. // Περί
  27. char about_u8[] = {0xce, 0xa0, 0xce, 0xb5, 0xcf, 0x81, 0xce, 0xaf, 0};
  28. SCM sym = scm_from_utf8_symbol (about_u8);
  29. // Value determined by calling wide_string_hash on {0x3A0, 0x3B5,
  30. // 0x3C1, 0x3AF} via a temporary test program.
  31. #if SIZEOF_UNSIGNED_LONG == 8
  32. const unsigned long expect = 4029223418961680680;
  33. #elif SIZEOF_UNSIGNED_LONG == 4
  34. const unsigned long expect = 938126682;
  35. #else
  36. #error "unsigned long not 4 or 8 bytes (need additonal test data)"
  37. #endif
  38. const unsigned long actual = scm_to_ulong (scm_symbol_hash (sym));
  39. if (actual != expect)
  40. {
  41. fprintf (stderr, "fail: unexpected utf-8 symbol hash (%lu != %lu)\n",
  42. actual, expect);
  43. exit (EXIT_FAILURE);
  44. }
  45. }
  46. static void
  47. tests (void *data, int argc, char **argv)
  48. {
  49. test_hashing ();
  50. }
  51. int
  52. main (int argc, char *argv[])
  53. {
  54. scm_boot_guile (argc, argv, tests, NULL);
  55. return 0;
  56. }