/***************************************************************************
                           ciconv.h  -  DCLib C++ iconv wrapper
                             -------------------
    begin                : Thu Sep 20 2007
    copyright            : (C) 2007 by Edward Sheldrake
    email                : ejs1920@yahoo.co.uk
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifndef CICONV_H
#define CICONV_H
 
/**
 * @author Edward Sheldrake
 *
 * It converts between encodings.
 * 
 * The input is a CString and the output is another CString, really
 * it would have been better for a CString to be in some defined
 * encoding.
 */

#include <dclib/dcos.h>
#include <dclib/core/cstring.h>

#include <iconv.h>
#include <string.h>

class CIconv {

public:
	/**
	 * Constructor using specified encodings.
	 * Note that from and to are the other way around
	 * compared to the iconv_open.
	 */
	CIconv( const CString & from, const CString & to );
	/** Destructor */
	~CIconv();
	
	/** Encode text between the encodings. */
	CString encode( const CString & text );
	/**
	 * Encode text between the encodings.
	 * This one is slower than the first, since it needs to call strlen,
	 * but faster than creating a CString since there's no copying of the input.
	 */
	CString encode( const char * data );

private:
	/** iconv structure used for encoding */
	iconv_t cd;
	/** facility to disable encoding */
	bool disabled;
	/**
	 * Does the actual encoding.
	 */
	CString encode( const char * data, const size_t len );
};

/** inline functions */

/** */
inline CString CIconv::encode( const CString & text )
{
	if ( disabled )
	{
		return text;
	}
	else
	{
		return encode( text.Data(), text.Length() );
	}
}

/** */
inline CString CIconv::encode( const char * data )
{
	if ( disabled )
	{
		return CString(data);
	}
	else
	{
		return encode( data, strlen(data) );
	}
}
#endif // CICONV_H
