#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include <iiimp-data.h>

#include "iiimp-dataP.h"


IIIMP_ccdef *
iiimp_ccdef_new(
    IIIMP_data_s *	data_s,
    IIIMP_string *	contents)
{
    IIIMP_ccdef *	ccdef;

    ccdef = (IIIMP_ccdef *)malloc(sizeof (IIIMP_ccdef));
    if (NULL == ccdef) {
	data_s->status = IIIMP_DATA_MALLOC_ERROR;
	return NULL;
    }

    if (NULL == contents) {
	ccdef->nbyte = 4;
    } else {
	ccdef->nbyte = contents->nbyte;
    }

    ccdef->contents = contents;

    return ccdef;
}


void
iiimp_ccdef_delete(IIIMP_data_s * data_s, IIIMP_ccdef * ccdef)
{
    if (NULL == ccdef) return;
    iiimp_string_delete(data_s, ccdef->contents);
    free(ccdef);
    return;

}


void
iiimp_ccdef_pack(
    IIIMP_data_s *	data_s,
    IIIMP_ccdef *	m,
    size_t *		nbyte,
    uchar_t **		ptr)
{
    size_t		rest;
    uchar_t *		p;

    rest = *nbyte;
    p = *ptr;

    iiimp_string_pack(data_s, m->contents, &rest, &p);

    *nbyte = rest;
    *ptr = p;

    return;
}


IIIMP_ccdef *
iiimp_ccdef_unpack(
    IIIMP_data_s *	data_s,
    size_t *		nbyte,
    const uchar_t **	ptr,
    size_t		nbyte_max)
{
    IIIMP_ccdef *	ccdef;
    size_t		rest;
    const uchar_t *	p;

    rest = nbyte_max;
    p = *ptr;

    if ((*nbyte < rest) || (rest < (4 + 4 + 4 + 4))) {
	data_s->status = IIIMP_DATA_INVALID;
	return NULL;
    }

    ccdef = (IIIMP_ccdef *)malloc(sizeof (IIIMP_ccdef));
    if (NULL == ccdef) {
	data_s->status = IIIMP_DATA_MALLOC_ERROR;
	return NULL;
    }

    ccdef->contents = iiimp_string_unpack(data_s, &rest, &p, rest);
    if (NULL == ccdef->contents) {
	free(ccdef);
	return NULL;
    }

    *nbyte = rest;
    *ptr = p;

    return ccdef;
}


void
iiimp_ccdef_print(
    IIIMP_data_s *	data_s,
    IIIMP_ccdef *	m)
{
    if (NULL == m) return;

    iiimp_string_print(data_s, m->contents);
}


/* Local Variables: */
/* c-file-style: "iiim-project" */
/* End: */
