2
0

example_strmap.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* _
  2. * ___ __ _ __ _ _ _(_)
  3. * / __|/ _` |/ _` | | | | |
  4. * \__ \ (_| | (_| | |_| | |
  5. * |___/\__,_|\__, |\__,_|_|
  6. * |___/
  7. *
  8. * Cross-platform library which helps to develop web servers or frameworks.
  9. *
  10. * Copyright (C) 2016-2019 Silvio Clecio <[email protected]>
  11. *
  12. * Sagui library is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * Sagui library is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with Sagui library; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. /* NOTE: Error checking has been omitted to make it clear. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <sagui.h>
  31. static int map_sort(__SG_UNUSED void *cls, struct sg_strmap *pair_a,
  32. struct sg_strmap *pair_b) {
  33. return strcmp(sg_strmap_val(pair_b), sg_strmap_val(pair_a)); /* desc */
  34. }
  35. static int map_iter(__SG_UNUSED void *cls, struct sg_strmap *pair) {
  36. const char *name = sg_strmap_name(pair);
  37. printf("\t%c: %s\n", *name, name);
  38. return 0;
  39. }
  40. static void chat(struct sg_strmap **map, const char *name, const char *msg) {
  41. struct sg_strmap *pair;
  42. sg_strmap_set(map, name, msg);
  43. if (msg && (sg_strmap_find(*map, name, &pair) == 0))
  44. printf("%c:\t%s\n", *sg_strmap_name(pair), sg_strmap_val(pair));
  45. }
  46. int main(void) {
  47. struct sg_strmap *map = NULL;
  48. chat(&map, "Clecio", "Hello!");
  49. chat(&map, "Paim", "Hello. How are you?");
  50. chat(&map, "Clecio", "I'm fine. And you?");
  51. chat(&map, "Paim", "Me too.");
  52. printf("\nChatters:\n");
  53. sg_strmap_sort(&map, &map_sort, NULL);
  54. sg_strmap_iter(map, &map_iter, NULL);
  55. sg_strmap_cleanup(&map);
  56. return EXIT_SUCCESS;
  57. }