order.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file container.c
  7. * \brief Implements a smartlist (a resizable array) along
  8. * with helper functions to use smartlists. Also includes
  9. * hash table implementations of a string-to-void* map, and of
  10. * a digest-to-void* map.
  11. **/
  12. #include <stdlib.h>
  13. #include "lib/container/order.h"
  14. #include "lib/log/util_bug.h"
  15. /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
  16. * function for an array of type <b>elt_t</b>*.
  17. *
  18. * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
  19. * the kth element of an n-element list can be done in O(n). Then again, this
  20. * implementation is not in critical path, and it is obviously correct. */
  21. #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
  22. static int \
  23. _cmp_ ## elt_t(const void *_a, const void *_b) \
  24. { \
  25. const elt_t *a = _a, *b = _b; \
  26. if (*a<*b) \
  27. return -1; \
  28. else if (*a>*b) \
  29. return 1; \
  30. else \
  31. return 0; \
  32. } \
  33. elt_t \
  34. funcname(elt_t *array, int n_elements, int nth) \
  35. { \
  36. tor_assert(nth >= 0); \
  37. tor_assert(nth < n_elements); \
  38. qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
  39. return array[nth]; \
  40. }
  41. IMPLEMENT_ORDER_FUNC(find_nth_int, int)
  42. IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
  43. IMPLEMENT_ORDER_FUNC(find_nth_double, double)
  44. IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
  45. IMPLEMENT_ORDER_FUNC(find_nth_int32, int32_t)
  46. IMPLEMENT_ORDER_FUNC(find_nth_long, long)