/*
 * Copyright (C) 2015 by the University of Southern California
 * $Id: net_msg.cc 24038 2015-05-17 03:00:48Z liangzhu $
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License along           
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. 
 * 
 */

#include "net_msg.hh"
#include <stdio.h>
#include <string.h>
#include <assert.h>

net_msg::net_msg(uint8_t *m, size_t l)
{
  data = m;
  len = l;
};

net_msg::net_msg(size_t l)
{
  net_msg();
  assert(data == NULL);
  create(l);
};

net_msg::net_msg()
{
  data = NULL;
  len = 0;
};

net_msg::~net_msg()
{
  clean();
};

void net_msg::create(size_t l)
{
  clean();
  data = new uint8_t[l];
  assert(data != NULL);
  memset(data, 0, l);
  len = l;
}

void net_msg::clean()
{
  if (data != NULL) {
    delete[] data;
    data = NULL;
    len = 0;
  }
}

void net_msg::copy(uint8_t *m, size_t l, bool tcp)
{
  clean();
  size_t offset = (tcp ? 2 : 0);
  len = l + offset;
  data = new uint8_t[len];
  assert(data != NULL);
  if (tcp) {
    uint16_t ln = htons(l);
    memcpy(data, &ln, 2);
    memcpy(data + 2, m, l);
  } else {
    memcpy(data, m, l);
  }
}

void net_msg::append(uint8_t *d, size_t l)
{
  size_t old_len = len;
  uint8_t *old_data = new uint8_t[len];
  assert(old_data);
  memcpy(old_data, data, len);
  create(l + old_len);
  memcpy(data, old_data, old_len);
  memcpy(data + old_len, d, l);
  delete old_data;
}
