order.c 2.2 KB

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