/*
 * © Copyright 1996-2012 ECMWF.
 *
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 * In applying this licence, ECMWF does not waive the privileges and immunities
 * granted to it by virtue of its status as an intergovernmental organisation nor
 * does it submit to any jurisdiction.
 */

#include "mars.h"
/* This should be included from the proper file */

typedef enum tag
{
    tag_zero,
    tag_start_obj,
    tag_end_obj,
    tag_char,
    tag_unsigned_char,
    tag_int,
    tag_unsigned_int,
    tag_short,
    tag_unsigned_short,
    tag_long,
    tag_unsigned_long,
    tag_long_long,
    tag_unsigned_long_long,
    tag_float,
    tag_double,
    tag_string,
    tag_blob,
    tag_exception,
    tag_start_rec,
    tag_end_rec,
    tag_eof,
    last_tag
} tag;

static char* tag_names[] = {
    "0",
    "start of object",
    "end of object",
    "char",
    "unsigned char",
    "int",
    "unsigned int",
    "short",
    "unsigned short",
    "long",
    "unsigned long",
    "long long",
    "unsigned long long",
    "float",
    "double",
    "string",
    "blob",
    "exception",
    "start of record",
    "end of record",
    "end of file",
};

/* Write --------------------------- */

static void stream_putbytes(mstream* s, void* p, int len) {
    if (s->write(s->data, p, len) != len)
        s->error = -2;
    else
        s->out += len;
}

static void stream_putchar(mstream* s, unsigned char c) {
    stream_putbytes(s, &c, 1);
}

static void stream_putlong(mstream* s, unsigned long p) {
    if (sizeof(unsigned long) != 4) {
        if (sizeof(unsigned int) == 4) {
            unsigned int x = htonl(p);
            stream_putbytes(s, &x, sizeof(x));
        }
        else if (sizeof(unsigned short) == 4) {
            unsigned short x = htons(p);
            stream_putbytes(s, &x, sizeof(x));
        }
        else {
            marslog(LOG_EXIT, "Cannot run on this architecture");
        }
    }
    else {
        p = htonl(p);
        stream_putbytes(s, &p, sizeof(p));
    }
}

static void stream_write_tag(mstream* s, tag t) {
    stream_putchar(s, (unsigned char)t);
}

void stream_write_char(mstream* s, char c) {
    stream_write_tag(s, tag_char);
    stream_putchar(s, c);
}

void stream_write_uchar(mstream* s, unsigned char c) {
    stream_write_tag(s, tag_unsigned_char);
    stream_putchar(s, c);
}

void stream_write_int(mstream* s, int c) {
    stream_write_tag(s, tag_int);
    stream_putlong(s, c);
}

void stream_write_uint(mstream* s, unsigned int c) {
    stream_write_tag(s, tag_unsigned_int);
    stream_putlong(s, c);
}

void stream_write_long(mstream* s, long c) {
    stream_write_tag(s, tag_long);
    stream_putlong(s, c);
}

void stream_write_ulong(mstream* s, unsigned long c) {
    stream_write_tag(s, tag_unsigned_long);
    stream_putlong(s, c);
}

void stream_write_longlong(mstream* s, long64 n) {
    unsigned long hi = (n >> 32);
    unsigned long lo = (n & 0xffffffff);

    stream_write_tag(s, tag_long_long);
    stream_putlong(s, hi);
    stream_putlong(s, lo);
}

void stream_write_ulonglong(mstream* s, ulong64 n) {
    unsigned long hi = (n >> 32);
    unsigned long lo = (n & 0xffffffff);

    stream_write_tag(s, tag_unsigned_long_long);
    stream_putlong(s, hi);
    stream_putlong(s, lo);
}

union Double {
    double d;
#if __SIZEOF_LONG__ == 4
    struct {
        unsigned long hi;
        unsigned long lo;
    } s;
#else
    struct {
        unsigned int hi;
        unsigned int lo;
    } s;
#endif
};

void stream_write_double(mstream* s, double x) {
    union Double d;
    stream_write_tag(s, tag_double);
    if (sizeof(d.d) != 2 * sizeof(d.s.hi)) {
        marslog(LOG_EXIT, "Double is foobar");
    }
    /* ASSERT(sizeof(d.d) == 2*sizeof(d.s.hi)); */
    d.d = x;
    stream_putlong(s, d.s.hi);
    stream_putlong(s, d.s.lo);
}

void stream_write_short(mstream* s, short c) {
    stream_write_tag(s, tag_short);
    stream_putlong(s, c);
}

void stream_write_ushort(mstream* s, unsigned short c) {
    stream_write_tag(s, tag_unsigned_short);
    stream_putlong(s, c);
}

void stream_write_string(mstream* s, const char* p) {
    int len = p ? strlen(p) : 0;

    stream_write_tag(s, tag_string);
    stream_putlong(s, len);
    while (p && *p)
        stream_putchar(s, (unsigned char)*p++);
}

void stream_write_blob(mstream* s, const void* d, long len) {
    const char* p = (const char*)d;
    stream_write_tag(s, tag_blob);
    stream_putlong(s, len);
    while (len-- > 0)
        stream_putchar(s, (unsigned char)*p++);
}

void stream_write_start(mstream* s, const char* p) {
    stream_write_tag(s, tag_start_obj);
    stream_write_string(s, p);
}

void stream_write_end(mstream* s) {
    stream_write_tag(s, tag_end_obj);
}


/* Read --------------------------- */

static void stream_getbytes(mstream* s, void* p, int len) {
    char* q = (char*)p;
    while (len > 0) {
        int l = s->read(s->data, q, len);
        if (l <= 0) {
            marslog(LOG_EROR | LOG_PERR, "Failed to read %d", len);
            s->error = -32;
            return;
        }

        q += l;
        len -= l;
        s->in += l;
    }
}

static unsigned char stream_getchar(mstream* s) {
    unsigned char c = 0;
    stream_getbytes(s, &c, 1);
    return c;
}

static unsigned long stream_getlong(mstream* s) {
    unsigned long l = 0;

    if (sizeof(unsigned long) != 4) {
        if (sizeof(unsigned int) == 4) {
            unsigned int x;
            stream_getbytes(s, &x, sizeof(x));
            l = ntohl(x);
        }
        else if (sizeof(unsigned short) == 4) {
            unsigned short x;
            stream_getbytes(s, &x, sizeof(x));
            l = ntohs(x);
        }
        else {
            marslog(LOG_EXIT, "Cannot run on this architecture");
        }
    }
    else {
        long p;
        stream_getbytes(s, &p, sizeof(p));
        l = ntohl(p);
    }

    return l;
}

static void stream_read_tag(mstream* s, tag t) {
    unsigned char c = stream_getchar(s);
    if (t != (enum tag)c) {
        char* name = c < NUMBER(tag_names) ? tag_names[c] : "(invalid)";
        marslog(LOG_EROR, "Bad tag '%s' (should be '%s')", name, tag_names[t]);
        s->error = -2;
    }
}

char stream_read_char(mstream* s) {
    stream_read_tag(s, tag_char);
    return stream_getchar(s);
}

unsigned char stream_read_uchar(mstream* s) {
    stream_read_tag(s, tag_unsigned_char);
    return stream_getchar(s);
}

int stream_read_int(mstream* s) {
    stream_read_tag(s, tag_int);
    return (int)stream_getlong(s);
}

unsigned int stream_read_uint(mstream* s) {
    stream_read_tag(s, tag_unsigned_int);
    return (unsigned int)stream_getlong(s);
}

long stream_read_long(mstream* s) {
    stream_read_tag(s, tag_long);
    return (long)stream_getlong(s);
}

unsigned long stream_read_ulong(mstream* s) {
    stream_read_tag(s, tag_unsigned_long);
    return (unsigned long)stream_getlong(s);
}

short stream_read_short(mstream* s) {
    stream_read_tag(s, tag_short);
    return (short)stream_getlong(s);
}

unsigned short stream_read_ushort(mstream* s) {
    stream_read_tag(s, tag_unsigned_short);
    return (unsigned short)stream_getlong(s);
}

const char* stream_read_string(mstream* s) {
    static char* p   = NULL;
    static long plen = -1;

    char* q;
    long len;

    stream_read_tag(s, tag_string);
    if (s->error)
        return "<invalid-string>";

    len = stream_getlong(s);
    if (s->error)
        return "<invalid-string-length>";


    if (p == NULL || len >= plen) {
        FREE(p);
        p = MALLOC(plen = len + 1);
    }

    q = p;
    while (len-- > 0)
        *q++ = stream_getchar(s);
    *q = 0;

    return p;
}

const void* stream_read_blob(mstream* s, long* size) {
    static char* p   = NULL;
    static long plen = -1;

    char* q;
    long len;

    stream_read_tag(s, tag_blob);
    if (s->error) {
        *size = -1;
        return 0;
    }

    len = stream_getlong(s);
    if (s->error) {
        *size = -1;
        return 0;
    }


    if (p == NULL || len > plen) {
        if (len > 0) /* It seems there can be 0 length blobs (?) */
        {
            FREE(p);
            p = MALLOC(plen = len);
        }
    }
    *size = len;

    q = p;
    while (len-- > 0)
        *q++ = stream_getchar(s);

    return p;
}


long64 stream_read_longlong(mstream* s) {
    unsigned long hi;
    unsigned long lo;
    long64 n;

    stream_read_tag(s, tag_long_long);

    hi = stream_getlong(s);
    lo = stream_getlong(s);

    n = hi;
    n <<= 32;
    n |= lo;

    return n;
}

ulong64 stream_read_ulonglong(mstream* s) {
    unsigned long hi;
    unsigned long lo;
    ulong64 n;

    stream_read_tag(s, tag_unsigned_long_long);

    hi = stream_getlong(s);
    lo = stream_getlong(s);

    n = hi;
    n <<= 32;
    n |= lo;

    return n;
}


const char* stream_read_start(mstream* s) {
    stream_read_tag(s, tag_start_obj);
    return s->error ? 0 : stream_read_string(s);
}

void stream_read_end(mstream* s) {
    stream_read_tag(s, tag_end_obj);
}


void make_socket_stream(mstream* s, int* soc) {
    s->error = 0;
    s->read  = readtcp;
    s->write = writetcp;
    s->data  = soc;
    s->in    = 0;
    s->out   = 0;
}

static int readfile(void* p, void* buf, int len) {
    return fread(buf, 1, len, (FILE*)p);
}

static int writefile(void* p, void* buf, int len) {
    return fwrite(buf, 1, len, (FILE*)p);
}

void make_file_stream(mstream* s, FILE* f) {
    s->error = 0;
    s->read  = readfile;
    s->write = writefile;
    s->data  = f;
    s->in    = 0;
    s->out   = 0;
}
