yapf/str.hpp
author KUDr
Tue, 02 Jan 2007 18:40:37 +0000
branchcustombridgeheads
changeset 5641 d4d00a16ef26
parent 5626 1811beeb472f
permissions -rw-r--r--
(svn r7755) [cbh] - Fix: [NTP] now works with cbh (needs testing)
/* $Id$ */

#ifndef  STR_HPP
#define  STR_HPP

#include <errno.h>
#include <stdarg.h>

#include "blob.hpp"
#include "strapi.hpp"


// simple string implementation
template <typename Tchar, bool TcaseInsensitive>
struct CStrT : public CBlobT<Tchar>
{
	typedef CBlobT<Tchar> base;
	typedef CStrApiT<Tchar, TcaseInsensitive> Api;
	typedef typename base::size_t size_t;
	typedef typename base::OnTransfer OnTransfer;


	FORCEINLINE CStrT(const Tchar* str = NULL) {AppendStr(str);}
	FORCEINLINE CStrT(const Tchar* str, size_t num_chars) : base(str, num_chars) {base::FixTail();}
	FORCEINLINE CStrT(const Tchar* str, const Tchar* end) : base(str, end - str) {base::FixTail();}
	FORCEINLINE CStrT(const CBlobBaseSimple& src) : base(src) {base::FixTail();}
	/** Take ownership constructor */
	FORCEINLINE CStrT(const OnTransfer& ot) : base(ot) {}
	FORCEINLINE Tchar* GrowSizeNC(size_t count) {Tchar* ret = base::GrowSizeNC(count); base::FixTail(); return ret;}
	FORCEINLINE void AppendStr(const Tchar* str) {if (str != NULL && str[0] != '\0') base::Append(str, (size_t)Api::StrLen(str)); base::FixTail();}
	FORCEINLINE CStrT& operator = (const Tchar* src) {base::Clear(); Append(src); return *this;}
	FORCEINLINE bool operator < (const CStrT &other) const {return (Api::StrCmp(base::Data(), other.Data()) < 0);}

	int FormatL(const Tchar *fmt, va_list args)
	{
		size_t addSize = Api::StrLen(fmt);
		if (addSize < 16) addSize = 16;
		addSize += addSize > 1;
		int ret;
		do {
			Tchar *buf = MakeFreeSpace(addSize);
			ret = Api::SPrintFL(buf, base::GetReserve(), fmt, args);
			addSize *= 2;
		} while(ret < 0 && (errno == ERANGE || errno == 0));
		if (ret > 0) {
			GrowSizeNC(ret);
		} else {
//			int err = errno;
			base::FixTail();
		}
		return ret;
	}

	int Format(const Tchar *format, ...)
	{
		va_list args;
		va_start(args, format);
		int ret = FormatL(format, args);
		va_end(args);
		return ret;
	}

};

typedef CStrT<char   , false> CStrA;
typedef CStrT<char   , true > CStrCiA;
typedef CStrT<wchar_t, false> CStrW;
typedef CStrT<wchar_t, true > CStrCiW;

#endif /* STR_HPP */