s_alloc.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 "String.h"
  12. #define STRLEN 128
  13. extern void
  14. s_free(String *sp)
  15. {
  16. if (sp == nil)
  17. return;
  18. lock((Lock *)sp);
  19. if(--(sp->ref) != 0){
  20. unlock((Lock *)sp);
  21. return;
  22. }
  23. unlock((Lock *)sp);
  24. if(sp->fixed == 0 && sp->base != nil)
  25. free(sp->base);
  26. free(sp);
  27. }
  28. /* get another reference to a string */
  29. extern String *
  30. s_incref(String *sp)
  31. {
  32. lock((Lock *)sp);
  33. sp->ref++;
  34. unlock((Lock *)sp);
  35. return sp;
  36. }
  37. /* allocate a String head */
  38. extern String *
  39. _s_alloc(void)
  40. {
  41. String *s;
  42. s = mallocz(sizeof *s, 1);
  43. if(s == nil)
  44. return s;
  45. s->ref = 1;
  46. s->fixed = 0;
  47. return s;
  48. }
  49. /* create a new `short' String */
  50. extern String *
  51. s_newalloc(int len)
  52. {
  53. String *sp;
  54. sp = _s_alloc();
  55. if(sp == nil)
  56. sysfatal("s_newalloc: %r");
  57. setmalloctag(sp, getcallerpc(&len));
  58. if(len < STRLEN)
  59. len = STRLEN;
  60. sp->base = sp->ptr = malloc(len);
  61. if (sp->base == nil)
  62. sysfatal("s_newalloc: %r");
  63. setmalloctag(sp->base, getcallerpc(&len));
  64. sp->end = sp->base + len;
  65. s_terminate(sp);
  66. return sp;
  67. }
  68. /* create a new `short' String */
  69. extern String *
  70. s_new(void)
  71. {
  72. String *sp;
  73. sp = _s_alloc();
  74. if(sp == nil)
  75. sysfatal("s_new: %r");
  76. sp->base = sp->ptr = malloc(STRLEN);
  77. if (sp->base == nil)
  78. sysfatal("s_new: %r");
  79. sp->end = sp->base + STRLEN;
  80. s_terminate(sp);
  81. return sp;
  82. }