Research portable Memory game | Исследовать портируемую игру Память
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.9KB

  1. #include <stdlib.h> /* malloc */
  2. #include <stddef.h> /* offsetof */
  3. #include <stdio.h> /* printf */
  4. #include <string.h> /* memset */
  5. #include "uthash.h"
  6. #define UTF32 '\x1'
  7. typedef struct {
  8. UT_hash_handle hh;
  9. size_t len;
  10. char encoding; /* these two fields */
  11. int text[]; /* comprise the key */
  12. } msg_t;
  13. typedef struct {
  14. char encoding;
  15. int text[];
  16. } lookup_key_t;
  17. int main()
  18. {
  19. unsigned keylen;
  20. msg_t *msg, *tmp, *msgs = NULL;
  21. lookup_key_t *lookup_key;
  22. int beijing[] = {0x5317, 0x4eac}; /* UTF-32LE for 北京 */
  23. /* allocate and initialize our structure */
  24. msg = (msg_t*)malloc( sizeof(msg_t) + sizeof(beijing) );
  25. if (msg == NULL) {
  26. exit(-1);
  27. }
  28. memset(msg, 0, sizeof(msg_t)+sizeof(beijing)); /* zero fill */
  29. msg->len = sizeof(beijing);
  30. msg->encoding = UTF32;
  31. memcpy(msg->text, beijing, sizeof(beijing));
  32. /* calculate the key length including padding, using formula */
  33. keylen = offsetof(msg_t, text) /* offset of last key field */
  34. + sizeof(beijing) /* size of last key field */
  35. - offsetof(msg_t, encoding); /* offset of first key field */
  36. /* add our structure to the hash table */
  37. HASH_ADD( hh, msgs, encoding, keylen, msg);
  38. /* look it up to prove that it worked :-) */
  39. msg=NULL;
  40. lookup_key = (lookup_key_t*)malloc(sizeof(*lookup_key) + sizeof(beijing));
  41. if (lookup_key == NULL) {
  42. exit(-1);
  43. }
  44. memset(lookup_key, 0, sizeof(*lookup_key) + sizeof(beijing));
  45. lookup_key->encoding = UTF32;
  46. memcpy(lookup_key->text, beijing, sizeof(beijing));
  47. HASH_FIND( hh, msgs, &lookup_key->encoding, keylen, msg );
  48. if (msg != NULL) {
  49. printf("found \n");
  50. }
  51. free(lookup_key);
  52. HASH_ITER(hh, msgs, msg, tmp) {
  53. HASH_DEL(msgs, msg);
  54. free(msg);
  55. }
  56. return 0;
  57. }