named_list.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <stddef.h>
  2. #include <stdint.h>
  3. #include <named_list.h>
  4. /* Get number of elements in a list
  5. * This is not very efficient as-is since it has to walk the whole list.
  6. */
  7. size_t namedlist_cnt(const NamedList* list) {
  8. size_t i;
  9. for(i = 0;; i++) {
  10. if(list[i].name == NULL) return i;
  11. }
  12. }
  13. /* Returns the generation mask of the requested item in the list */
  14. uint32_t namedlist_gen_get_pos(const NamedList* list, uint32_t pos) {
  15. return list[pos].gen;
  16. }
  17. /* Returns the generation mask of the item in the list that matches the
  18. * provided index. This will ultimately return the 0th element in the case
  19. * of the provided index not matching any of the list elements.
  20. */
  21. uint32_t namedlist_gen_get_index(const NamedList* list, uint32_t index) {
  22. return list[namedlist_pos_get(list, index)].gen;
  23. }
  24. /* Returns the list position based on the provided index. If index is not
  25. * matched, the 0th position is returned. In most lists this is a "NONE"
  26. * indicator. e.g. No Move.
  27. */
  28. uint32_t namedlist_pos_get(const NamedList* list, uint32_t index) {
  29. int i;
  30. for(i = 0;; i++) {
  31. if(list[i].name == NULL) break;
  32. if(index == list[i].index) return i;
  33. }
  34. /* This will return the first entry in case index is not matched.
  35. * Could be surprising at runtime.
  36. */
  37. return 0;
  38. }
  39. /* Get the item's index value from the position specified */
  40. uint32_t namedlist_index_get(const NamedList* list, uint32_t pos) {
  41. return list[pos].index;
  42. }
  43. /* Get a pointer to the item's name from an item's index */
  44. const char* namedlist_name_get_index(const NamedList* list, uint32_t index) {
  45. return list[namedlist_pos_get(list, index)].name;
  46. }
  47. /* Get a pointer to the item's name from a position */
  48. const char* namedlist_name_get_pos(const NamedList* list, uint32_t pos) {
  49. return list[pos].name;
  50. }