list.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 "sam.h"
  10. /*
  11. * Check that list has room for one more element.
  12. */
  13. static void
  14. growlist(List *l, int esize)
  15. {
  16. uchar *p;
  17. if(l->listptr == nil || l->nalloc == 0){
  18. l->nalloc = INCR;
  19. l->listptr = emalloc(INCR*esize);
  20. l->nused = 0;
  21. }
  22. else if(l->nused == l->nalloc){
  23. p = erealloc(l->listptr, (l->nalloc+INCR)*esize);
  24. l->listptr = p;
  25. memset(p+l->nalloc*esize, 0, INCR*esize);
  26. l->nalloc += INCR;
  27. }
  28. }
  29. /*
  30. * Remove the ith element from the list
  31. */
  32. void
  33. dellist(List *l, int i)
  34. {
  35. Posn *pp;
  36. void **vpp;
  37. l->nused--;
  38. switch(l->type){
  39. case 'P':
  40. pp = l->posnptr+i;
  41. memmove(pp, pp+1, (l->nused-i)*sizeof(*pp));
  42. break;
  43. case 'p':
  44. vpp = l->voidpptr+i;
  45. memmove(vpp, vpp+1, (l->nused-i)*sizeof(*vpp));
  46. break;
  47. }
  48. }
  49. /*
  50. * Add a new element, whose position is i, to the list
  51. */
  52. void
  53. inslist(List *l, int i, ...)
  54. {
  55. Posn *pp;
  56. void **vpp;
  57. va_list list;
  58. va_start(list, i);
  59. switch(l->type){
  60. case 'P':
  61. growlist(l, sizeof(*pp));
  62. pp = l->posnptr+i;
  63. memmove(pp+1, pp, (l->nused-i)*sizeof(*pp));
  64. *pp = va_arg(list, Posn);
  65. break;
  66. case 'p':
  67. growlist(l, sizeof(*vpp));
  68. vpp = l->voidpptr+i;
  69. memmove(vpp+1, vpp, (l->nused-i)*sizeof(*vpp));
  70. *vpp = va_arg(list, void*);
  71. break;
  72. }
  73. va_end(list);
  74. l->nused++;
  75. }
  76. void
  77. listfree(List *l)
  78. {
  79. free(l->listptr);
  80. free(l);
  81. }
  82. List*
  83. listalloc(int type)
  84. {
  85. List *l;
  86. l = emalloc(sizeof(List));
  87. l->type = type;
  88. l->nalloc = 0;
  89. l->nused = 0;
  90. return l;
  91. }