ndbgetval.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 <bio.h>
  12. #include "ndb.h"
  13. /*
  14. * search for a tuple that has the given 'attr=val' and also 'rattr=x'.
  15. * copy 'x' into 'buf' and return the whole tuple.
  16. *
  17. * return 0 if not found.
  18. */
  19. char*
  20. ndbgetvalue(Ndb *db, Ndbs *s, char *attr, char *val, char *rattr,
  21. Ndbtuple **pp)
  22. {
  23. Ndbtuple *t, *nt;
  24. char *rv;
  25. Ndbs temps;
  26. if(s == nil)
  27. s = &temps;
  28. if(pp)
  29. *pp = nil;
  30. t = ndbsearch(db, s, attr, val);
  31. while(t){
  32. /* first look on same line (closer binding) */
  33. nt = s->t;
  34. for(;;){
  35. if(strcmp(rattr, nt->attr) == 0){
  36. rv = strdup(nt->val);
  37. if(pp != nil)
  38. *pp = t;
  39. else
  40. ndbfree(t);
  41. return rv;
  42. }
  43. nt = nt->line;
  44. if(nt == s->t)
  45. break;
  46. }
  47. /* search whole tuple */
  48. for(nt = t; nt; nt = nt->entry){
  49. if(strcmp(rattr, nt->attr) == 0){
  50. rv = strdup(nt->val);
  51. if(pp != nil)
  52. *pp = t;
  53. else
  54. ndbfree(t);
  55. return rv;
  56. }
  57. }
  58. ndbfree(t);
  59. t = ndbsnext(s, attr, val);
  60. }
  61. return nil;
  62. }
  63. Ndbtuple*
  64. ndbgetval(Ndb *db, Ndbs *s, char *attr, char *val, char *rattr,
  65. char *buf)
  66. {
  67. Ndbtuple *t;
  68. char *p;
  69. p = ndbgetvalue(db, s, attr, val, rattr, &t);
  70. if(p == nil){
  71. if(buf != nil)
  72. *buf = 0;
  73. } else {
  74. if(buf != nil){
  75. strncpy(buf, p, Ndbvlen-1);
  76. buf[Ndbvlen-1] = 0;
  77. }
  78. free(p);
  79. }
  80. ndbsetmalloctag(t, getcallerpc(&db));
  81. return t;
  82. }