#ifndef _NETBUFFER_
#define _NETBUFFER_

#include "sys/sys"
#include "memory/memory"

#include "error/error"
#include "config/config"
#include "profiler/profiler"
#include "fdset/fdset"
#include "servertype/servertype"

/* A few defs when malloc() / realloc() are suspected to be not thread-safe.
 * The defines are used in eg. copy() and check_space(). */
#ifdef MISTRUST_MALLOC_THREADSAFE
#define LOCK_MALLOC  	Mutex::lock((void*)malloc)
#define UNLOCK_MALLOC  	Mutex::unlock((void*)malloc)
#else
#define LOCK_MALLOC
#define UNLOCK_MALLOC
#endif

class Netbuffer MEM(: public Memory) {
public:
    Netbuffer();
    Netbuffer (Netbuffer const &other);
    Netbuffer (string const &s);
    virtual ~Netbuffer();
    Netbuffer const &operator= (Netbuffer const &other);

    char charat(unsigned index) const;
    char operator[] (unsigned index) 	{ return charat(index); }

    char const *bufdata() const 	{ return buf_data; }
    unsigned bufsz() const 		{ return buf_sz; }

    unsigned netread (int fd, int timeout = 0);
    unsigned netwrite (int fd, int timeout) const;

    unsigned strfind (char const *s) const;
    unsigned charfind (char ch, unsigned start = 0) const;

    bool setchar(unsigned offset, char ch);
    void setstring(string const &s);

    string stringat(unsigned index, unsigned len);

    bool insertat(unsigned index, char const *s, unsigned len = 0);
    bool removeat(unsigned index, unsigned len = 1);

    void reset();


private:
    void copy (Netbuffer const &other);
    void destroy();

    void check_space(unsigned extra);
    string printable(char c) const;
    string printable() const;

    char *buf_data;
    unsigned buf_sz;
    unsigned buf_alloced;
};

#endif
