/src/example/key_value.c

http://cmockery.googlecode.com/ · C · 54 lines · 30 code · 6 blank · 18 comment · 3 complexity · d86e7b1949d7c92a91492bc7860e697a MD5 · raw file

  1. /*
  2. * Copyright 2008 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <stddef.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. typedef struct KeyValue {
  20. unsigned int key;
  21. const char* value;
  22. } KeyValue;
  23. static KeyValue *key_values = NULL;
  24. static unsigned int number_of_key_values = 0;
  25. void set_key_values(KeyValue * const new_key_values,
  26. const unsigned int new_number_of_key_values) {
  27. key_values = new_key_values;
  28. number_of_key_values = new_number_of_key_values;
  29. }
  30. // Compare two key members of KeyValue structures.
  31. int key_value_compare_keys(const void *a, const void *b) {
  32. return (int)((KeyValue*)a)->key - (int)((KeyValue*)b)->key;
  33. }
  34. // Search an array of key value pairs for the item with the specified value.
  35. KeyValue* find_item_by_value(const char * const value) {
  36. unsigned int i;
  37. for (i = 0; i < number_of_key_values; i++) {
  38. if (strcmp(key_values[i].value, value) == 0) {
  39. return &key_values[i];
  40. }
  41. }
  42. return NULL;
  43. }
  44. // Sort an array of key value pairs by key.
  45. void sort_items_by_key() {
  46. qsort(key_values, number_of_key_values, sizeof(*key_values),
  47. key_value_compare_keys);
  48. }