index_heap.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "sc25519.h"
  2. #include "index_heap.h"
  3. /* caller's responsibility to ensure hlen>=3 */
  4. void heap_init(unsigned long long *h, unsigned long long hlen, sc25519 *scalars)
  5. {
  6. h[0] = 0;
  7. unsigned long long i=1;
  8. while(i<hlen)
  9. heap_push(h, &i, i, scalars);
  10. }
  11. void heap_extend(unsigned long long *h, unsigned long long oldlen, unsigned long long newlen, sc25519 *scalars)
  12. {
  13. unsigned long long i=oldlen;
  14. while(i<newlen)
  15. heap_push(h, &i, i, scalars);
  16. }
  17. void heap_push(unsigned long long *h, unsigned long long *hlen, unsigned long long elem, sc25519 *scalars)
  18. {
  19. /* Move up towards the root */
  20. /* XXX: Check size of hlen, whether cast to signed value is ok */
  21. signed long long pos = *hlen;
  22. signed long long ppos = (pos-1)/2;
  23. unsigned long long t;
  24. h[*hlen] = elem;
  25. while(pos > 0)
  26. {
  27. /* if(sc25519_lt_vartime(&scalars[h[ppos]], &scalars[h[pos]])) */
  28. if(sc25519_lt(&scalars[h[ppos]], &scalars[h[pos]]))
  29. {
  30. t = h[ppos];
  31. h[ppos] = h[pos];
  32. h[pos] = t;
  33. pos = ppos;
  34. ppos = (pos-1)/2;
  35. }
  36. else break;
  37. }
  38. (*hlen)++;
  39. }
  40. /* Put the largest value in the heap in max1, the second largest in max2 */
  41. void heap_get2max(unsigned long long *h, unsigned long long *max1, unsigned long long *max2, sc25519 *scalars)
  42. {
  43. *max1 = h[0];
  44. *max2 = h[1];
  45. if(sc25519_lt(&scalars[h[1]],&scalars[h[2]]))
  46. *max2 = h[2];
  47. }
  48. /* After the root has been replaced, restore heap property */
  49. /* extern void heap_rootreplaced(unsigned long long *h, unsigned long long hlen, sc25519 *scalars);
  50. */
  51. /* extern void heap_rootreplaced_shortscalars(unsigned long long *h, unsigned long long hlen, sc25519 *scalars);
  52. */