/*
  This file is part of CDO. CDO is a collection of Operators to
  manipulate and analyse Climate model Data.

  Copyright (C) 2003-2020 Uwe Schulzweida, <uwe.schulzweida AT mpimet.mpg.de>
  See COPYING file for copying and redistribution conditions.

  This program 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; version 2 of the License.

  This program 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.
*/
#ifndef LISTBUF_H
#define LISTBUF_H

#include <stdio.h>
#include <sys/stat.h>
#include <string>
#include <vector>

class ListBuffer
{
public:
  std::vector<char> buffer;
  std::string name;

  ListBuffer() {}
  ~ListBuffer() {}

  int
  read(FILE *fp, const char *_name)
  {
    const int filedes = fileno(fp);
    struct stat buf;
    size_t filesize = (fstat(filedes, &buf) == 0) ? (size_t) buf.st_size : 0;
    if (filesize == 0)
      {
        fprintf(stderr, "ListBuffer: empty stream: %s\n", _name);
        return -1;
      }

    this->buffer.resize(filesize);
    if (fread(buffer.data(), 1, filesize, fp) != filesize)
      {
        fprintf(stderr, "ListBuffer: read failed on %s!\n", _name);
        return -1;
      }

    if (_name) this->name = _name;

    return 0;
  }
};

#endif
