#ifndef MYLIBBUFFER_H /*************************************************************************** -*- c++ -*- **/
#define MYLIBBUFFER_H

/****************************************************************************************************************/

#include <stdio.h>
#include <stdarg.h>

class Buffer {
public:
  Buffer(int maxlen=0);
  Buffer(const char *src, int ln);
  ~Buffer();

public: // Attributes
  char *data(void) const  { return m_buf;     }
  int len(void) const     { return m_len;     }
  void setLen(int length);
  int size(void) const    { return m_size;    }
  int maxSize(void) const { return m_maxsize; }
  int remains(void) const { return m_maxsize - m_size; }

public: // Read
  unsigned char readByte(void);
  unsigned short readWord(void);
  unsigned long readLong(void);
  const char *readString(int len=-1);
  int readLine(char *buf, int bufsize);
  void rewind(void) { m_idx = 0; }
  bool valid(void) { return m_idx >= 0; }

public: // Write
  void append(unsigned char val);
  void append(unsigned short val);
  void append(unsigned long val);
  void append(const Buffer &b) { append(b.data(), b.len()); }
  void append(const char *str, int length);
  char *space(int bytes); // Makes room for more bytes, returns pointer into buffer
  void clear(bool also_free = true, int maxsize = -1);

  void printf(const char *fmt, ...);
  void vprintf(const char *fmt, va_list ap);

  void appendHtml(const char *str);

public: // File access
  bool slurp(const char *filename);
  bool save(const char *filename);

protected:
  bool grow(int sz); // Grow buffer by sz bytes

private:
  char *m_buf;
  int m_len;
  int m_idx;
  int m_size;
  int m_maxsize;
};

/****************************************************************************************************************/

#endif
