(root)/
texinfo-7.1/
tp/
Texinfo/
XS/
text.c
       1  /* Copyright 2014-2023 Free Software Foundation, Inc.
       2  
       3     This program is free software: you can redistribute it and/or modify
       4     it under the terms of the GNU General Public License as published by
       5     the Free Software Foundation, either version 3 of the License, or
       6     (at your option) any later version.
       7  
       8     This program is distributed in the hope that it will be useful,
       9     but WITHOUT ANY WARRANTY; without even the implied warranty of
      10     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      11     GNU General Public License for more details.
      12  
      13     You should have received a copy of the GNU General Public License
      14     along with this program.  If not, see <http://www.gnu.org/licenses/>. */
      15  
      16  #ifdef HAVE_CONFIG_H
      17    #include <config.h>
      18  #endif
      19  #include <stdlib.h>
      20  #include <string.h>
      21  #include <stdio.h>
      22  #include <stdarg.h>
      23  
      24  #include "text.h"
      25  
      26  /* Make sure there are LEN free bytes. */
      27  static void
      28  text_alloc (TEXT *t, size_t len)
      29  {
      30    if (t->end + len > t->space)
      31      {
      32        /* FIXME: Double it instead? */
      33        t->space = t->end + len;
      34        if (t->space < 10)
      35          t->space = 10;
      36        t->text = realloc (t->text, t->space);
      37        if (!t->text)
      38          abort ();
      39      }
      40  }
      41  
      42  void
      43  text_printf (TEXT *t, char *format, ...)
      44  {
      45    va_list v;
      46    char *s;
      47  
      48    va_start (v, format);
      49    if (vasprintf (&s, format, v) < 0)
      50      abort ();  /* out of memory */
      51    text_append (t, s);
      52    free (s);
      53    va_end (v);
      54  }
      55  
      56  void
      57  text_append_n (TEXT *t, char *s, size_t len)
      58  {
      59    text_alloc (t, len + 1);
      60    memcpy (t->text + t->end, s, len);
      61    t->end += len;
      62    t->text[t->end] = '\0';
      63  }
      64  
      65  void
      66  text_append (TEXT *t, char *s)
      67  {
      68    size_t len = strlen (s);
      69    text_append_n (t, s, len);
      70  }
      71  
      72  /* Set text to an empty string without clearing any storage */
      73  void
      74  text_reset (TEXT *t)
      75  {
      76    if (t->end > 0)
      77      {
      78        t->end = 0;
      79        t->text[0] = 0;
      80      }
      81  }
      82  
      83  void
      84  text_init (TEXT *t)
      85  {
      86    t->end = t->space = 0;
      87    t->text = 0;
      88  }
      89  
      90  void
      91  text_destroy (TEXT *t)
      92  {
      93    t->end = t->space = 0;
      94    free(t->text); t->text = 0;
      95  }