varbuf.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * libdpkg - Debian packaging suite library routines
  3. * varbuf.c - variable length expandable buffer handling
  4. *
  5. * Copyright (C) 1994,1995 Ian Jackson <iwj10@cus.cam.ac.uk>
  6. *
  7. * This is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2,
  10. * or (at your option) any later version.
  11. *
  12. * This is distributed in the hope that it will be useful, but
  13. * WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public
  18. * License along with dpkg; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <stdio.h>
  24. #include <config.h>
  25. #include <dpkg.h>
  26. #include <dpkg-db.h>
  27. void varbufaddc(struct varbuf *v, int c) {
  28. if (v->used >= v->size) varbufextend(v);
  29. v->buf[v->used++]= c;
  30. }
  31. void varbufprintf(struct varbuf *v, const char *fmt, ...) {
  32. int ou, r;
  33. va_list al;
  34. ou= v->used;
  35. v->used+= strlen(fmt);
  36. do {
  37. varbufextend(v);
  38. va_start(al,fmt);
  39. r= vsnprintf(v->buf+ou,v->size-ou,fmt,al);
  40. va_end(al);
  41. if (r < 0) r= (v->size-ou+1) * 2;
  42. v->used= ou+r;
  43. } while (r >= v->size-ou-1);
  44. }
  45. void varbufvprintf(struct varbuf *v, const char *fmt, va_list va) {
  46. int ou, r;
  47. va_list al;
  48. ou= v->used;
  49. v->used+= strlen(fmt);
  50. do {
  51. varbufextend(v);
  52. al= va;
  53. r= vsnprintf(v->buf+ou,v->size-ou,fmt,al);
  54. if (r < 0) r= (v->size-ou+1) * 2;
  55. v->used= ou+r;
  56. } while (r >= v->size-ou-1);
  57. }
  58. void varbufaddbuf(struct varbuf *v, const void *s, const int l) {
  59. int ou;
  60. ou= v->used;
  61. v->used += l;
  62. if (v->used >= v->size) varbufextend(v);
  63. memcpy(v->buf + ou, s, l);
  64. }
  65. void varbufinit(struct varbuf *v) {
  66. /* NB: dbmodify.c does its own init to get a big buffer */
  67. v->size= v->used= 0;
  68. v->buf= 0;
  69. }
  70. void varbufreset(struct varbuf *v) {
  71. v->used= 0;
  72. }
  73. void varbufextend(struct varbuf *v) {
  74. int newsize;
  75. char *newbuf;
  76. newsize= v->size + 80 + v->used;
  77. newbuf= realloc(v->buf,newsize);
  78. if (!newbuf) ohshite(_("failed to realloc for variable buffer"));
  79. v->size= newsize;
  80. v->buf= newbuf;
  81. }
  82. void varbuffree(struct varbuf *v) {
  83. free(v->buf); v->buf=0; v->size=0; v->used=0;
  84. }