strinttab.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. #include <html.h>
  5. #include "impl.h"
  6. // Do case-insensitive lookup of key[0:keylen] in t[0:n] (key part),
  7. // returning 1 if found, 0 if not.
  8. // Array t must be sorted in increasing lexicographic order of key.
  9. // If found, return corresponding val in *pans.
  10. int
  11. _lookup(StringInt* t, int n, Rune* key, int keylen, int* pans)
  12. {
  13. int min;
  14. int max;
  15. int try;
  16. int cmpresult;
  17. min = 0;
  18. max = n - 1;
  19. while(min <= max) {
  20. try = (min + max)/2;
  21. cmpresult = _Strncmpci(key, keylen, t[try].key);
  22. if(cmpresult > 0)
  23. min = try + 1;
  24. else if(cmpresult < 0)
  25. max = try - 1;
  26. else {
  27. *pans = t[try].val;
  28. return 1;
  29. }
  30. }
  31. return 0;
  32. }
  33. // Return first key in t[0:n] that corresponds to val,
  34. // nil if none.
  35. Rune*
  36. _revlookup(StringInt* t, int n, int val)
  37. {
  38. int i;
  39. for(i = 0; i < n; i++)
  40. if(t[i].val == val)
  41. return t[i].key;
  42. return nil;
  43. }
  44. // Make a StringInt table out of a[0:n], mapping each string
  45. // to its index. Check that entries are in alphabetical order.
  46. StringInt*
  47. _makestrinttab(Rune** a, int n)
  48. {
  49. StringInt* ans;
  50. int i;
  51. ans = (StringInt*)emalloc(n * sizeof(StringInt));
  52. for(i = 0; i < n; i++) {
  53. ans[i].key = a[i];
  54. ans[i].val = i;
  55. assert(i == 0 || runestrcmp(a[i], a[i - 1]) >= 0);
  56. }
  57. return ans;
  58. }