"str" functions

crux-00008: $SRC/str/str.c

#include "str/str.h"
#include "utils/ar.h"
#include "utils/panic.h"

int
str_length (struct str * s)
{
  return s->l;
}

static void
check_pos (struct str * s, int pos, int  l)
{
  if (pos < 0) panic ("string position below 0");
  if (pos >= s->l) panic ("substring length too large");
  if (l < 0) panic ("substring length below 0");
  if ((pos + l) > s->l) panic ("substring length too large");
}

char *
str_view (struct str * s, int pos, int l)
{
  check_pos (s, pos, l);
  return s->s + pos;
}

void
str_set_length (struct str * s, int l)
{
  if (l < 0) panic ("setting string to sub-0 length");
  ar_ref ((void **)&s->s, &s->z, 1, l + 1);
  s->l = l;
}

void
str_set (struct str * s, int l, char * c)
{
  int x;
  str_set_length (s, l);
  for (x = 0; x < l; ++x) s->s[x] = c[x];
}


void
str_set0 (struct str * s, char * c)
{
  if (!c)
    str_set_length (s, 0);
  else
    {
      int x;
      for (x = 0; c[x]; ++x);
      str_set (s, x, c);
    }
}

void
str_adjoin (struct str * s, char c)
{
  str_set_length (s, 1 + s->l);
  s->s[s->l - 1] = c;
}

void
str_append (struct str * s, int l, char * c)
{
  int x = s->l;
  if (l < 0) panic ("append length boo");
  str_set_length (s, x + l);
  while (l--) s->s[x++] = *(c++);
}


void
str_append0 (struct str * s, char * c)
{
  int x;
  for (x = 0; c[x]; ++x);
  str_append (s, x, c);
}

void
str_copy (struct str * s, struct str * t)
{
  str_set (s, t->l, t->s);
}


void
str_cat (struct str * s, struct str * t)
{
  str_append (s, t->l, t->s);
}

void
str_trim (struct str * s)
{
  ar_trim ((void **)&s->s, &s->z, 1, s->l + 1);
}

/*

    This file is part of Crux.

    Crux is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Crux is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Crux.  If not, see <http://www.gnu.org/licenses/>.

*/