Reorganized source tree. Moved client.cpp into cmd/synergy as

synergy.cpp and server.cpp into cmd/synergyd as synergyd.cpp.
Moved and renamed related files.  Moved remaining source files
into lib/....  Modified and added makefiles as appropriate.
Result is that library files are under lib with each library
in its own directory and program files are under cmd with each
command in its own directory.
This commit is contained in:
crs
2002-07-30 16:52:46 +00:00
parent 9792d35a6b
commit fee4095624
201 changed files with 367 additions and 375 deletions

73
lib/base/BasicTypes.h Normal file
View File

@@ -0,0 +1,73 @@
#ifndef BASICTYPES_H
#define BASICTYPES_H
#include "common.h"
//
// pick types of particular sizes
//
#if !defined(TYPE_OF_SIZE_1)
# if SIZEOF_CHAR == 1
# define TYPE_OF_SIZE_1 char
# endif
#endif
#if !defined(TYPE_OF_SIZE_2)
# if SIZEOF_INT == 2
# define TYPE_OF_SIZE_2 int
# else
# define TYPE_OF_SIZE_2 short
# endif
#endif
#if !defined(TYPE_OF_SIZE_4)
# if SIZEOF_INT == 4
# define TYPE_OF_SIZE_4 int
# else
# define TYPE_OF_SIZE_4 long
# endif
#endif
//
// verify existence of required types
//
#if !defined(TYPE_OF_SIZE_1)
# error No 1 byte integer type
#endif
#if !defined(TYPE_OF_SIZE_2)
# error No 2 byte integer type
#endif
#if !defined(TYPE_OF_SIZE_4)
# error No 4 byte integer type
#endif
//
// make typedefs
//
// except for SInt8 and UInt8 these types are only guaranteed to be
// at least as big as indicated (in bits). that is, they may be
// larger than indicated.
//
typedef signed TYPE_OF_SIZE_1 SInt8;
typedef signed TYPE_OF_SIZE_2 SInt16;
typedef signed TYPE_OF_SIZE_4 SInt32;
typedef unsigned TYPE_OF_SIZE_1 UInt8;
typedef unsigned TYPE_OF_SIZE_2 UInt16;
typedef unsigned TYPE_OF_SIZE_4 UInt32;
//
// clean up
//
#undef TYPE_OF_SIZE_1
#undef TYPE_OF_SIZE_2
#undef TYPE_OF_SIZE_4
#endif

25
lib/base/CFunctionJob.cpp Normal file
View File

@@ -0,0 +1,25 @@
#include "CFunctionJob.h"
//
// CFunctionJob
//
CFunctionJob::CFunctionJob(void (*func)(void*), void* arg) :
m_func(func),
m_arg(arg)
{
// do nothing
}
CFunctionJob::~CFunctionJob()
{
// do nothing
}
void
CFunctionJob::run()
{
if (m_func != NULL) {
m_func(m_arg);
}
}

24
lib/base/CFunctionJob.h Normal file
View File

@@ -0,0 +1,24 @@
#ifndef CFUNCTIONJOB_H
#define CFUNCTIONJOB_H
#include "IJob.h"
//! Use a function as a job
/*!
A job class that invokes a function.
*/
class CFunctionJob : public IJob {
public:
//! run() invokes \c func(arg)
CFunctionJob(void (*func)(void*), void* arg = NULL);
virtual ~CFunctionJob();
// IJob overrides
virtual void run();
private:
void (*m_func)(void*);
void* m_arg;
};
#endif

314
lib/base/CLog.cpp Normal file
View File

@@ -0,0 +1,314 @@
#include "CLog.h"
#include "CString.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#if WINDOWS_LIKE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define vsnprintf _vsnprintf
#endif
// names of priorities
static const char* g_priority[] = {
"FATAL",
"ERROR",
"WARNING",
"NOTE",
"INFO",
"DEBUG",
"DEBUG1",
"DEBUG2"
};
// number of priorities
static const int g_numPriority = (int)(sizeof(g_priority) /
sizeof(g_priority[0]));
// the default priority
#if defined(NDEBUG)
static const int g_defaultMaxPriority = 4;
#else
static const int g_defaultMaxPriority = 5;
#endif
// length of longest string in g_priority
static const int g_maxPriorityLength = 7;
// length of suffix string (": ")
static const int g_prioritySuffixLength = 2;
// amount of padded required to fill in the priority prefix
static const int g_priorityPad = g_maxPriorityLength +
g_prioritySuffixLength;
// platform newline sequence
#if WINDOWS_LIKE
static const char* g_newline = "\r\n";
#else
static const char* g_newline = "\n";
#endif
// minimum length of a newline sequence
static const int g_newlineLength = 2;
//
// CLog
//
CLog::Outputter CLog::s_outputter = NULL;
CLog::Lock CLog::s_lock = &CLog::dummyLock;
int CLog::s_maxPriority = -1;
void
CLog::print(const char* fmt, ...)
{
// check if fmt begins with a priority argument
int priority = 4;
if (fmt[0] == '%' && fmt[1] == 'z') {
priority = fmt[2] - '\060';
fmt += 3;
}
// done if below priority threshold
if (priority > getMaxPriority()) {
return;
}
// compute prefix padding length
int pad = g_priorityPad;
// print to buffer
char stack[1024];
va_list args;
va_start(args, fmt);
char* buffer = CStringUtil::vsprint(stack,
sizeof(stack) / sizeof(stack[0]),
pad, g_newlineLength, fmt, args);
va_end(args);
// output buffer
output(priority, buffer);
// clean up
if (buffer != stack)
delete[] buffer;
}
void
CLog::printt(const char* file, int line, const char* fmt, ...)
{
// check if fmt begins with a priority argument
int priority = 4;
if (fmt[0] == '%' && fmt[1] == 'z') {
priority = fmt[2] - '\060';
fmt += 3;
}
// done if below priority threshold
if (priority > getMaxPriority()) {
return;
}
// compute prefix padding length
char stack[1024];
sprintf(stack, "%d", line);
int pad = strlen(file) + 1 /* comma */ +
strlen(stack) + 1 /* colon */ + 1 /* space */ +
g_priorityPad;
// print to buffer, leaving space for a newline at the end
va_list args;
va_start(args, fmt);
char* buffer = CStringUtil::vsprint(stack,
sizeof(stack) / sizeof(stack[0]),
pad, g_newlineLength, fmt, args);
va_end(args);
// print the prefix to the buffer. leave space for priority label.
sprintf(buffer + g_priorityPad, "%s,%d:", file, line);
buffer[pad - 1] = ' ';
// discard file and line if priority < 0
char* message = buffer;
if (priority < 0) {
message += pad - g_priorityPad;
}
// output buffer
output(priority, message);
// clean up
if (buffer != stack)
delete[] buffer;
}
void
CLog::setOutputter(Outputter outputter)
{
CHoldLock lock(s_lock);
s_outputter = outputter;
}
CLog::Outputter
CLog::getOutputter()
{
CHoldLock lock(s_lock);
return s_outputter;
}
void
CLog::setLock(Lock newLock)
{
CHoldLock lock(s_lock);
s_lock = (newLock == NULL) ? dummyLock : newLock;
}
CLog::Lock
CLog::getLock()
{
CHoldLock lock(s_lock);
return (s_lock == dummyLock) ? NULL : s_lock;
}
bool
CLog::setFilter(const char* maxPriority)
{
if (maxPriority != NULL) {
for (int i = 0; i < g_numPriority; ++i) {
if (strcmp(maxPriority, g_priority[i]) == 0) {
setFilter(i);
return true;
}
}
return false;
}
return true;
}
void
CLog::setFilter(int maxPriority)
{
CHoldLock lock(s_lock);
s_maxPriority = maxPriority;
}
int
CLog::getFilter()
{
CHoldLock lock(s_lock);
return getMaxPriority();
}
void
CLog::dummyLock(bool)
{
// do nothing
}
int
CLog::getMaxPriority()
{
CHoldLock lock(s_lock);
if (s_maxPriority == -1) {
s_maxPriority = g_defaultMaxPriority;
setFilter(getenv("SYN_LOG_PRI"));
}
return s_maxPriority;
}
void
CLog::output(int priority, char* msg)
{
assert(priority >= -1 && priority < g_numPriority);
assert(msg != NULL);
// insert priority label
int n = -g_prioritySuffixLength;
if (priority >= 0) {
n = strlen(g_priority[priority]);
strcpy(msg + g_maxPriorityLength - n, g_priority[priority]);
msg[g_maxPriorityLength + 0] = ':';
msg[g_maxPriorityLength + 1] = ' ';
msg[g_maxPriorityLength + 1] = ' ';
}
// put a newline at the end
strcat(msg + g_priorityPad, g_newline);
// print it
CHoldLock lock(s_lock);
if (s_outputter == NULL ||
!s_outputter(priority, msg + g_maxPriorityLength - n)) {
#if WINDOWS_LIKE
openConsole();
#endif
fprintf(stderr, "%s", msg + g_maxPriorityLength - n);
}
}
#if WINDOWS_LIKE
static DWORD s_thread = 0;
static
BOOL WINAPI
CLogSignalHandler(DWORD)
{
// terminate cleanly and skip remaining handlers
PostThreadMessage(s_thread, WM_QUIT, 0, 0);
return TRUE;
}
void
CLog::openConsole()
{
static bool s_hasConsole = false;
// ignore if already created
if (s_hasConsole)
return;
// remember the current thread. when we get a ctrl+break or the
// console is closed we'll post WM_QUIT to this thread to shutdown
// cleanly.
// note -- win95/98/me are broken and will not receive a signal
// when the console is closed nor during logoff or shutdown,
// see microsoft articles Q130717 and Q134284. we could work
// around this in a painful way using hooks and hidden windows
// (as apache does) but it's not worth it. the app will still
// quit, just not cleanly. users in-the-know can use ctrl+c.
s_thread = GetCurrentThreadId();
// open a console
if (!AllocConsole())
return;
// get the handle for error output
HANDLE herr = GetStdHandle(STD_ERROR_HANDLE);
// prep console. windows 95 and its ilk have braindead
// consoles that can't even resize independently of the
// buffer size. use a 25 line buffer for those systems.
OSVERSIONINFO osInfo;
COORD size = { 80, 1000 };
osInfo.dwOSVersionInfoSize = sizeof(osInfo);
if (GetVersionEx(&osInfo) &&
osInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
size.Y = 25;
SetConsoleScreenBufferSize(herr, size);
SetConsoleTextAttribute(herr,
FOREGROUND_RED |
FOREGROUND_GREEN |
FOREGROUND_BLUE);
SetConsoleCtrlHandler(CLogSignalHandler, TRUE);
// reopen stderr to point at console
freopen("con", "w", stderr);
s_hasConsole = true;
}
#endif

201
lib/base/CLog.h Normal file
View File

@@ -0,0 +1,201 @@
#ifndef CLOG_H
#define CLOG_H
#include "common.h"
#include <stdarg.h>
//! Logging facility
/*!
The logging class; all console output should go through this class.
It supports multithread safe operation, several message priority levels,
filtering by priority, and output redirection. The macros log() and
clog() provide convenient access.
*/
class CLog {
public:
//! Log levels
/*!
The logging priority levels in order of highest to lowest priority.
*/
enum ELevel {
kFATAL, //!< For fatal errors
kERROR, //!< For serious errors
kWARNING, //!< For minor errors and warnings
kNOTE, //!< For messages about notable events
kINFO, //!< For informational messages
kDEBUG, //!< For important debugging messages
kDEBUG1, //!< For more detailed debugging messages
kDEBUG2 //!< For even more detailed debugging messages
};
//! Outputter function.
/*!
Type of outputter function. The outputter should write \c message,
which has the given \c priority, to a log and return true. Or it can
return false to let CLog use the default outputter.
*/
typedef bool (*Outputter)(int priority, const char* message);
//! Locking function
/*!
Type of lock/unlock function. If \c lock is true then block other
threads that try to lock until this thread unlocks. If \c lock is
false then unlock and allow another (waiting) thread to lock.
*/
typedef void (*Lock)(bool lock);
//! @name manipulators
//@{
//! Set the function used to write the log
/*!
Sets the function used to write to the log. The outputter function
is called with the formatted string to write and the priority level.
CLog will have already filtered messages below the current filter
priority. A NULL outputter means to use the default which is to print
to stderr. Note that the outputter should not call CLog methods but,
if it does, the current lock function must permit recursive locks.
*/
static void setOutputter(Outputter);
//! Set the lock/unlock function
/*!
Set the lock/unlock function. Use setLock(NULL) to remove the
locking function. There is no default lock function; do not call
CLog from multiple threads unless a working lock function has been
installed.
*/
static void setLock(Lock);
//! Set the minimum priority filter.
/*!
Set the filter. Messages below this priority are discarded.
The default priority is 4 (INFO) (unless built without NDEBUG
in which case it's 5 (DEBUG)). The default can be overridden
by setting the SYN_LOG_PRI env var to "FATAL", "ERROR", etc.
setFilter(const char*) returns true if the priority \c name was
recognized; if \c name is NULL then it simply returns true.
*/
static bool setFilter(const char* name);
static void setFilter(int);
//@}
//! @name accessors
//@{
//! Print a log message
/*!
Print a log message using the printf-like \c format and arguments.
*/
static void print(const char* format, ...);
//! Print a log message
/*!
Print a log message using the printf-like \c format and arguments
preceded by the filename and line number.
*/
static void printt(const char* file, int line,
const char* format, ...);
//! Get the function used to write the log
static Outputter getOutputter();
//! Get the lock/unlock function
/*!
Get the lock/unlock function. Note that the lock function is
used when retrieving the lock function.
*/
static Lock getLock();
//! Get the minimum priority level.
static int getFilter();
//@}
private:
class CHoldLock {
public:
CHoldLock(Lock lock) : m_lock(lock) { m_lock(true); }
~CHoldLock() { m_lock(false); }
private:
Lock m_lock;
};
static void dummyLock(bool);
static int getMaxPriority();
static void output(int priority, char* msg);
#if WINDOWS_LIKE
static void openConsole();
#endif
private:
static Outputter s_outputter;
static Lock s_lock;
static int s_maxPriority;
};
/*!
\def log(arg)
Write to the log. Because macros cannot accept variable arguments, this
should be invoked like so:
\code
log((CLOG_XXX "%d and %d are %s", x, y, x == y ? "equal" : "not equal"));
\endcode
In particular, notice the double open and close parentheses. Also note
that there is no comma after the \c CLOG_XXX. The \c XXX should be
replaced by one of enumerants in \c CLog::ELevel without the leading
\c k. For example, \c CLOG_INFO. The special \c CLOG_PRINT level will
not be filtered and is never prefixed by the filename and line number.
If \c NOLOGGING is defined during the build then this macro expands to
nothing. If \c NDEBUG is defined during the build then it expands to a
call to CLog::print. Otherwise it expands to a call to CLog::printt,
which includes the filename and line number.
*/
/*!
\def logc(expr, arg)
Write to the log if and only if expr is true. Because macros cannot accept
variable arguments, this should be invoked like so:
\code
clog(x == y, (CLOG_XXX "%d and %d are equal", x, y));
\endcode
In particular, notice the parentheses around everything after the boolean
expression. Also note that there is no comma after the \c CLOG_XXX.
The \c XXX should be replaced by one of enumerants in \c CLog::ELevel
without the leading \c k. For example, \c CLOG_INFO. The special
\c CLOG_PRINT level will not be filtered and is never prefixed by the
filename and line number.
If \c NOLOGGING is defined during the build then this macro expands to
nothing. If \c NDEBUG is defined during the build then it expands to a
call to CLog::print. Otherwise it expands to a call to CLog::printt,
which includes the filename and line number.
*/
#if defined(NOLOGGING)
#define log(_a1)
#define logc(_a1, _a2)
#define CLOG_TRACE
#elif defined(NDEBUG)
#define log(_a1) CLog::print _a1
#define logc(_a1, _a2) if (_a1) CLog::print _a2
#define CLOG_TRACE
#else
#define log(_a1) CLog::printt _a1
#define logc(_a1, _a2) if (_a1) CLog::printt _a2
#define CLOG_TRACE __FILE__, __LINE__,
#endif
#define CLOG_PRINT CLOG_TRACE "%z\057"
#define CLOG_CRIT CLOG_TRACE "%z\060"
#define CLOG_ERR CLOG_TRACE "%z\061"
#define CLOG_WARN CLOG_TRACE "%z\062"
#define CLOG_NOTE CLOG_TRACE "%z\063"
#define CLOG_INFO CLOG_TRACE "%z\064"
#define CLOG_DEBUG CLOG_TRACE "%z\065"
#define CLOG_DEBUG1 CLOG_TRACE "%z\066"
#define CLOG_DEBUG2 CLOG_TRACE "%z\067"
#endif

211
lib/base/CStopwatch.cpp Normal file
View File

@@ -0,0 +1,211 @@
#include "CStopwatch.h"
//
// CStopwatch
//
CStopwatch::CStopwatch(bool triggered) :
m_mark(0.0),
m_triggered(triggered),
m_stopped(triggered)
{
if (!triggered) {
m_mark = getClock();
}
}
CStopwatch::~CStopwatch()
{
// do nothing
}
double
CStopwatch::reset()
{
if (m_stopped) {
const double dt = m_mark;
m_mark = 0.0;
return dt;
}
else {
const double t = getClock();
const double dt = t - m_mark;
m_mark = t;
return dt;
}
}
void
CStopwatch::stop()
{
if (m_stopped) {
return;
}
// save the elapsed time
m_mark = getClock() - m_mark;
m_stopped = true;
}
void
CStopwatch::start()
{
m_triggered = false;
if (!m_stopped) {
return;
}
// set the mark such that it reports the time elapsed at stop()
m_mark = getClock() - m_mark;
m_stopped = false;
}
void
CStopwatch::setTrigger()
{
stop();
m_triggered = true;
}
double
CStopwatch::getTime()
{
if (m_triggered) {
const double dt = m_mark;
start();
return dt;
}
else if (m_stopped) {
return m_mark;
}
else {
return getClock() - m_mark;
}
}
CStopwatch::operator double()
{
return getTime();
}
bool
CStopwatch::isStopped() const
{
return m_stopped;
}
double
CStopwatch::getTime() const
{
if (m_stopped) {
return m_mark;
}
else {
return getClock() - m_mark;
}
}
CStopwatch::operator double() const
{
return getTime();
}
#if WINDOWS_LIKE
// avoid getting a lot a crap from mmsystem.h that we don't need
#define MMNODRV // Installable driver support
#define MMNOSOUND // Sound support
#define MMNOWAVE // Waveform support
#define MMNOMIDI // MIDI support
#define MMNOAUX // Auxiliary audio support
#define MMNOMIXER // Mixer support
#define MMNOJOY // Joystick support
#define MMNOMCI // MCI support
#define MMNOMMIO // Multimedia file I/O support
#define MMNOMMSYSTEM // General MMSYSTEM functions
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>
typedef WINMMAPI DWORD (WINAPI *PTimeGetTime)(void);
static double s_freq = 0.0;
static HINSTANCE s_mmInstance = NULL;
static PTimeGetTime s_tgt = NULL;
//
// initialize local variables
//
class CStopwatchInit {
public:
CStopwatchInit();
~CStopwatchInit();
};
static CStopwatchInit s_init;
CStopwatchInit::CStopwatchInit()
{
LARGE_INTEGER freq;
if (QueryPerformanceFrequency(&freq) && freq.QuadPart != 0) {
s_freq = 1.0 / static_cast<double>(freq.QuadPart);
}
else {
// load winmm.dll and get timeGetTime
s_mmInstance = LoadLibrary("winmm");
if (s_mmInstance) {
s_tgt = (PTimeGetTime)GetProcAddress(s_mmInstance, "timeGetTime");
}
}
}
CStopwatchInit::~CStopwatchInit()
{
if (s_mmInstance) {
FreeLibrary(reinterpret_cast<HMODULE>(s_mmInstance));
}
}
double
CStopwatch::getClock() const
{
// get time. we try three ways, in order of descending precision
if (s_freq != 0.0) {
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return s_freq * static_cast<double>(c.QuadPart);
}
else if (s_tgt) {
return 0.001 * static_cast<double>(s_tgt());
}
else {
return 0.001 * static_cast<double>(GetTickCount());
}
}
#elif UNIX_LIKE
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
double
CStopwatch::getClock() const
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + 1.0e-6 * (double)t.tv_usec;
}
#endif // UNIX_LIKE

94
lib/base/CStopwatch.h Normal file
View File

@@ -0,0 +1,94 @@
#ifndef CSTOPWATCH_H
#define CSTOPWATCH_H
#include "common.h"
//! A timer class
/*!
This class measures time intervals. All time interval measurement
should use this class.
*/
class CStopwatch {
public:
/*!
The default constructor does an implicit reset() or setTrigger().
If triggered == false then the clock starts ticking.
*/
CStopwatch(bool triggered = false);
~CStopwatch();
//! @name manipulators
//@{
//! Reset the timer to zero
/*!
Set the start time to the current time, returning the time since
the last reset. This does not remove the trigger if it's set nor
does it start a stopped clock. If the clock is stopped then
subsequent reset()'s will return 0.
*/
double reset();
//! Stop the timer
/*!
Stop the stopwatch. The time interval while stopped is not
counted by the stopwatch. stop() does not remove the trigger.
Has no effect if already stopped.
*/
void stop();
//! Start the timer
/*!
Start the stopwatch. start() removes the trigger, even if the
stopwatch was already started.
*/
void start();
//! Stop the timer and set the trigger
/*!
setTrigger() stops the clock like stop() except there's an
implicit start() the next time (non-const) getTime() is called.
This is useful when you want the clock to start the first time
you check it.
*/
void setTrigger();
//! Get elapsed time
/*!
Returns the time since the last reset() (or calls reset() and
returns zero if the trigger is set).
*/
double getTime();
//! Same as getTime()
operator double();
//@}
//! @name accessors
//@{
//! Check if timer is stopped
/*!
Returns true if the stopwatch is stopped.
*/
bool isStopped() const;
// return the time since the last reset().
//! Get elapsed time
/*!
Returns the time since the last reset(). This cannot trigger the
stopwatch to start and will not clear the trigger.
*/
double getTime() const;
//! Same as getTime() const
operator double() const;
//@}
private:
double getClock() const;
private:
double m_mark;
bool m_triggered;
bool m_stopped;
};
#endif

199
lib/base/CString.cpp Normal file
View File

@@ -0,0 +1,199 @@
#include "CString.h"
#include "common.h"
#include "stdvector.h"
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#if WINDOWS_LIKE
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define vsnprintf _vsnprintf
#endif
//
// CStringUtil
//
CString
CStringUtil::format(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
CString result = vformat(fmt, args);
va_end(args);
return result;
}
CString
CStringUtil::vformat(const char* fmt, va_list args)
{
// find highest indexed substitution and the locations of substitutions
std::vector<size_t> pos;
std::vector<size_t> width;
std::vector<int> index;
int maxIndex = 0;
for (const char* scan = fmt; *scan != '\0'; ++scan) {
if (*scan == '%') {
++scan;
if (*scan == '\0') {
break;
}
else if (*scan == '%') {
// literal
index.push_back(0);
pos.push_back(static_cast<int>(scan - 1 - fmt));
width.push_back(2);
}
else if (*scan == '{') {
// get argument index
char* end;
int i = static_cast<int>(strtol(scan + 1, &end, 10));
if (*end != '}') {
// invalid index -- ignore
scan = end - 1;
}
else {
index.push_back(i);
pos.push_back(static_cast<int>(scan - 1 - fmt));
width.push_back(static_cast<int>(end - scan + 2));
if (i > maxIndex) {
maxIndex = i;
}
scan = end;
}
}
else {
// improper escape -- ignore
}
}
}
// get args
std::vector<const char*> value;
std::vector<size_t> length;
value.push_back("%");
length.push_back(1);
for (int i = 0; i < maxIndex; ++i) {
const char* arg = va_arg(args, const char*);
value.push_back(arg);
length.push_back(strlen(arg));
}
// compute final length
size_t resultLength = strlen(fmt);
const int n = static_cast<int>(pos.size());
for (int i = 0; i < n; ++i) {
resultLength -= width[i];
resultLength += length[index[i]];
}
// substitute
CString result;
result.reserve(resultLength);
size_t src = 0;
for (int i = 0; i < n; ++i) {
result.append(fmt + src, pos[i] - src);
result.append(value[index[i]]);
src = pos[i] + width[i];
}
result.append(fmt + src);
return result;
}
CString
CStringUtil::print(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
CString result = vprint(fmt, args);
va_end(args);
return result;
}
CString
CStringUtil::vprint(const char* fmt, va_list args)
{
char tmp[1024];
char* buffer = vsprint(tmp, sizeof(tmp) / sizeof(tmp[0]), 0, 0, fmt, args);
if (buffer == tmp) {
return buffer;
}
else {
CString result(buffer);
delete[] buffer;
return result;
}
}
char*
CStringUtil::vsprint(char* buffer, int len,
int prefix, int suffix, const char* fmt, va_list args)
{
assert(len > 0);
// try writing to input buffer
int n;
if (buffer != NULL && len >= prefix + suffix) {
n = vsnprintf(buffer + prefix, len - (prefix + suffix), fmt, args);
if (n >= 0 && n <= len - (prefix + suffix))
return buffer;
}
// start allocating buffers until we write the whole string
buffer = NULL;
do {
delete[] buffer;
len *= 2;
buffer = new char[len + (prefix + suffix)];
n = vsnprintf(buffer + prefix, len - (prefix + suffix), fmt, args);
} while (n < 0 || n > len - (prefix + suffix));
return buffer;
}
//
// CStringUtil::CaselessCmp
//
bool
CStringUtil::CaselessCmp::cmpEqual(
const CString::value_type& a,
const CString::value_type& b)
{
// FIXME -- use std::tolower but not in all versions of libstdc++ have it
return tolower(a) == tolower(b);
}
bool
CStringUtil::CaselessCmp::cmpLess(
const CString::value_type& a,
const CString::value_type& b)
{
// FIXME -- use std::tolower but not in all versions of libstdc++ have it
return tolower(a) < tolower(b);
}
bool
CStringUtil::CaselessCmp::less(const CString& a, const CString& b)
{
return std::lexicographical_compare(
a.begin(), a.end(),
b.begin(), b.end(),
&CStringUtil::CaselessCmp::cmpLess);
}
bool
CStringUtil::CaselessCmp::equal(const CString& a, const CString& b)
{
return !(less(a, b) || less(b, a));
}
bool
CStringUtil::CaselessCmp::operator()(const CString& a, const CString& b) const
{
return less(a, b);
}

90
lib/base/CString.h Normal file
View File

@@ -0,0 +1,90 @@
#ifndef CSTRING_H
#define CSTRING_H
#include <stdarg.h>
#include "stdpre.h"
#include <string>
#include "stdpost.h"
// use standard C++ string class for our string class
typedef std::string CString;
//! String utilities
/*!
This class provides various functions for string manipulation.
*/
class CStringUtil {
public:
//! Format positional arguments
/*!
Format a string using positional arguments. fmt has literal
characters and conversion specifications introduced by `\%':
- \c\%\% -- literal `\%'
- \c\%{n} -- positional element n, n a positive integer, {} are literal
All arguments in the variable list are const char*. Positional
elements are indexed from 1.
*/
static CString format(const char* fmt, ...);
//! Format positional arguments
/*!
Same as format() except takes va_list.
*/
static CString vformat(const char* fmt, va_list);
//! Print a string using printf-style formatting
/*!
Equivalent to printf() except the result is returned as a CString.
*/
static CString print(const char* fmt, ...);
//! Print a string using printf-style formatting
/*!
Same as print() except takes va_list.
*/
static CString vprint(const char* fmt, va_list);
//! Print a string using printf-style formatting into a buffer
/*!
This is like print but print into a given buffer. If the resulting
string will not fit into \c buffer then a new buffer is allocated and
returned, otherwise \c buffer is returned. the caller must delete[]
the returned memory if is not \c buffer.
\c prefix and \c suffix must be >= 0. Exactly \c prefix characters and
at least \c suffix characters are available in the buffer before
and after the printed string, respectively. \c bufferLength is the
length of buffer and should not be adjusted by the caller to
account for \c prefix or \c suffix.
*/
static char* vsprint(char* buffer, int bufferLength,
int prefix, int suffix, const char* fmt, va_list);
//! Case-insensitive comparisons
/*!
This class provides case-insensitve comparison functions.
*/
class CaselessCmp {
public:
//! Same as less()
bool operator()(const CString& a, const CString& b) const;
//! Returns true iff \c a is lexicographically less than \c b
static bool less(const CString& a, const CString& b);
//! Returns true iff \c a is lexicographically equal to \c b
static bool equal(const CString& a, const CString& b);
//! Returns true iff \c a is lexicographically less than \c b
static bool cmpLess(const CString::value_type& a,
const CString::value_type& b);
//! Returns true iff \c a is lexicographically equal to \c b
static bool cmpEqual(const CString::value_type& a,
const CString::value_type& b);
};
};
#endif

754
lib/base/CUnicode.cpp Normal file
View File

@@ -0,0 +1,754 @@
#include "CUnicode.h"
#include <limits.h>
#include <string.h>
//
// local utility functions
//
inline
static
UInt16
decode16(const UInt8* n)
{
union x16 {
UInt8 n8[2];
UInt16 n16;
} c;
c.n8[0] = n[0];
c.n8[1] = n[1];
return c.n16;
}
inline
static
UInt32
decode32(const UInt8* n)
{
union x32 {
UInt8 n8[4];
UInt32 n32;
} c;
c.n8[0] = n[0];
c.n8[1] = n[1];
c.n8[2] = n[2];
c.n8[3] = n[3];
return c.n32;
}
inline
static
void
resetError(bool* errors)
{
if (errors != NULL) {
*errors = false;
}
}
inline
static
void
setError(bool* errors)
{
if (errors != NULL) {
*errors = true;
}
}
//
// CUnicode
//
UInt32 CUnicode::s_invalid = 0x0000ffff;
UInt32 CUnicode::s_replacement = 0x0000fffd;
bool
CUnicode::isUTF8(const CString& src)
{
// convert and test each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str());
for (UInt32 n = src.size(); n > 0; ) {
if (fromUTF8(data, n) == s_invalid) {
return false;
}
}
return true;
}
CString
CUnicode::UTF8ToUCS2(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = src.size();
CString dst;
dst.reserve(2 * n);
// convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
}
else if (c >= 0x00010000) {
setError(errors);
c = s_replacement;
}
UInt16 ucs2 = static_cast<UInt16>(c);
dst.append(reinterpret_cast<const char*>(&ucs2), 2);
}
return dst;
}
CString
CUnicode::UTF8ToUCS4(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = src.size();
CString dst;
dst.reserve(4 * n);
// convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
}
dst.append(reinterpret_cast<const char*>(&c), 4);
}
return dst;
}
CString
CUnicode::UTF8ToUTF16(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = src.size();
CString dst;
dst.reserve(2 * n);
// convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
}
else if (c >= 0x00110000) {
setError(errors);
c = s_replacement;
}
if (c < 0x00010000) {
UInt16 ucs2 = static_cast<UInt16>(c);
dst.append(reinterpret_cast<const char*>(&ucs2), 2);
}
else {
c -= 0x00010000;
UInt16 utf16h = static_cast<UInt16>((c >> 10) + 0xd800);
UInt16 utf16l = static_cast<UInt16>((c & 0x03ff) + 0xdc00);
dst.append(reinterpret_cast<const char*>(&utf16h), 2);
dst.append(reinterpret_cast<const char*>(&utf16l), 2);
}
}
return dst;
}
CString
CUnicode::UTF8ToUTF32(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = src.size();
CString dst;
dst.reserve(4 * n);
// convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
}
else if (c >= 0x00110000) {
setError(errors);
c = s_replacement;
}
dst.append(reinterpret_cast<const char*>(&c), 4);
}
return dst;
}
CString
CUnicode::UTF8ToText(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// convert to wide char
UInt32 size;
wchar_t* tmp = UTF8ToWideChar(src, size, errors);
// get length of multibyte string
char mbc[MB_LEN_MAX];
size_t mblen;
mbstate_t state;
memset(&state, 0, sizeof(state));
size_t len = 0;
UInt32 n = size;
for (const wchar_t* scan = tmp; n > 0; ++scan, --n) {
mblen = wcrtomb(mbc, *scan, &state);
if (mblen == -1) {
// unconvertable character
setError(errors);
len += 1;
}
else {
len += mblen;
}
}
// handle nul terminator
mblen = wcrtomb(mbc, L'\0', &state);
if (mblen != -1) {
len += mblen;
}
assert(mbsinit(&state) != 0);
// allocate multibyte string
char* mbs = new char[len];
// convert to multibyte
char* dst = mbs;
n = size;
for (const wchar_t* scan = tmp; n > 0; ++scan, --n) {
mblen = wcrtomb(dst, *scan, &state);
if (mblen == -1) {
// unconvertable character
*dst++ = '?';
}
else {
dst += mblen;
}
}
mblen = wcrtomb(dst, L'\0', &state);
if (mblen != -1) {
// don't include nul terminator
dst += mblen - 1;
}
CString text(mbs, dst - mbs);
// clean up
delete[] mbs;
delete[] tmp;
return text;
}
CString
CUnicode::UCS2ToUTF8(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = src.size() >> 1;
return doUCS2ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
}
CString
CUnicode::UCS4ToUTF8(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = src.size() >> 2;
return doUCS4ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
}
CString
CUnicode::UTF16ToUTF8(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = src.size() >> 1;
return doUTF16ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
}
CString
CUnicode::UTF32ToUTF8(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = src.size() >> 2;
return doUTF32ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
}
CString
CUnicode::textToUTF8(const CString& src, bool* errors)
{
// default to success
resetError(errors);
// get length of multibyte string
UInt32 n = src.size();
size_t len = 0;
mbstate_t state;
memset(&state, 0, sizeof(state));
for (const char* scan = src.c_str(); n > 0; ) {
size_t mblen = mbrtowc(NULL, scan, n, &state);
switch (mblen) {
case (size_t)-2:
// incomplete last character. convert to unknown character.
setError(errors);
len += 1;
n = 0;
break;
case (size_t)-1:
// invalid character. count one unknown character and
// start at the next byte.
setError(errors);
len += 1;
scan += 1;
n -= 1;
break;
case 0:
len += 1;
scan += 1;
n -= 1;
break;
default:
// normal character
len += 1;
scan += mblen;
n -= mblen;
break;
}
}
memset(&state, 0, sizeof(state));
// allocate wide character string
wchar_t* wcs = new wchar_t[len];
// convert multibyte to wide char
n = src.size();
wchar_t* dst = wcs;
for (const char* scan = src.c_str(); n > 0; ++dst) {
size_t mblen = mbrtowc(dst, scan, n, &state);
switch (mblen) {
case (size_t)-2:
// incomplete character. convert to unknown character.
*dst = (wchar_t)0xfffd;
n = 0;
break;
case (size_t)-1:
// invalid character. count one unknown character and
// start at the next byte.
*dst = (wchar_t)0xfffd;
scan += 1;
n -= 1;
break;
case 0:
*dst = (wchar_t)0x0000;
scan += 1;
n -= 1;
break;
default:
// normal character
scan += mblen;
n -= mblen;
break;
}
}
// convert to UTF8
CString utf8 = wideCharToUTF8(wcs, len, errors);
// clean up
delete[] wcs;
return utf8;
}
wchar_t*
CUnicode::UTF8ToWideChar(const CString& src, UInt32& size, bool* errors)
{
// convert to platform's wide character encoding
#if WINDOWS_LIKE
CString tmp = UTF8ToUTF16(src, errors);
size = tmp.size() >> 1;
#elif UNIX_LIKE
CString tmp = UTF8ToUCS4(src, errors);
size = tmp.size() >> 2;
#endif
// copy to a wchar_t array
wchar_t* dst = new wchar_t[size];
::memcpy(dst, tmp.data(), sizeof(wchar_t) * size);
return dst;
}
CString
CUnicode::wideCharToUTF8(const wchar_t* src, UInt32 size, bool* errors)
{
// convert from platform's wide character encoding.
// note -- this must include a wide nul character (independent of
// the CString's nul character).
#if WINDOWS_LIKE
return doUTF16ToUTF8(reinterpret_cast<const UInt8*>(src), size, errors);
#elif UNIX_LIKE
return doUCS4ToUTF8(reinterpret_cast<const UInt8*>(src), size, errors);
#endif
}
CString
CUnicode::doUCS2ToUTF8(const UInt8* data, UInt32 n, bool* errors)
{
// make some space
CString dst;
dst.reserve(n);
// convert each character
for (; n > 0; data += 2, --n) {
UInt32 c = decode16(data);
toUTF8(dst, c, errors);
}
return dst;
}
CString
CUnicode::doUCS4ToUTF8(const UInt8* data, UInt32 n, bool* errors)
{
// make some space
CString dst;
dst.reserve(n);
// convert each character
for (; n > 0; data += 4, --n) {
UInt32 c = decode32(data);
toUTF8(dst, c, errors);
}
return dst;
}
CString
CUnicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors)
{
// make some space
CString dst;
dst.reserve(n);
// convert each character
for (; n > 0; data += 2, --n) {
UInt32 c = decode16(data);
if (c < 0x0000d800 || c > 0x0000dfff) {
toUTF8(dst, c, errors);
}
else if (n == 1) {
// error -- missing second word
setError(errors);
toUTF8(dst, s_replacement, NULL);
}
else if (c >= 0x0000d800 && c <= 0x0000dbff) {
UInt32 c2 = decode16(data);
data += 2;
--n;
if (c2 < 0x0000dc00 || c2 > 0x0000dfff) {
// error -- [d800,dbff] not followed by [dc00,dfff]
setError(errors);
toUTF8(dst, s_replacement, NULL);
}
else {
c = (((c - 0x0000d800) << 10) | (c2 - 0x0000dc00)) + 0x00010000;
toUTF8(dst, c, errors);
}
}
else {
// error -- [dc00,dfff] without leading [d800,dbff]
setError(errors);
toUTF8(dst, s_replacement, NULL);
}
}
return dst;
}
CString
CUnicode::doUTF32ToUTF8(const UInt8* data, UInt32 n, bool* errors)
{
// make some space
CString dst;
dst.reserve(n);
// convert each character
for (; n > 0; data += 4, --n) {
UInt32 c = decode32(data);
if (c >= 0x00110000) {
setError(errors);
c = s_replacement;
}
toUTF8(dst, c, errors);
}
return dst;
}
UInt32
CUnicode::fromUTF8(const UInt8*& data, UInt32& n)
{
assert(data != NULL);
assert(n != 0);
// compute character encoding length, checking for overlong
// sequences (i.e. characters that don't use the shortest
// possible encoding).
UInt32 size;
if (data[0] < 0x80) {
// 0xxxxxxx
size = 1;
}
else if (data[0] < 0xc0) {
// 10xxxxxx -- in the middle of a multibyte character. counts
// as one invalid character.
--n;
++data;
return s_invalid;
}
else if (data[0] < 0xe0) {
// 110xxxxx
size = 2;
}
else if (data[0] < 0xf0) {
// 1110xxxx
size = 3;
}
else if (data[0] < 0xf8) {
// 11110xxx
size = 4;
}
else if (data[0] < 0xfc) {
// 111110xx
size = 5;
}
else if (data[0] < 0xfe) {
// 1111110x
size = 6;
}
else {
// invalid sequence. dunno how many bytes to skip so skip one.
--n;
++data;
return s_invalid;
}
// make sure we have enough data
if (size > n) {
data += n;
n = 0;
return s_invalid;
}
// extract character
UInt32 c;
switch (size) {
case 1:
c = static_cast<UInt32>(data[0]);
break;
case 2:
c = ((static_cast<UInt32>(data[0]) & 0x1f) << 6) |
((static_cast<UInt32>(data[1]) & 0x3f) );
break;
case 3:
c = ((static_cast<UInt32>(data[0]) & 0x0f) << 12) |
((static_cast<UInt32>(data[1]) & 0x3f) << 6) |
((static_cast<UInt32>(data[2]) & 0x3f) );
break;
case 4:
c = ((static_cast<UInt32>(data[0]) & 0x07) << 18) |
((static_cast<UInt32>(data[1]) & 0x3f) << 12) |
((static_cast<UInt32>(data[1]) & 0x3f) << 6) |
((static_cast<UInt32>(data[1]) & 0x3f) );
break;
case 5:
c = ((static_cast<UInt32>(data[0]) & 0x03) << 24) |
((static_cast<UInt32>(data[1]) & 0x3f) << 18) |
((static_cast<UInt32>(data[1]) & 0x3f) << 12) |
((static_cast<UInt32>(data[1]) & 0x3f) << 6) |
((static_cast<UInt32>(data[1]) & 0x3f) );
break;
case 6:
c = ((static_cast<UInt32>(data[0]) & 0x01) << 30) |
((static_cast<UInt32>(data[1]) & 0x3f) << 24) |
((static_cast<UInt32>(data[1]) & 0x3f) << 18) |
((static_cast<UInt32>(data[1]) & 0x3f) << 12) |
((static_cast<UInt32>(data[1]) & 0x3f) << 6) |
((static_cast<UInt32>(data[1]) & 0x3f) );
break;
default:
assert(0 && "invalid size");
return s_invalid;
}
// check that all bytes after the first have the pattern 10xxxxxx.
// truncated sequences are treated as a single malformed character.
bool truncated = false;
switch (size) {
case 6:
if ((data[5] & 0xc0) != 0x80) {
truncated = true;
size = 5;
}
// fall through
case 5:
if ((data[4] & 0xc0) != 0x80) {
truncated = true;
size = 4;
}
// fall through
case 4:
if ((data[3] & 0xc0) != 0x80) {
truncated = true;
size = 3;
}
// fall through
case 3:
if ((data[2] & 0xc0) != 0x80) {
truncated = true;
size = 2;
}
// fall through
case 2:
if ((data[1] & 0xc0) != 0x80) {
truncated = true;
size = 1;
}
}
// update parameters
data += size;
n -= size;
// invalid if sequence was truncated
if (truncated) {
return s_invalid;
}
// check for characters that didn't use the smallest possible encoding
static UInt32 s_minChar[] = {
0,
0x00000000,
0x00000080,
0x00000800,
0x00010000,
0x00200000,
0x04000000
};
if (c < s_minChar[size]) {
return s_invalid;
}
// check for characters not in ISO-10646
if (c >= 0x0000d800 && c <= 0x0000dfff) {
return s_invalid;
}
if (c >= 0x0000fffe && c <= 0x0000ffff) {
return s_invalid;
}
return c;
}
void
CUnicode::toUTF8(CString& dst, UInt32 c, bool* errors)
{
UInt8 data[6];
// handle characters outside the valid range
if ((c >= 0x0000d800 && c <= 0x0000dfff) || c >= 0x80000000) {
setError(errors);
c = s_replacement;
}
// convert to UTF-8
if (c < 0x00000080) {
data[0] = static_cast<UInt8>(c);
dst.append(reinterpret_cast<char*>(data), 1);
}
else if (c < 0x00000800) {
data[0] = static_cast<UInt8>(((c >> 6) & 0x0000001f) + 0xc0);
data[1] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char*>(data), 2);
}
else if (c < 0x00010000) {
data[0] = static_cast<UInt8>(((c >> 12) & 0x0000000f) + 0xe0);
data[1] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char*>(data), 3);
}
else if (c < 0x00200000) {
data[0] = static_cast<UInt8>(((c >> 18) & 0x00000007) + 0xf0);
data[1] = static_cast<UInt8>(((c >> 12) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[3] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char*>(data), 4);
}
else if (c < 0x04000000) {
data[0] = static_cast<UInt8>(((c >> 24) & 0x00000003) + 0xf8);
data[1] = static_cast<UInt8>(((c >> 18) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>(((c >> 12) & 0x0000003f) + 0x80);
data[3] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[4] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char*>(data), 5);
}
else if (c < 0x80000000) {
data[0] = static_cast<UInt8>(((c >> 30) & 0x00000001) + 0xfc);
data[1] = static_cast<UInt8>(((c >> 24) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>(((c >> 18) & 0x0000003f) + 0x80);
data[3] = static_cast<UInt8>(((c >> 12) & 0x0000003f) + 0x80);
data[4] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[5] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char*>(data), 6);
}
else {
assert(0 && "character out of range");
}
}

130
lib/base/CUnicode.h Normal file
View File

@@ -0,0 +1,130 @@
#ifndef CUNICODE_H
#define CUNICODE_H
#include "CString.h"
#include "BasicTypes.h"
#include <wchar.h>
//! Unicode utility functions
/*!
This class provides functions for converting between various Unicode
encodings and the current locale encoding.
*/
class CUnicode {
public:
//! @name accessors
//@{
//! Test UTF-8 string for validity
/*!
Returns true iff the string contains a valid sequence of UTF-8
encoded characters.
*/
static bool isUTF8(const CString&);
//! Convert from UTF-8 to UCS-2 encoding
/*!
Convert from UTF-8 to UCS-2. If errors is not NULL then *errors
is set to true iff any character could not be encoded in UCS-2.
Decoding errors do not set *errors.
*/
static CString UTF8ToUCS2(const CString&, bool* errors = NULL);
//! Convert from UTF-8 to UCS-4 encoding
/*!
Convert from UTF-8 to UCS-4. If errors is not NULL then *errors
is set to true iff any character could not be encoded in UCS-4.
Decoding errors do not set *errors.
*/
static CString UTF8ToUCS4(const CString&, bool* errors = NULL);
//! Convert from UTF-8 to UTF-16 encoding
/*!
Convert from UTF-8 to UTF-16. If errors is not NULL then *errors
is set to true iff any character could not be encoded in UTF-16.
Decoding errors do not set *errors.
*/
static CString UTF8ToUTF16(const CString&, bool* errors = NULL);
//! Convert from UTF-8 to UTF-32 encoding
/*!
Convert from UTF-8 to UTF-32. If errors is not NULL then *errors
is set to true iff any character could not be encoded in UTF-32.
Decoding errors do not set *errors.
*/
static CString UTF8ToUTF32(const CString&, bool* errors = NULL);
//! Convert from UTF-8 to the current locale encoding
/*!
Convert from UTF-8 to the current locale encoding. If errors is not
NULL then *errors is set to true iff any character could not be encoded.
Decoding errors do not set *errors.
*/
static CString UTF8ToText(const CString&, bool* errors = NULL);
//! Convert from UCS-2 to UTF-8
/*!
Convert from UCS-2 to UTF-8. If errors is not NULL then *errors is
set to true iff any character could not be decoded.
*/
static CString UCS2ToUTF8(const CString&, bool* errors = NULL);
//! Convert from UCS-4 to UTF-8
/*!
Convert from UCS-4 to UTF-8. If errors is not NULL then *errors is
set to true iff any character could not be decoded.
*/
static CString UCS4ToUTF8(const CString&, bool* errors = NULL);
//! Convert from UTF-16 to UTF-8
/*!
Convert from UTF-16 to UTF-8. If errors is not NULL then *errors is
set to true iff any character could not be decoded.
*/
static CString UTF16ToUTF8(const CString&, bool* errors = NULL);
//! Convert from UTF-32 to UTF-8
/*!
Convert from UTF-32 to UTF-8. If errors is not NULL then *errors is
set to true iff any character could not be decoded.
*/
static CString UTF32ToUTF8(const CString&, bool* errors = NULL);
//! Convert from the current locale encoding to UTF-8
/*!
Convert from the current locale encoding to UTF-8. If errors is not
NULL then *errors is set to true iff any character could not be decoded.
*/
static CString textToUTF8(const CString&, bool* errors = NULL);
//@}
private:
// convert UTF8 to wchar_t string (using whatever encoding is native
// to the platform). caller must delete[] the returned string. the
// string is *not* nul terminated; the length (in characters) is
// returned in size.
static wchar_t* UTF8ToWideChar(const CString&,
UInt32& size, bool* errors);
// convert nul terminated wchar_t string (in platform's native
// encoding) to UTF8.
static CString wideCharToUTF8(const wchar_t*,
UInt32 size, bool* errors);
// internal conversion to UTF8
static CString doUCS2ToUTF8(const UInt8* src, UInt32 n, bool* errors);
static CString doUCS4ToUTF8(const UInt8* src, UInt32 n, bool* errors);
static CString doUTF16ToUTF8(const UInt8* src, UInt32 n, bool* errors);
static CString doUTF32ToUTF8(const UInt8* src, UInt32 n, bool* errors);
// convert characters to/from UTF8
static UInt32 fromUTF8(const UInt8*& src, UInt32& size);
static void toUTF8(CString& dst, UInt32 c, bool* errors);
private:
static UInt32 s_invalid;
static UInt32 s_replacement;
};
#endif

17
lib/base/IInterface.h Normal file
View File

@@ -0,0 +1,17 @@
#ifndef IINTERFACE_H
#define IINTERFACE_H
#include "common.h"
//! Base class of interfaces
/*!
This is the base class of all interface classes. An interface class has
only pure virtual methods.
*/
class IInterface {
public:
//! Interface destructor does nothing
virtual ~IInterface() { }
};
#endif

16
lib/base/IJob.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef IJOB_H
#define IJOB_H
#include "IInterface.h"
//! Job interface
/*!
A job is an interface for executing some function.
*/
class IJob : public IInterface {
public:
//! Run the job
virtual void run() = 0;
};
#endif

36
lib/base/Makefile.am Normal file
View File

@@ -0,0 +1,36 @@
## Process this file with automake to produce Makefile.in
NULL =
DEPTH = ../..
noinst_LIBRARIES = libbase.a
libbase_a_SOURCES = \
CFunctionJob.cpp \
CLog.cpp \
CStopwatch.cpp \
CString.cpp \
CUnicode.cpp \
XBase.cpp \
BasicTypes.h \
CFunctionJob.h \
CLog.h \
CStopwatch.h \
CString.h \
CUnicode.h \
IInterface.h \
IJob.h \
TMethodJob.h \
XBase.h \
common.h \
stdfstream.h \
stdistream.h \
stdlist.h \
stdmap.h \
stdostream.h \
stdpost.h \
stdpre.h \
stdset.h \
stdsstream.h \
stdvector.h \
$(NULL)
INCLUDES = \
$(NULL)

53
lib/base/TMethodJob.h Normal file
View File

@@ -0,0 +1,53 @@
#ifndef CMETHODJOB_H
#define CMETHODJOB_H
#include "IJob.h"
//! Use a function as a job
/*!
A job class that invokes a member function.
*/
template <class T>
class TMethodJob : public IJob {
public:
//! run() invokes \c object->method(arg)
TMethodJob(T* object, void (T::*method)(void*), void* arg = NULL);
virtual ~TMethodJob();
// IJob overrides
virtual void run();
private:
T* m_object;
void (T::*m_method)(void*);
void* m_arg;
};
template <class T>
inline
TMethodJob<T>::TMethodJob(T* object, void (T::*method)(void*), void* arg) :
m_object(object),
m_method(method),
m_arg(arg)
{
// do nothing
}
template <class T>
inline
TMethodJob<T>::~TMethodJob()
{
// do nothing
}
template <class T>
inline
void
TMethodJob<T>::run()
{
if (m_object != NULL) {
(m_object->*m_method)(m_arg);
}
}
#endif

95
lib/base/XBase.cpp Normal file
View File

@@ -0,0 +1,95 @@
#include "XBase.h"
#include <cerrno>
#include <cstdarg>
// win32 wants a const char* argument to std::exception c'tor
#if WINDOWS_LIKE
#define STDEXCEPTARG ""
#endif
// default to no argument
#ifndef STDEXCEPTARG
#define STDEXCEPTARG
#endif
//
// XBase
//
XBase::XBase() :
exception(STDEXCEPTARG),
m_what()
{
// do nothing
}
XBase::XBase(const CString& msg) :
exception(STDEXCEPTARG),
m_what(msg)
{
// do nothing
}
XBase::~XBase()
{
// do nothing
}
const char*
XBase::what() const
{
if (m_what.empty()) {
m_what = getWhat();
}
return m_what.c_str();
}
CString
XBase::format(const char* /*id*/, const char* fmt, ...) const throw()
{
// FIXME -- lookup message string using id as an index. set
// fmt to that string if it exists.
// format
CString result;
va_list args;
va_start(args, fmt);
try {
result = CStringUtil::vformat(fmt, args);
}
catch (...) {
// ignore
}
va_end(args);
return result;
}
//
// MXErrno
//
MXErrno::MXErrno() :
m_errno(errno)
{
// do nothing
}
MXErrno::MXErrno(int err) :
m_errno(err)
{
// do nothing
}
int
MXErrno::getErrno() const
{
return m_errno;
}
const char*
MXErrno::getErrstr() const
{
return strerror(m_errno);
}

68
lib/base/XBase.h Normal file
View File

@@ -0,0 +1,68 @@
#ifndef XBASE_H
#define XBASE_H
#include "CString.h"
#include "stdpre.h"
#include <exception>
#include "stdpost.h"
//! Exception base class
/*!
This is the base class of most exception types.
*/
class XBase : public std::exception {
public:
//! Use getWhat() as the result of what()
XBase();
//! Use \c msg as the result of what()
XBase(const CString& msg);
virtual ~XBase();
// std::exception overrides
virtual const char* what() const;
protected:
//! Get a human readable string describing the exception
virtual CString getWhat() const throw() = 0;
//! Format a string
/*!
Looks up a message format using \c id, using \c defaultFormat if
no format can be found, then replaces positional parameters in
the format string and returns the result.
*/
virtual CString format(const char* id,
const char* defaultFormat, ...) const throw();
private:
mutable CString m_what;
};
//! Mix-in for handling \c errno
/*!
This mix-in class for exception classes provides storage and query of
\c errno.
*/
class MXErrno {
public:
//! Save \c errno as the error code
MXErrno();
//! Save \c err as the error code
MXErrno(int err);
//! @name accessors
//@{
//! Get the error code
int getErrno() const;
//! Get the human readable string for the error code
const char* getErrstr() const;
//@}
private:
int m_errno;
};
#endif

202
lib/base/base.dsp Normal file
View File

@@ -0,0 +1,202 @@
# Microsoft Developer Studio Project File - Name="base" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Static Library" 0x0104
CFG=base - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "base.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "base.mak" CFG="base - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "base - Win32 Release" (based on "Win32 (x86) Static Library")
!MESSAGE "base - Win32 Debug" (based on "Win32 (x86) Static Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "base - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD CPP /nologo /MT /W4 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /FD /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "base - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /MTd /W4 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /FD /GZ /c
# SUBTRACT CPP /YX
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo
!ENDIF
# Begin Target
# Name "base - Win32 Release"
# Name "base - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\CFunctionJob.cpp
# End Source File
# Begin Source File
SOURCE=.\CLog.cpp
# End Source File
# Begin Source File
SOURCE=.\CStopwatch.cpp
# End Source File
# Begin Source File
SOURCE=.\CString.cpp
# End Source File
# Begin Source File
SOURCE=.\CUnicode.cpp
# End Source File
# Begin Source File
SOURCE=.\XBase.cpp
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\BasicTypes.h
# End Source File
# Begin Source File
SOURCE=.\CFunctionJob.h
# End Source File
# Begin Source File
SOURCE=.\CLog.h
# End Source File
# Begin Source File
SOURCE=.\common.h
# End Source File
# Begin Source File
SOURCE=.\CStopwatch.h
# End Source File
# Begin Source File
SOURCE=.\CString.h
# End Source File
# Begin Source File
SOURCE=.\CUnicode.h
# End Source File
# Begin Source File
SOURCE=.\IInterface.h
# End Source File
# Begin Source File
SOURCE=.\IJob.h
# End Source File
# Begin Source File
SOURCE=.\stdfstream.h
# End Source File
# Begin Source File
SOURCE=.\stdistream.h
# End Source File
# Begin Source File
SOURCE=.\stdlist.h
# End Source File
# Begin Source File
SOURCE=.\stdmap.h
# End Source File
# Begin Source File
SOURCE=.\stdostream.h
# End Source File
# Begin Source File
SOURCE=.\stdpost.h
# End Source File
# Begin Source File
SOURCE=.\stdpre.h
# End Source File
# Begin Source File
SOURCE=.\stdset.h
# End Source File
# Begin Source File
SOURCE=.\stdsstream.h
# End Source File
# Begin Source File
SOURCE=.\stdvector.h
# End Source File
# Begin Source File
SOURCE=.\TMethodJob.h
# End Source File
# Begin Source File
SOURCE=.\XBase.h
# End Source File
# End Group
# End Target
# End Project

60
lib/base/common.h Normal file
View File

@@ -0,0 +1,60 @@
#ifndef COMMON_H
#define COMMON_H
// this file should be included, directly or indirectly by every other.
#if HAVE_CONFIG_H
# include "config.h"
#endif
// check if win32 platform
#if defined(_WIN32) || HAVE_WINDOWS_H
# define WINDOWS_LIKE 1
// VC++ specific
# if (_MSC_VER >= 1200)
// work around for statement scoping bug
# define for if (false) { } else for
// turn off bonehead warnings
# pragma warning(disable: 4786) // identifier truncated in debug info
# pragma warning(disable: 4514) // unreferenced inline function removed
// this one's a little too aggressive
# pragma warning(disable: 4127) // conditional expression is constant
// emitted incorrectly under release build in some circumstances
# if defined(NDEBUG)
# pragma warning(disable: 4702) // unreachable code
# pragma warning(disable: 4701) // variable maybe used uninitialized
# endif
# endif // (_MSC_VER >= 1200)
// VC++ has built-in sized types
# if defined(_MSC_VER)
# define TYPE_OF_SIZE_1 __int8
# define TYPE_OF_SIZE_2 __int16
# define TYPE_OF_SIZE_4 __int32
# else
# define SIZE_OF_CHAR 1
# define SIZE_OF_SHORT 2
# define SIZE_OF_INT 4
# define SIZE_OF_LONG 4
# endif
#endif // defined(_WIN32) || HAVE_WINDOWS_H
// unix-like if not like anything else
#if (!defined(WINDOWS_LIKE) || WINDOWS_LIKE == 0)
# define UNIX_LIKE 1
#endif
// define NULL
#ifndef NULL
#define NULL 0
#endif
// make assert available since we use it a lot
#include <assert.h>
#endif

4
lib/base/stdfstream.h Normal file
View File

@@ -0,0 +1,4 @@
#include "stdpre.h"
#include <fstream>
#include "stdpost.h"
#include "stdistream.h"

29
lib/base/stdistream.h Normal file
View File

@@ -0,0 +1,29 @@
#include "stdpre.h"
#if defined(HAVE_ISTREAM)
#include <istream>
#else
#include <iostream>
#endif
#include "stdpost.h"
#if defined(_MSC_VER) && _MSC_VER <= 1200
// VC++6 istream has no overloads for __int* types, .NET does
inline
std::istream& operator>>(std::istream& s, SInt8& i)
{ return s >> (signed char&)i; }
inline
std::istream& operator>>(std::istream& s, SInt16& i)
{ return s >> (short&)i; }
inline
std::istream& operator>>(std::istream& s, SInt32& i)
{ return s >> (int&)i; }
inline
std::istream& operator>>(std::istream& s, UInt8& i)
{ return s >> (unsigned char&)i; }
inline
std::istream& operator>>(std::istream& s, UInt16& i)
{ return s >> (unsigned short&)i; }
inline
std::istream& operator>>(std::istream& s, UInt32& i)
{ return s >> (unsigned int&)i; }
#endif

3
lib/base/stdlist.h Normal file
View File

@@ -0,0 +1,3 @@
#include "stdpre.h"
#include <list>
#include "stdpost.h"

3
lib/base/stdmap.h Normal file
View File

@@ -0,0 +1,3 @@
#include "stdpre.h"
#include <map>
#include "stdpost.h"

7
lib/base/stdostream.h Normal file
View File

@@ -0,0 +1,7 @@
#include "stdpre.h"
#if defined(HAVE_OSTREAM)
#include <ostream>
#else
#include <iostream>
#endif
#include "stdpost.h"

3
lib/base/stdpost.h Normal file
View File

@@ -0,0 +1,3 @@
#if defined(_MSC_VER)
#pragma warning(pop)
#endif

13
lib/base/stdpre.h Normal file
View File

@@ -0,0 +1,13 @@
#if defined(_MSC_VER)
#pragma warning(disable: 4786) // identifier truncated
#pragma warning(disable: 4514) // unreferenced inline
#pragma warning(disable: 4710) // not inlined
#pragma warning(disable: 4663) // C++ change, template specialization
#pragma warning(disable: 4503) // decorated name length too long
#pragma warning(push, 3)
#pragma warning(disable: 4018) // signed/unsigned mismatch
#pragma warning(disable: 4284)
#pragma warning(disable: 4146) // unary minus on unsigned value
#pragma warning(disable: 4127) // conditional expression is constant
#pragma warning(disable: 4701) // variable possibly used uninitialized
#endif

3
lib/base/stdset.h Normal file
View File

@@ -0,0 +1,3 @@
#include "stdpre.h"
#include <set>
#include "stdpost.h"

4
lib/base/stdsstream.h Normal file
View File

@@ -0,0 +1,4 @@
#include "stdpre.h"
#include <sstream>
#include "stdpost.h"
#include "stdistream.h"

3
lib/base/stdvector.h Normal file
View File

@@ -0,0 +1,3 @@
#include "stdpre.h"
#include <vector>
#include "stdpost.h"