#include "XercesStr.h"
#include <BasicUtils/BasicException.h>

#include <xercesc/util/XMLString.hpp>
XERCES_CPP_NAMESPACE_USE;

using namespace std;

XercesStr::XercesStr(const XMLCh *const str) {
  local = 0;
  generic = XMLString::replicate(str);
}

XercesStr::XercesStr(const string str) {
  generic = 0;
  local = XMLString::replicate(str.c_str());
}

XercesStr::XercesStr(const char *str) {
  generic = 0;
  local = XMLString::replicate(str);
}

XercesStr::~XercesStr() {
  if (local) XMLString::release(&local);
  if (generic) XMLString::release(&generic);
}

const char *XercesStr::localForm() const {
  if (local) return local;
  if (generic)
    return ((XercesStr *)this)->local = XMLString::transcode(generic);
  return "";
}

const XMLCh *XercesStr::genericForm() const {
  if (generic) return generic;
  if (local)
    return ((XercesStr *)this)->generic = XMLString::transcode(local);
  return (XMLCh *)"";
}


void XercesStr::convert(const XMLCh *const src, std::string &dest) {
  char *cStr = XMLString::transcode(src);

  dest = cStr;
  XMLString::release(&cStr);
}

void XercesStr::convert(const XMLCh *const src, std::string &dest,
			const unsigned int length) {
  char *cStr = new char[length + 1];

  ASSERT_OR_THROW("Failed to convert!",
		  XMLString::transcode(src, cStr, length));
  dest = cStr;
  
  delete cStr;
}
