Click here to Skip to main content
15,884,237 members
Articles / Desktop Programming / MFC

FiveLoaves v1.0

Rate me:
Please Sign up or sign in to vote.
3.84/5 (10 votes)
2 Jul 20028 min read 84.7K   4.4K   49  
FiveLoaves is an Internet utility designed to meet the most common needs of internet users - primarily secure connectivity
// --------------------------------------------------------------------------
//					www.UnitedBusinessTechnologies.com
//			  Copyright (c) 1998 - 2002  All Rights Reserved.
//
// Source in this file is released to the public under the following license:
// --------------------------------------------------------------------------
// This toolkit may be used free of charge for any purpose including corporate
// and academic use.  For profit, and Non-Profit uses are permitted.
//
// This source code and any work derived from this source code must retain 
// this copyright at the top of each source file.
// 
// UBT welcomes any suggestions, improvements or new platform ports.
// email to: XMLFoundation@UnitedBusinessTechnologies.com
// --------------------------------------------------------------------------

#ifndef _G_STRING_HH_
#define _G_STRING_HH_

#ifndef ___max
#define ___max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef ___min
#define ___min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

#ifndef _WIN32
	#define	__int64 long long
#endif

#include "GList.h"

#include <stdarg.h> // for va_list declaration


// 2X faster than using an ostream with a preallocated strstreambuf.
// 10X more portable. -- Designed for speedo. :)
class GString
{
protected:
	char *_str;
	long  _len;
	long  _max;
	void resize();

public:
	// System wide GString settings that affect all GStrings on all threads
	static GString	g_FloatFmt;			// "%.6g"
	static GString	g_DoubleFmt;		// "%.6g"
	static GString	g_LongDoubleFmt;	// "%.6Lg"

public:
	// constructs an empty string
	GString(long nInitialSize = 256);

	// constructs a copy of the source string 
	GString(const GString &src);
	GString(const GString &src, int nCnt);

	// constructs a copy of the character string
	GString(const char *src);
	GString(const char *src, int nCnt);

	// constructs a string with ch repeated nCnt times
	GString(char ch, short nCnt);

	// frees the buffer
	virtual ~GString();
	
	// Load this GString from an file
	int FromFile(const char* pzFileName, bool bThrowOnFail = 1);
	// Save this GString to a file - overwrite if file exists
	int ToFile(const char* pzFileName, bool bThrowOnFail = 1);
	// Append this GString to a file - create file if not existing
	int ToFileAppend(const char* pzFileName, bool bThrowOnFail = 1);

// formatting functions
	/*
		The mask can contain any printable character and is terminated 
		by a null.

		The character '_' in the mask will be replaced by a single character
		in the source string.  The character '*' will be replaced by the
		remaining characters in the source string.  Both '_' and '*' can be
		escaped using the character '\'.  You can escape the escape character
		with an escape character, i.e. "\\".

		Some example masks:

		Phone number mask: (___)___-____ [ext:*]
		Socialism security mask: ___-__-____

		If the source data is larger than the mask and the mask doesn't contain
		the wild character '*' the source data will be truncated.
	*/
	void MergeMask(const char *szSrc, const char *szMask);

	/*
		FormatNumber formats the value of the GString using the format
		string specified by szFormat
	*/
	void FormatNumber(const char *szFormat, 
					  char decimal_separator = '.',
					  char grouping_separator = ',',
					  char minus_sign = '-',
					  const char *NaN = "NaN",
					  char zero_digit = '0',
					  char digit = '#',
					  char pattern_separator = ';',
					  char percent = '%',
					  char permille = '?');

	// Call this member function to write formatted data to a 
	// GString in the same way that sprintf formats data into 
	// a C-style character array. 
	void Format(const char *lpszFormat, ...);
	void FormatV(const char *lpszFormat, va_list argList);

	// removes leading and trailing quotation's from string
	void StripQuotes();

	// assignment operators
	GString & operator=(char);
	GString & operator=(__int64);
	GString & operator=(const char *);
	GString & operator=(const signed char *);
	GString & operator=(unsigned char);
	GString & operator=(signed char);
	GString & operator=(short);
	GString & operator=(unsigned short);
	GString & operator=(int);
	GString & operator=(unsigned int);
	GString & operator=(long);
	GString & operator=(unsigned long);
	GString & operator=(float);
	GString & operator=(double);
	GString & operator=(long double);
	GString & operator=(const GString &);

	// append operators, enables a GString to mimic ostream
	// write() appends to the GString to mimic ostream
	void write(const char *,int);
	GString & operator<<(__int64);
	GString & operator<<(const char *);
	GString & operator<<(const signed char *);
	GString & operator<<(char);
	GString & operator<<(unsigned char);
	GString & operator<<(signed char);
	GString & operator<<(short);
	GString & operator<<(unsigned short);
	GString & operator<<(int);
	GString & operator<<(unsigned int);
	GString & operator<<(long);
	GString & operator<<(unsigned long);
	GString & operator<<(float);
	GString & operator<<(double);
	GString & operator<<(long double);
	GString & operator<<(const GString &);

	GString & operator+=(__int64);
	GString & operator+=(const signed char *);
	GString & operator+=(const char *);
	GString & operator+=(char);
	GString & operator+=(unsigned char);
	GString & operator+=(signed char);
	GString & operator+=(short);
	GString & operator+=(unsigned short);
	GString & operator+=(int);
	GString & operator+=(unsigned int);
	GString & operator+=(long);
	GString & operator+=(unsigned long);
	GString & operator+=(float);
	GString & operator+=(double);
	GString & operator+=(long double);
	GString & operator+=(const GString &);

	// friend functions for addition
	friend GString operator+(GString &, GString &);
	friend GString operator+(GString &, const char *);
	friend GString operator+(const char *, GString &);
	friend GString operator+(GString &, const signed char *);
	friend GString operator+(const signed char *, GString &);
	friend GString operator+(GString &, char);
	friend GString operator+(char, GString &);
	friend GString operator+(GString &, unsigned char);
	friend GString operator+(unsigned char, GString &);
	friend GString operator+(GString &, signed char);
	friend GString operator+(signed char, GString &);

	// Comparitive operators with other GString classes
	int operator >  (const GString &) const;
	int operator >= (const GString &) const;
	int operator == (const GString &) const;
	int operator <  (const GString &) const;
	int operator <= (const GString &) const;
	int operator != (const GString &) const;

	// Returns zero if the strings are identical, 
	// < 0 if this GString object is less than lpsz, 
	// or > 0 if this GString object is greater than lpsz.
	int Compare(const char *) const;
	int Compare(GString &) const;
	int CompareNoCase(const char *) const;
	int CompareNoCase(const GString &) const;

	// Comparitive operators with standard GString
	int operator >  (const char *) const;
	int operator >= (const char *) const;
	int operator == (const char *) const;
	int operator <  (const char *) const;
	int operator <= (const char *) const;
	int operator != (const char *) const;

	// returns the length of the string
	long Length() const { return _len; }
	long GetLength() const { return _len; } // for MFC'ers
	
	// escapes <>&"\ in 'this' with &#ascii-number;
	void EscapeXMLReserved();
	// appends pzSource onto 'this', escaping <>&"\ with &#ascii;
	// nLen = # bytes to append from pzSource or -1 to append until a null.
	void AppendEscapeXMLReserved(const char *pzSource, int nLen = -1);
	void AppendXMLTabs( int nTabs );


	// returns a character pointer to the string�s data.
	inline operator const char *() const { return _str; }
	// same as a (const char *) cast above - easier to use through a pointer ->
	// turns this [ (const char *)(*myStr) ] into [ myStr->StrVal() ]
	const char *StrVal() const { return _str; }

	// given s == "Hello World" 
	// s.StartingAt(6) == "World"
	// The string is not trimmed, just indexed. s still == "Hello World"
	const char *StartingAt( int n0BasedIndex ) {return (n0BasedIndex < _len) ? &_str[n0BasedIndex] : 0;}

	// returns true if the string is empty
	bool IsEmpty() const { return _len == 0; }

	// Makes this GString object an empty string.
	void Empty() { _len = 0; _str[_len] = 0; }

	// Load an error from the active ErrorProfile() owned by GException.cpp
	void LoadResource(const char* szSystem, int error, ...);

	// overloaded subscript ([]) operator returns a single character 
	// specified by the zero-based index in nIndex. 
	char& operator[](int nIdx);
	char GetAt(int nIdx) const;
	// The SetAt member function overwrites a single character 
	// specified by an zero based index number. 
	void SetAt(int nIdx, char ch);

	// Pads the string object on the left with ch to make the string
	// a minimum of n character's in length
	void PadLeft(int nCnt, char ch = ' ');
	// Pads the string on the left with nCnt of ch
	void Prepend(int nCnt, char ch = ' ');
	// Removes the character ch from the left side of the string.
	void TrimLeft(char ch = ' ', short nCnt = -1);
	// trim white space from the left of the string
	void TrimLeftWS(); 
	// Pads the string object on the right with ch to make the string
	// a minimum of n character's in length
	void PadRight(int nCnt, char ch = ' ');
	// Pads the string on the right with nCnt of ch
	void Append(int nCnt, char ch = ' ');
	// Removes the character ch from the right side of the string. (max nCnt)
	void TrimRight(char ch = ' ', short nCnt = -1);
	// Shortens the sting by nCnt bytes
	void TrimRightBytes(short nCnt);

	// Extracts the first (that is, leftmost) nCount characters from 
	// this GString object and returns a copy of the extracted substring. 
	// If nCount exceeds the string length, then the entire string is extracted. 
	GString Left (int nCnt) const;
	// Extracts a substring of length nCount characters from this GString object, 
	// starting at position nFirst (zero-based). 
	GString Mid  (int nFirst) const;
	GString Mid  (int nFirst, int nCnt) const;
	// Extracts the last (that is, rightmost) nCount characters from this GString 
	// object and returns a copy of the extracted substring. If nCount exceeds the
	// string length, then the entire string is extracted. 
	GString Right(int nCnt) const;
	void TrimRightWS(); // trim white space from the end of the string

	// Converts this GString object to an uppercase string.
	void MakeUpper();
	// Converts this GString object to a lowercase string.
	void MakeLower();
	// Reverses the characters in the GString
	void MakeReverse();

	int FindSubStringCaseInsensitive( const char * lpszSub, int nStart = 0 ) const;
	int Find( char ch ) const;
	int Find( const char * lpszSub ) const;
	int Find( char ch, int nStart ) const;
	int Find( const char * pstr, int nStart ) const;

	void Insert( int nIndex, char ch );
	void Insert( int nIndex, const char * pstr );

	void Remove ( int nStart, int nLen );
	void Replace( char chWhat, char chRep );
	void Replace( const char * szWhat, char chRep );
	void Replace( const char * szWhat, const char *szRep );
	void ReplaceCaseInsensitive( const char * szWhat, const char *szRep, int nStart = 0 );
	void Replace( char chWhat, const char *szRep );

	// replace each char in pzReplaceChars with %nn where
	// nn is a two byte hex value of the byte that was replaced.
	// example: GString s("ABC");  
	//			s.EscapeWithHex("XYZB");
	//			s == "A%42C"
	//	42 is hex for 66 that is the ASCII of a B, the only matching escape in XYZB.
	//
	// another example: GString s("A\nC");  
	//			s.EscapeWithHex("\r\n\t");
	//			s == "A%0AC"
	//
	const char *EscapeWithHex(const char *pzEscapeChars);
	void UnEscapeHexed();

	// x-path
	void NormalizeSpace();
	void Translate(const char *szConvert, const char *szTo);

protected:
	// allocated along with 'this' to reduces malloc/free calls.
	// When a GString < 256 bytes is constructed, _initialbuf is used.
	// As the string grows beyond 256, _strIsOnHeap becomes true and
	// _str no longer points into _initialbuf, but now is on the heap.
	char _initialbuf[260];
	int _strIsOnHeap; // false when we're working in our _initialbuf

};

#endif //_G_STRING_HH_

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder United Business Technologies
United States United States
http://about.me/brian.aberle
https://www.linkedin.com/in/brianaberle
http://SyrianRue.org/Brian

Comments and Discussions