free(3) replacement

crux-00011: $SRC/utils/ar_trim.c

#include "utils/ar_i.h"
#include "utils/chk.h"
#include "utils/panic.h"


void
ar_trim  (void ** ar, int * arn, int sz, int len)
{
  if (sz < 0)
    {
      panic ("negatively sized array elements are not supported");
    }
  else if (len < 0)
    {
      panic ("negative array index");
    }
  else if (len == *arn)
    {
      return;
    }
  else if (len > *arn)
    {
      (void)ar_ref (ar, arn, sz, len - 1);
      return;
    }
  else if (len == 0)
    {
      chk_free ((void *)*ar, *arn);
      *ar = 0;
      *arn = 0;
      return;
    }
  else
    {
      int at = len - 1;
      int new_arn = ar_round_up (at);
      int new_len = new_arn * sz;
      int old_len = *arn * sz;
      int pos;

      *ar = chk_realloc (*ar, old_len, new_len);
      *arn = new_arn;
      for (pos = at * sz; pos < new_len; ++pos)
        ((char *)*ar)[pos] = 0;
      return;
    }
}


/*

    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/>.

*/