strinttab.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <draw.h>
  12. #include <html.h>
  13. #include "impl.h"
  14. // Do case-insensitive lookup of key[0:keylen] in t[0:n] (key part),
  15. // returning 1 if found, 0 if not.
  16. // Array t must be sorted in increasing lexicographic order of key.
  17. // If found, return corresponding val in *pans.
  18. int
  19. _lookup(StringInt* t, int n, Rune* key, int keylen, int* pans)
  20. {
  21. int min;
  22. int max;
  23. int try;
  24. int cmpresult;
  25. min = 0;
  26. max = n - 1;
  27. while(min <= max) {
  28. try = (min + max)/2;
  29. cmpresult = _Strncmpci(key, keylen, t[try].key);
  30. if(cmpresult > 0)
  31. min = try + 1;
  32. else if(cmpresult < 0)
  33. max = try - 1;
  34. else {
  35. *pans = t[try].val;
  36. return 1;
  37. }
  38. }
  39. return 0;
  40. }
  41. // Return first key in t[0:n] that corresponds to val,
  42. // nil if none.
  43. Rune*
  44. _revlookup(StringInt* t, int n, int val)
  45. {
  46. int i;
  47. for(i = 0; i < n; i++)
  48. if(t[i].val == val)
  49. return t[i].key;
  50. return nil;
  51. }
  52. // Make a StringInt table out of a[0:n], mapping each string
  53. // to its index. Check that entries are in alphabetical order.
  54. StringInt*
  55. _makestrinttab(Rune** a, int n)
  56. {
  57. StringInt* ans;
  58. int i;
  59. ans = (StringInt*)emalloc(n * sizeof(StringInt));
  60. for(i = 0; i < n; i++) {
  61. ans[i].key = a[i];
  62. ans[i].val = i;
  63. assert(i == 0 || runestrcmp(a[i], a[i - 1]) >= 0);
  64. }
  65. return ans;
  66. }