/* Agent Tcl
   Bob Gray
   29 January 1997

   agentAgentId.cc

   This file implements the class AgentId.

   Copyright (c) 1995-1997, Robert S. Gray Dartmouth College

   See the file "agent.terms" for information on usage and redistribution
   of this file and for a DISCLAIMER OF ALL WARRANTIES.
*/

#ifndef NO_PRAGMAS
#pragma implementation
#endif

#include "agentAgentId.h"       // interface definition
#include "genUtility.h"

UINT_32 AgentIdPacker::getPackedSize (void)
{
    UINT_32 len;
    UINT_32 size;

	// IP address, numeric id and two string lengths

    size = 4 * sizeof(UINT_32);

	// agent machine and name

    if ((len = m_agentId.m_serverName.length()) != 0) {
	size += len;
    }

    if ((len = m_agentId.m_name.length()) != 0) {
	size += len;
    }

    return (size);
}

char * AgentIdPacker::pack (char *bp)
{
    UINT_32 hostLong;
    UINT_32 netLong;

	/* machine name */

    hostLong = m_agentId.m_serverName.length();
    netLong = htonl (hostLong);
    bp = fast_memcpy (bp, (char *) &netLong, sizeof(UINT_32));
 
    if (hostLong != 0) {
	bp = fast_memcpy (bp, m_agentId.m_serverName.value(), hostLong);
    }

    	/* IP address */

    bp = fast_memcpy (bp, (char *) &m_agentId.m_serverIp, sizeof(UINT_32));

	/* agent name */

    hostLong = m_agentId.m_name.length();
    netLong = htonl (hostLong);
    bp = fast_memcpy (bp, (char *) &netLong, sizeof(UINT_32));
 
    if (hostLong != 0) {
	bp = fast_memcpy (bp, m_agentId.m_name.value(), hostLong);
    }

 	/* agent id */

    netLong = ntohl (m_agentId.m_id);
    bp = fast_memcpy (bp, (char *) &netLong, sizeof(UINT_32));
    return (bp);
}

char *AgentIdUnpacker::unpack (char *bp, char *end_bp)
{
    UINT_32 hostLong;

	/* get the machine name */

    if ((bp = breakout_long (bp, end_bp, hostLong)) == NULL) {
	return (NULL);
    }

    if (bp + hostLong > end_bp) {
	return (NULL);
    }

    m_agentId.m_serverName.append (bp, hostLong);
    bp += hostLong;

	/* get the IP address */

    if ((bp = breakout_ip (bp, end_bp, m_agentId.m_serverIp)) == NULL) {
	return (NULL);
    }

	/* get the agent name */

    if ((bp = breakout_long (bp, end_bp, hostLong)) == NULL) {
	return (NULL);
    }

    if (bp + hostLong > end_bp) {
	return (NULL);
    }

    m_agentId.m_name.append (bp, hostLong);
    bp += hostLong;

	/* get the agent id */

    if ((bp = breakout_long (bp, end_bp, m_agentId.m_id)) == NULL) {
	return (NULL);
    }

    return (bp);
}
