Program Listing for File t8_windows.h

Return to documentation for file (src/t8_misc/t8_windows.h)

/*
  This file is part of t8code.
  t8code is a C library to manage a collection (a forest) of multiple
  connected adaptive space-trees of general element classes in parallel.

  Copyright (C) 2023 the developers

  t8code 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 2 of the License, or
  (at your option) any later version.

  t8code 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 t8code; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#ifndef T8_WINDOWS_H
#define T8_WINDOWS_H

static ssize_t
getdelim (char **lineptr, size_t *n, int delimiter, FILE *stream)
{
  int initial_buffer_size = 1024;
  int c;
  size_t pos;
  size_t new_size;
  char *new_ptr;

  if (lineptr == NULL || stream == NULL || n == NULL) {
    return -1;
  }

  c = getc (stream);

  if (c == EOF) {
    return -1;
  }

  if (*lineptr == NULL) {
    *lineptr = (char *) malloc (initial_buffer_size);
    if (*lineptr == NULL) {
      return -1;
    }
    *n = initial_buffer_size;
  }

  pos = 0;
  while (c != EOF) {
    if (pos + 1 >= *n) {
      new_size = *n + (*n >> 2);
      if (new_size < initial_buffer_size) {
        new_size = initial_buffer_size;
      }
      new_ptr = (char *) realloc (*lineptr, new_size);
      if (new_ptr == NULL) {
        return -1;
      }
      *n = new_size;
      *lineptr = new_ptr;
    }

    ((unsigned char *) (*lineptr))[pos++] = c;
    if (c == delimiter) {
      break;
    }

    c = getc (stream);
  }

  (*lineptr)[pos] = '\0';
  return pos;
}

static ssize_t
getline (char **lineptr, size_t *n, FILE *stream)
{
  return getdelim (lineptr, n, '\n', stream);
}

static char *
strsep (char **stringp, const char *delim)
{
  char *current;
  char *original = *stringp;

  if (*stringp == NULL) {
    return NULL;
  }

  current = *stringp;
  while (1) {
    /* Delimiter not found in string: reset *stringp to NULL */
    if (*current == '\0') {
      *stringp = NULL;
      break;
    }

    /* Delimiter found: overwrite delimiter and reset *stringp to current location */
    if (*current == *delim) {
      *current = '\0';
      *stringp = current + 1;
      break;
    }

    current++;
  }

  return original;
}

#endif /* !T8_WINDOWS_H */