monotonic_queue.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "monotonic_queue.h"
  2. void monotonic_queue_init(struct monotonic_queue *mq,
  3. monotonic_queue_cmp cmp)
  4. {
  5. mq->h = mq->h_min = mq->t = mq->len = 0;
  6. mq->cmp = cmp;
  7. }
  8. int monotonic_queue_push(struct monotonic_queue *mq, float value)
  9. {
  10. int t1;
  11. while (mq->h_min != mq->t && mq->cmp(value, mq->buf[mq->h_min]))
  12. mq->h_min = (mq->h_min + 1) % MONOTONIC_QUEUE_CAP;
  13. t1 = (mq->t + 1) % MONOTONIC_QUEUE_CAP;
  14. if (t1 == mq->h)
  15. /* over flow */
  16. return -1;
  17. mq->len++;
  18. mq->buf[mq->t] = value;
  19. mq->t = t1;
  20. return 0;
  21. }
  22. int monotonic_queue_pop(struct monotonic_queue *mq)
  23. {
  24. if (mq->h == mq->t)
  25. /* empty */
  26. return -1;
  27. mq->len--;
  28. if (mq->h == mq->h_min)
  29. mq->h_min = (mq->h_min + 1) % MONOTONIC_QUEUE_CAP;
  30. mq->h = (mq->h + 1) % MONOTONIC_QUEUE_CAP;
  31. return 0;
  32. }
  33. int monotonic_queue_get_min(struct monotonic_queue *mq, float *dest)
  34. {
  35. if (mq->h == mq->t)
  36. /* empty */
  37. return -1;
  38. *dest = mq->buf[mq->h_min];
  39. return 0;
  40. }
  41. int monotonic_queue_get_len(struct monotonic_queue *mq)
  42. {
  43. return mq->len;
  44. }
  45. /* vim: set ts=8 sw=8 sts=8 noet: */