index_heap.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * File: dclxvi-20130329/index_heap.c
  3. * Author: Ruben Niederhagen, Peter Schwabe
  4. * Public Domain
  5. */
  6. #include <assert.h>
  7. #ifdef NEW_PARAMETERS
  8. #include "scalar_512.h"
  9. #else
  10. #include "scalar.h"
  11. #endif
  12. #include "index_heap.h"
  13. static void heap_push(unsigned long long *h, unsigned long long *hlen, unsigned long long elem, scalar_t *s)
  14. {
  15. /* Move up towards the root */
  16. /* XXX: Check size of hlen, whether cast to signed value is ok */
  17. signed long long pos = *hlen;
  18. signed long long ppos = (pos-1)/2;
  19. unsigned long long t;
  20. h[*hlen] = elem;
  21. while(pos > 0)
  22. {
  23. if(scalar_lt_vartime(s[h[ppos]], s[h[pos]]))
  24. {
  25. t = h[ppos];
  26. h[ppos] = h[pos];
  27. h[pos] = t;
  28. pos = ppos;
  29. ppos = (pos-1)/2;
  30. }
  31. else break;
  32. }
  33. (*hlen)++;
  34. }
  35. /* caller's responsibility to ensure hlen>=3 */
  36. void heap_init(unsigned long long *h, unsigned long long hlen, scalar_t *s)
  37. {
  38. assert(hlen>=5);
  39. assert(hlen&1);
  40. h[0] = 0;
  41. unsigned long long i=1;
  42. while(i<hlen)
  43. heap_push(h, &i, i, s);
  44. }
  45. /* Put the largest value in the heap in max1, the second largest in max2 */
  46. void heap_get2max(unsigned long long *h, unsigned long long *max1, unsigned long long *max2, scalar_t *s)
  47. {
  48. *max1 = h[0];
  49. *max2 = h[1];
  50. if(scalar_lt_vartime(s[h[1]],s[h[2]]))
  51. *max2 = h[2];
  52. }