OpenTTCN/Developer corner/Implementing external functions/Skeletons/CPP/CD impl.cpp
From OpenTTCN
Home | Developer's corner | Knowledge base | Working documents | Documentation | OpenTTCN IDE | Tutorials | Training | How do I | Frequently asked questions | Technical support |
CD_impl.cpp
#include "CD_impl.h"
#include <StartHere.h>
#include <StartHereCD.h>
#include <tri/TriTypes.h>
#include <tci/TciValues.h>
#include <iostream>
#include <string>
using namespace ORG_ETSI_TTCN3_TCI;
using namespace ORG_ETSI_TTCN3_TRI;
using OpenTTCN::SDK::StartHere;
using OpenTTCN::SDK::StartHereCD;
CD_impl :: ~CD_impl()
{
}
TriMessage* CD_impl :: encode(const TciValue* value)
{
TriMessage* result = TriMessage::create();
TciTypeClass typeClass = value->getType().getTypeClass();
if (typeClass == TCI_CHARSTRING)
{
const CharstringValue* casted =
dynamic_cast<const CharstringValue*> (value);
std::string s = casted->getString();
s = s.substr(1, s.size() - 2);
const char* str = s.c_str();
long str_len = s.size();
long result_bits = (str_len + 2) << 3;
unsigned char* result_data = (unsigned char *) malloc(result_bits >> 3);
// String length, most significant byte first:
result_data[0] = (unsigned char) (str_len >> 8);
result_data[1] = (unsigned char) (str_len >> 0);
memcpy(result_data + 2, str, str_len);
result->setData(result_data, result_bits);
free(result_data);
}
else if (typeClass == TCI_INTEGER)
{
const IntegerValue* casted =
dynamic_cast<const IntegerValue*> (value);
long v = casted->getInt();
long v_len = sizeof(long);
long result_bits = v_len << 3;
unsigned char* result_data = (unsigned char *) malloc(v_len);
memcpy(result_data, &v, v_len);
result->setData(result_data, result_bits);
free(result_data);
}
else
{
StartHere::reportError("tciEncode(): Unrecognized value type class.");
}
return result;
}
TciValue* CD_impl :: decode(
const TriMessage* message,
const TciType* decHypothesis)
{
TciValue* result = 0;
TciTypeClass typeClass;
TciCdRequired* cdReq = StartHereCD::getTciCdRequired();
if (!decHypothesis)
{
StartHere::reportError("tciDecode(): Error: No decoding hypothesis.");
return 0;
}
typeClass = decHypothesis->getTypeClass();
const unsigned char* message_data = message->getData();
if (typeClass == TCI_CHARSTRING)
{
long str_len =
(((unsigned long) message_data[0]) << 8) |
(((unsigned long) message_data[1]) << 0);
std::string s((const char *) (message_data + 2), str_len);
CharstringValue* cs_result =
dynamic_cast<CharstringValue*> (cdReq->getCharstring().newInstance());
cs_result->setString("\"" + s + "\"");
result = cs_result;
}
else if (typeClass == TCI_INTEGER)
{
IntegerValue* iv_result =
dynamic_cast<IntegerValue*> (cdReq->getInteger().newInstance());
iv_result->setInt(*((long *) message_data));
result = iv_result;
}
else
{
StartHere::reportError("tciDecode(): Unrecognized hypothesis type class.");
}
return result;
}
