namespace Msp {
+Application *Application::app_ = 0;
+Application::Starter *Application::starter_ = 0;
+void *Application::data_ = 0;
+
Application::Application():
exit_code(0)
{ }
*/
int Application::run(int argc, char **argv, void *data)
{
- static bool called=false;
+ static bool called = false;
if(called)
{
cerr<<"Trying to call Application::run_app twice!\n";
return 125;
}
- called=true;
+ called = true;
if(!starter_)
{
return 126;
}
- data_=data;
+ data_ = data;
try
{
try
{
- app_=starter_->create_app(argc, argv);
+ app_ = starter_->create_app(argc, argv);
}
catch(const UsageError &e)
{
return 1;
}
- int result=app_->main();
- Application *a=app_;
- app_=0;
+ int result = app_->main();
+ Application *a = app_;
+ app_ = 0;
delete a;
return result;
}
delete app_;
#ifdef WIN32
- string msg=Debug::demangle(typeid(e).name())+":\n"+e.what();
+ string msg = Debug::demangle(typeid(e).name())+":\n"+e.what();
MessageBoxA(0, msg.c_str(), "Uncaught exception", MB_OK|MB_ICONERROR);
#else
cerr<<"An uncaught exception occurred.\n";
cerr<<" type: "<<Debug::demangle(typeid(e).name())<<'\n';
cerr<<" what(): "<<e.what()<<'\n';
- const Exception *exc=dynamic_cast<const Exception *>(&e);
+ const Exception *exc = dynamic_cast<const Exception *>(&e);
if(exc && !exc->get_backtrace().get_frames().empty())
{
cerr<<" backtrace:\n";
- const list<Debug::Backtrace::StackFrame> &frames=exc->get_backtrace().get_frames();
+ const list<Debug::Backtrace::StackFrame> &frames = exc->get_backtrace().get_frames();
for(list<Debug::Backtrace::StackFrame>::const_iterator i=frames.begin(); i!=frames.end(); ++i)
cerr<<" "<<*i<<'\n';
}
if(starter_)
throw InvalidState("Can't create more than one Starter instance");
- starter_=this;
+ starter_ = this;
}
-Application *Application::app_=0;
-Application::RegBase *Application::reg_app_=0;
-void *Application::data_=0;
-
} // namespace Msp
static Application *app_;
static void *data_;
+ Application(const Application &);
+ Application &operator=(const Application &);
protected:
Application();
public:
static void sighandler_(int);
};
- Application(const Application &);
- Application &operator=(const Application &);
template<typename T>
class RegisteredApplication: public Application
wot(w)
{
#ifdef WITH_EXCEPTION_BACKTRACE
- bt=Debug::Backtrace::create();
+ bt = Debug::Backtrace::create();
#endif
}
Exception &Exception::at(const std::string &w) throw()
{
- wer=w;
- wot=wer+": "+wot;
+ wer = w;
+ wot = wer+": "+wot;
return *this;
}
bool brief;
public:
- UsageError(const std::string &r, bool b=true): Exception(r), brief(b) { }
+ UsageError(const std::string &r, bool b = true): Exception(r), brief(b) { }
bool get_brief() const { return brief; }
};
/* $Id$
This file is part of libmspcore
-Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
+Copyright © 2006-2009, 2011 Mikko Rasa, Mikkosoft Productions
Distributed under the LGPL
*/
+
#include "getopt.h"
using namespace std;
delete *i;
}
-/**
-Generates a single line that gives an overview about the known options.
-
-@param argv0 The program name to be used in the usage string
-
-@return The generated usage string
-*/
-string GetOpt::generate_usage(const string &argv0) const
+GetOpt::OptBase &GetOpt::get_option(char s)
{
- ostringstream line;
-
- line<<argv0;
- for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
- {
- line<<" [";
- if((*i)->get_short())
- {
- line<<'-'<<(*i)->get_short();
- if(!(*i)->get_long().empty())
- line<<'|';
- else if((*i)->get_arg_type()==OPTIONAL_ARG)
- line<<'['<<(*i)->get_metavar()<<']';
- else if((*i)->get_arg_type()==REQUIRED_ARG)
- line<<' '<<(*i)->get_metavar();
- }
- if(!(*i)->get_long().empty())
- {
- line<<"--"<<(*i)->get_long();
-
- if((*i)->get_arg_type()==OPTIONAL_ARG)
- line<<"[="<<(*i)->get_metavar()<<']';
- else if((*i)->get_arg_type()==REQUIRED_ARG)
- line<<'='<<(*i)->get_metavar();
- }
- line<<']';
- }
-
- return line.str();
+ for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
+ if((*i)->get_short()==s)
+ return **i;
+ throw UsageError(string("Unknown option -")+s);
}
-/**
-Generates help for known options in tabular format, one option per line.
-The returned string will have a linefeed at the end.
-*/
-string GetOpt::generate_help() const
+GetOpt::OptBase &GetOpt::get_option(const string &l)
{
- bool any_short=false;
- for(list<OptBase *>::const_iterator i=opts.begin(); (!any_short && i!=opts.end()); ++i)
- any_short=(*i)->get_short();
-
- string::size_type maxw=0;
- list<string> switches;
- for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
- {
- ostringstream swtch;
- if((*i)->get_short())
- {
- swtch<<'-'<<(*i)->get_short();
- if(!(*i)->get_long().empty())
- swtch<<", ";
- else if((*i)->get_arg_type()==OPTIONAL_ARG)
- swtch<<'['<<(*i)->get_metavar()<<']';
- else if((*i)->get_arg_type()==REQUIRED_ARG)
- swtch<<' '<<(*i)->get_metavar();
- }
- else if(any_short)
- swtch<<" ";
- if(!(*i)->get_long().empty())
- {
- swtch<<"--"<<(*i)->get_long();
-
- if((*i)->get_arg_type()==OPTIONAL_ARG)
- swtch<<"[="<<(*i)->get_metavar()<<']';
- else if((*i)->get_arg_type()==REQUIRED_ARG)
- swtch<<'='<<(*i)->get_metavar();
- }
- switches.push_back(swtch.str());
- maxw=max(maxw, switches.back().size());
- }
-
- string result;
- list<string>::const_iterator j=switches.begin();
- for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i, ++j)
- {
- result+=" "+*j;
- result+=string(maxw+2-j->size(), ' ');
- result+=(*i)->get_help();
- result+='\n';
- }
-
- return result;
+ for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
+ if((*i)->get_long()==l)
+ return **i;
+ throw UsageError(string("Unknown option --")+l);
}
void GetOpt::operator()(unsigned argc, const char *const *argv)
{
- unsigned i=1;
+ unsigned i = 1;
for(; i<argc;)
{
if(argv[i][0]=='-')
if(!argv[i][2])
break;
- i+=process_long(argv+i);
+ i += process_long(argv+i);
}
else
- i+=process_short(argv+i);
+ i += process_short(argv+i);
}
else
args.push_back(argv[i++]);
args.push_back(argv[i]);
}
-GetOpt::OptBase &GetOpt::get_option(char s)
-{
- for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
- if((*i)->get_short()==s)
- return **i;
- throw UsageError(string("Unknown option -")+s);
-}
-
-GetOpt::OptBase &GetOpt::get_option(const string &l)
-{
- for(list<OptBase *>::iterator i=opts.begin(); i!=opts.end(); ++i)
- if((*i)->get_long()==l)
- return **i;
- throw UsageError(string("Unknown option --")+l);
-}
-
-/**
-Processes the given argument as a long option.
-
-@param argp Pointer to the argument
-
-@return The number of arguments eaten (1 or 2)
-*/
unsigned GetOpt::process_long(const char *const *argp)
{
// Skip the --
- const char *arg=argp[0]+2;
+ const char *arg = argp[0]+2;
// See if the argument contains an =
- unsigned equals=0;
+ unsigned equals = 0;
for(; arg[equals] && arg[equals]!='='; ++equals) ;
- OptBase &opt=get_option(string(arg, equals));
+ OptBase &opt = get_option(string(arg, equals));
if(arg[equals])
// Process the part after the = as option argument
return 1;
}
-/**
-Processes short options from the given argument.
-
-@param argp Pointer to the argument
-
-@return The number of arguments eaten (1 or 2)
-*/
unsigned GetOpt::process_short(const char *const *argp)
{
// Skip the -
- const char *arg=argp[0]+1;
+ const char *arg = argp[0]+1;
// Loop through all characters in the argument
for(; *arg; ++arg)
{
- OptBase &opt=get_option(*arg);
+ OptBase &opt = get_option(*arg);
if(arg[1] && opt.get_arg_type()!=NO_ARG)
{
return 1;
}
+string GetOpt::generate_usage(const string &argv0) const
+{
+ ostringstream line;
+
+ line<<argv0;
+ for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
+ {
+ line<<" [";
+ if((*i)->get_short())
+ {
+ line<<'-'<<(*i)->get_short();
+ if(!(*i)->get_long().empty())
+ line<<'|';
+ else if((*i)->get_arg_type()==OPTIONAL_ARG)
+ line<<'['<<(*i)->get_metavar()<<']';
+ else if((*i)->get_arg_type()==REQUIRED_ARG)
+ line<<' '<<(*i)->get_metavar();
+ }
+ if(!(*i)->get_long().empty())
+ {
+ line<<"--"<<(*i)->get_long();
+
+ if((*i)->get_arg_type()==OPTIONAL_ARG)
+ line<<"[="<<(*i)->get_metavar()<<']';
+ else if((*i)->get_arg_type()==REQUIRED_ARG)
+ line<<'='<<(*i)->get_metavar();
+ }
+ line<<']';
+ }
+
+ return line.str();
+}
+
+string GetOpt::generate_help() const
+{
+ bool any_short = false;
+ for(list<OptBase *>::const_iterator i=opts.begin(); (!any_short && i!=opts.end()); ++i)
+ any_short = (*i)->get_short();
+
+ string::size_type maxw = 0;
+ list<string> switches;
+ for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i)
+ {
+ ostringstream swtch;
+ if((*i)->get_short())
+ {
+ swtch<<'-'<<(*i)->get_short();
+ if(!(*i)->get_long().empty())
+ swtch<<", ";
+ else if((*i)->get_arg_type()==OPTIONAL_ARG)
+ swtch<<'['<<(*i)->get_metavar()<<']';
+ else if((*i)->get_arg_type()==REQUIRED_ARG)
+ swtch<<' '<<(*i)->get_metavar();
+ }
+ else if(any_short)
+ swtch<<" ";
+ if(!(*i)->get_long().empty())
+ {
+ swtch<<"--"<<(*i)->get_long();
+
+ if((*i)->get_arg_type()==OPTIONAL_ARG)
+ swtch<<"[="<<(*i)->get_metavar()<<']';
+ else if((*i)->get_arg_type()==REQUIRED_ARG)
+ swtch<<'='<<(*i)->get_metavar();
+ }
+ switches.push_back(swtch.str());
+ maxw = max(maxw, switches.back().size());
+ }
+
+ string result;
+ list<string>::const_iterator j = switches.begin();
+ for(list<OptBase *>::const_iterator i=opts.begin(); i!=opts.end(); ++i, ++j)
+ {
+ result += " "+*j;
+ result += string(maxw+2-j->size(), ' ');
+ result += (*i)->get_help();
+ result += '\n';
+ }
+
+ return result;
+}
+
GetOpt::OptBase::OptBase(char s, const std::string &l, ArgType a):
shrt(s),
GetOpt::OptBase &GetOpt::OptBase::set_help(const string &h)
{
- help=h;
+ help = h;
return *this;
}
GetOpt::OptBase &GetOpt::OptBase::set_help(const string &h, const string &m)
{
- help=h;
- metavar=m;
+ help = h;
+ metavar = m;
return *this;
}
/* $Id$
This file is part of libmspcore
-Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
+Copyright © 2006-2009, 2011 Mikko Rasa, Mikkosoft Productions
Distributed under the LGPL
*/
+
#ifndef MSP_CORE_GETOPT_H_
#define MSP_CORE_GETOPT_H_
class OptBase
{
- public:
- OptBase &set_help(const std::string &);
- OptBase &set_help(const std::string &, const std::string &);
- char get_short() const { return shrt; }
- const std::string &get_long() const { return lng; }
- ArgType get_arg_type() const { return arg_type; }
- const std::string &get_help() const { return help; }
- const std::string &get_metavar() const { return metavar; }
- unsigned get_seen_count() const { return seen_count; }
- void process();
- void process(const std::string &);
- virtual ~OptBase() { }
protected:
- char shrt;
+ char shrt;
std::string lng;
- ArgType arg_type;
- unsigned seen_count;
+ ArgType arg_type;
+ unsigned seen_count;
std::string help;
std::string metavar;
OptBase(char, const std::string &, ArgType);
- virtual void store()=0;
- virtual void store(const std::string &)=0;
+ public:
+ virtual ~OptBase() { }
+
+ OptBase &set_help(const std::string &);
+ OptBase &set_help(const std::string &, const std::string &);
+ char get_short() const { return shrt; }
+ const std::string &get_long() const { return lng; }
+ ArgType get_arg_type() const { return arg_type; }
+ const std::string &get_help() const { return help; }
+ const std::string &get_metavar() const { return metavar; }
+ unsigned get_seen_count() const { return seen_count; }
+ void process();
+ void process(const std::string &);
+ protected:
+ virtual void store() = 0;
+ virtual void store(const std::string &) = 0;
};
private:
if(ss.fail())
throw UsageError("Invalid argument for --"+lng);
- data=tmp;
+ data = tmp;
}
private:
T &data;
const std::vector<std::string> &get_args() const { return args; }
template<typename T>
- OptBase &add_option(char s, const std::string &l, T &d, ArgType a=NO_ARG)
+ OptBase &add_option(char s, const std::string &l, T &d, ArgType a = NO_ARG)
{ opts.push_back(new Option<T>(s, l, d, a)); return *opts.back(); }
template<typename T>
- OptBase &add_option(char s, const std::string &l, std::list<T> &d, ArgType a=REQUIRED_ARG)
+ OptBase &add_option(char s, const std::string &l, std::list<T> &d, ArgType a = REQUIRED_ARG)
{ opts.push_back(new ListOption<std::list<T> >(s, l, d, a)); return *opts.back(); }
template<typename T>
OptBase &add_option(const std::string &l, T &d, ArgType a)
{ return add_option(0, l, d, a); }
- std::string generate_usage(const std::string &) const;
- std::string generate_help() const;
- void operator()(unsigned, const char *const *);
private:
-
OptBase &get_option(char);
OptBase &get_option(const std::string &);
+
+public:
+ /** Processes argc/argv style command line arguments. The contents of argv
+ will be unchanged; use get_args to access non-option arguments. */
+ void operator()(unsigned, const char *const *);
+
+private:
+ /** Processes a long option. Returns the number of arguments eaten. */
unsigned process_long(const char *const *);
+
+ /** Processes short options. Returns the number of arguments eaten. */
unsigned process_short(const char *const *);
+
+public:
+ /** Generates a single line that describes known options. */
+ std::string generate_usage(const std::string &) const;
+
+ /** Generates help for known options in tabular format, one option per
+ line. The returned string will have a linefeed at the end. */
+ std::string generate_help() const;
};
-template<> inline void GetOpt::Option<bool>::store() { data=true; }
+template<> inline void GetOpt::Option<bool>::store() { data = true; }
template<> inline void GetOpt::Option<unsigned>::store() { ++data; }
template<> inline void GetOpt::Option<std::string>::store(const std::string &a)
-{ data=a; }
+{ data = a; }
template<> inline void GetOpt::ListOption<std::list<std::string> >::store(const std::string &a)
{ data.push_back(a); }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int /*nCmdShow*/)
{
int argc = 0;
- LPWSTR *argv=CommandLineToArgvW(GetCommandLineW(), &argc);
+ LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(), &argc);
return Msp::Application::run(argc, (char **)argv, hInstance);
}
#endif
int unlock() { return pthread_mutex_unlock(&mutex); }
~Mutex() { pthread_mutex_destroy(&mutex); }
#else
- Mutex() { mutex=CreateMutex(0, false, 0); }
+ Mutex() { mutex = CreateMutex(0, false, 0); }
int lock() { return WaitForSingleObject(mutex, INFINITE)==WAIT_OBJECT_0; }
int trylock() { return WaitForSingleObject(mutex, 0)==WAIT_OBJECT_0; }
int unlock() { return !ReleaseMutex(mutex); }
Mutex &mutex;
public:
- MutexLock(Mutex &m, bool l=true): mutex(m) { if(l) mutex.lock(); }
+ MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); }
~MutexLock() { mutex.unlock(); }
int lock() { return mutex.lock(); }
T &operator*() const { return *data; }
T *operator->() const { return data; }
- void clear() { mutex=0; data=0; }
+ void clear() { mutex=0; data = 0; }
private:
RefPtr<MutexLock> mutex;
T *data;
MutexPtr(const MutexPtr<T> &p): RefCount(p), mutex(p.mutex), data(p.data) { }
T &operator*() const { return *data; }
T *operator->() const { return data; }
- void clear() { decref(); data=0; }
+ void clear() { decref(); data = 0; }
~MutexPtr() { decref(); }
protected:
Mutex &mutex;
/* $Id$
This file is part of libmspcore
-Copyright © 2006-2007, 2010 Mikko Rasa, Mikkosoft Productions
+Copyright © 2006-2007, 2010-2011 Mikko Rasa, Mikkosoft Productions
Distributed under the LGPL
*/
template<typename T>
class RefPtr
{
+ template<typename U> friend class RefPtr;
+
private:
enum
{
KEEP = 1U<<(sizeof(unsigned)*8-1)
};
+ T *data;
+ unsigned *count;
+
public:
RefPtr(): data(0), count(0) { }
RefPtr(T *d): data(d), count(data ? new unsigned(1) : 0) { }
+private:
+ RefPtr(T *d, unsigned *c): data(d), count(d ? c : 0) { incref(); }
- // Must have this or the compiler will generate a default copy-c'tor
+public:
+ /* Must have this or the compiler will generate a default copy-c'tor despite
+ the template version */
RefPtr(const RefPtr &p): data(p.data), count(p.count) { incref(); }
template<typename U>
RefPtr(const RefPtr<U> &p): data(p.data), count(p.count) { incref(); }
+ ~RefPtr() { decref(); }
+
RefPtr &operator=(T *d)
{
decref();
template<typename U>
RefPtr &operator=(const RefPtr<U> &p) { return assign(p); }
-
- ~RefPtr() { decref(); }
- /**
- Makes the RefPtr release its reference of the data. Note that if there are
- other RefPtrs left with the same data, it might still get deleted
- automatically.
- */
+private:
+ template<typename U>
+ RefPtr &assign(const RefPtr<U> &p)
+ {
+ decref();
+ data = p.data;
+ count = p.count;
+ incref();
+ return *this;
+ }
+
+public:
+ /** Makes the RefPtr release its reference of the data without deleting it.
+ Note that if there are other RefPtrs left with the same data, it might
+ still get deleted automatically. */
T *release()
{
T *d = data;
return d;
}
- /**
- Marks the data to not be deleted. This affects all RefPtrs with the same
- data.
- */
+ /** Marks the data to not be deleted. This affects all RefPtrs with the
+ same data. */
void keep()
{
if(count)
static RefPtr<T> cast_dynamic(const RefPtr<U> &p)
{ return RefPtr<T>(dynamic_cast<T *>(p.data), p.count); }
- template<typename U> friend class RefPtr;
private:
- T *data;
- unsigned *count;
-
- RefPtr(T *d, unsigned *c): data(d), count(d ? c : 0) { incref(); }
-
- template<typename U>
- RefPtr &assign(const RefPtr<U> &p)
- {
- decref();
- data = p.data;
- count = p.count;
- incref();
- return *this;
- }
-
void incref()
{
if(!count) return;
void Semaphore::init()
{
#ifdef WIN32
- count=0;
- sem=CreateSemaphore(0, 0, 32, 0);
+ count = 0;
+ sem = CreateSemaphore(0, 0, 32, 0);
#else
pthread_cond_init(&sem, 0);
#endif
if(count==0)
return 0;
- int ret=!ReleaseSemaphore(sem, 1, 0);
+ int ret = !ReleaseSemaphore(sem, 1, 0);
- unsigned old_count=count;
+ unsigned old_count = count;
mutex->unlock();
while(count==old_count)
Sleep(0);
{
if(count==0)
return 0;
- int ret=!ReleaseSemaphore(sem, count, 0);
+ int ret = !ReleaseSemaphore(sem, count, 0);
mutex->unlock();
while(count)
{
++count;
mutex->unlock();
- DWORD ret=WaitForSingleObject(sem, INFINITE);
+ DWORD ret = WaitForSingleObject(sem, INFINITE);
mutex->lock();
--count;
int Semaphore::wait(const Time::TimeDelta &d)
{
#ifndef WIN32
- Time::TimeStamp ts=Time::now()+d;
+ Time::TimeStamp ts = Time::now()+d;
timespec timeout;
- timeout.tv_sec=ts.raw()/1000000;
- timeout.tv_nsec=(ts.raw()%1000000)*1000;
+ timeout.tv_sec = ts.raw()/1000000;
+ timeout.tv_nsec = (ts.raw()%1000000)*1000;
- int r=pthread_cond_timedwait(&sem, &mutex->mutex, &timeout);
+ int r = pthread_cond_timedwait(&sem, &mutex->mutex, &timeout);
if(r==ETIMEDOUT)
return 1;
else if(r)
#else
++count;
mutex->lock();
- DWORD ret=WaitForSingleObject(sem, (DWORD)(d/Time::usec));
+ DWORD ret = WaitForSingleObject(sem, (DWORD)(d/Time::usec));
mutex->unlock();
--count;
return ret==WAIT_OBJECT_0;
#else
pthread_join(thread_, 0);
#endif
- launched_=false;
+ launched_ = false;
}
/**
#ifdef WIN32
DWORD dummy; // Win9x needs the lpTthreadId parameter
- thread_=CreateThread(0, 0, &main_, this, 0, &dummy);
+ thread_ = CreateThread(0, 0, &main_, this, 0, &dummy);
#else
pthread_create(&thread_, 0, &main_, this);
#endif
- launched_=true;
+ launched_ = true;
}
} // namespace Msp
void kill();
protected:
void launch();
- virtual void main()=0;
+ virtual void main() = 0;
void check_cancel();
private:
Variant &operator=(const T &v)
{
delete store;
- store=new Store<typename RemoveConst<T>::Type>(v);
+ store = new Store<typename RemoveConst<T>::Type>(v);
return *this;
}
Variant &operator=(const Variant &v)
{
delete store;
- store=(v.store ? v.store->clone() : 0);
+ store = (v.store ? v.store->clone() : 0);
return *this;
}
T &value() const
{
typedef typename RemoveConst<T>::Type NCT;
- Store<NCT> *s=dynamic_cast<Store<NCT> *>(store);
+ Store<NCT> *s = dynamic_cast<Store<NCT> *>(store);
if(!s)
throw InvalidState("Type mismatch");
return s->data;
{
#if !defined(WIN32) && defined(__GLIBC__)
void *addresses[50];
- int count=::backtrace(addresses, 50);
+ int count = ::backtrace(addresses, 50);
Backtrace bt;
Dl_info dli;
for(int i=0; i<count; ++i)
{
StackFrame frame;
- frame.address=addresses[i];
+ frame.address = addresses[i];
if(dladdr(addresses[i], &dli))
{
- frame.file=dli.dli_fname;
+ frame.file = dli.dli_fname;
if(dli.dli_sname)
- frame.symbol=demangle(dli.dli_sname);
+ frame.symbol = demangle(dli.dli_sname);
}
else
- frame.file="<unknown>";
+ frame.file = "<unknown>";
bt.frames.push_back(frame);
}
ostream &operator<<(ostream &out, const Backtrace &bt)
{
- const list<Backtrace::StackFrame> &frames=bt.get_frames();
+ const list<Backtrace::StackFrame> &frames = bt.get_frames();
for(list<Backtrace::StackFrame>::const_iterator i=frames.begin(); i!=frames.end(); ++i)
out<<*i<<'\n';
{
#ifdef __GNUC__
int status;
- char *dm=abi::__cxa_demangle(sym.c_str(), 0, 0, &status);
+ char *dm = abi::__cxa_demangle(sym.c_str(), 0, 0, &status);
string result;
if(status==0)
- result=dm;
+ result = dm;
else
- result=sym;
+ result = sym;
free(dm);
if(p==period)
return;
- period=p;
+ period = p;
for(map<string, ScopeInfo>::iterator i=scopes.begin(); i!=scopes.end(); ++i)
{
- ScopeInfo &si=i->second;
+ ScopeInfo &si = i->second;
if(p==0)
si.history.clear();
else
si.history.assign(period, Time::zero);
- si.hist_pos=0;
+ si.hist_pos = 0;
}
}
{
if(!scopes.count(name))
{
- map<string, ScopeInfo>::iterator i=scopes.insert(map<string, ScopeInfo>::value_type(name, ScopeInfo())).first;
+ map<string, ScopeInfo>::iterator i = scopes.insert(map<string, ScopeInfo>::value_type(name, ScopeInfo())).first;
i->second.history.resize(period);
}
}
ProfilingScope *Profiler::enter(ProfilingScope *ps)
{
- ProfilingScope *old=inner;
- inner=ps;
+ ProfilingScope *old = inner;
+ inner = ps;
return old;
}
void Profiler::record(const string &scope_name, const string &parent, const Time::TimeDelta &time, const Time::TimeDelta &child_t)
{
- map<string, ScopeInfo>::iterator i=scopes.find(scope_name);
+ map<string, ScopeInfo>::iterator i = scopes.find(scope_name);
if(i==scopes.end())
{
- i=scopes.insert(map<string, ScopeInfo>::value_type(scope_name, ScopeInfo())).first;
+ i = scopes.insert(map<string, ScopeInfo>::value_type(scope_name, ScopeInfo())).first;
i->second.history.resize(period);
}
- ScopeInfo &si=i->second;
+ ScopeInfo &si = i->second;
++si.calls;
++si.called_from[parent];
- si.total_time+=time;
- si.self_time+=time-child_t;
+ si.total_time += time;
+ si.self_time += time-child_t;
if(period)
{
- si.avg_time+=time/period-si.history[si.hist_pos]/period;
- si.history[si.hist_pos++]=time;
+ si.avg_time += time/period-si.history[si.hist_pos]/period;
+ si.history[si.hist_pos++] = time;
if(si.hist_pos>=period)
- si.hist_pos-=period;
+ si.hist_pos -= period;
}
else
- si.avg_time=si.total_time/si.calls;
+ si.avg_time = si.total_time/si.calls;
}
const Profiler::ScopeInfo &Profiler::scope(const string &sn) const
{
- map<string, ScopeInfo>::const_iterator i=scopes.find(sn);
+ map<string, ScopeInfo>::const_iterator i = scopes.find(sn);
if(i==scopes.end())
throw KeyError("Unknown scope");
ProfilingScope::~ProfilingScope()
{
- const Time::TimeDelta dt=Time::now()-start_t;
+ const Time::TimeDelta dt = Time::now()-start_t;
if(parent)
{
- parent->child_t+=dt;
+ parent->child_t += dt;
profiler.record(name, parent->name, dt, child_t);
}
else
void DateTime::add_days(int days)
{
- int new_year=year;
+ int new_year = year;
/* Leap years have a 400 year cycle, so any 400 consecutive years have a
- constant number of days (400*365+97=146097) */
- new_year+=days/146097*400;
- days%=146097;
+ constant number of days (400*365+97 = 146097) */
+ new_year += days/146097*400;
+ days %= 146097;
if(days<0)
{
- new_year-=400;
- days+=146097;
+ new_year -= 400;
+ days += 146097;
}
// Fudge factor for leap day
- int fudge=(month<=2)?1:0;
+ int fudge = (month<=2)?1:0;
// (Almost) every 4 year cycle has 1 leap year and 3 normal years
- unsigned cycles=days/1461;
- days%=1461;
+ unsigned cycles = days/1461;
+ days %= 1461;
- new_year+=cycles*4;
+ new_year += cycles*4;
// See how many non-leap-years we counted as leap years and reclaim the lost days
// XXX This breaks with negative years
- unsigned missed_leap_days=((year-fudge)%100+cycles*4)/100;
+ unsigned missed_leap_days = ((year-fudge)%100+cycles*4)/100;
if((year-fudge)%400+cycles*4>=400)
--missed_leap_days;
- days+=missed_leap_days;
+ days += missed_leap_days;
// Count single years from the 4 year cycle
- cycles=days/365;
- days%=365;
+ cycles = days/365;
+ days %= 365;
- new_year+=cycles;
+ new_year += cycles;
if((year-fudge)%4+cycles>=4)
{
// We passed a leap year - decrement days
if(days==0)
{
- days=is_leap_year(new_year-fudge)?365:364;
+ days = is_leap_year(new_year-fudge)?365:364;
--new_year;
}
else
--days;
}
- year=new_year;
+ year = new_year;
// Step months
while(mday+days>month_days(year, month))
{
- days-=month_days(year, month);
+ days -= month_days(year, month);
++month;
if(month>12)
{
++year;
- month=1;
+ month = 1;
}
}
- mday+=days;
+ mday += days;
}
void DateTime::set_timezone(const TimeZone &tz)
{
- zone=tz;
+ zone = tz;
}
void DateTime::convert_timezone(const TimeZone &tz)
{
add_raw((zone.get_offset()-tz.get_offset()).raw());
- zone=tz;
+ zone = tz;
}
DateTime DateTime::operator+(const TimeDelta &td) const
int DateTime::cmp(const DateTime &dt) const
{
- if(int c=cmp_(year, dt.year))
+ if(int c = cmp_(year, dt.year))
return c;
- if(int c=cmp_(month, dt.month))
+ if(int c = cmp_(month, dt.month))
return c;
- if(int c=cmp_(mday, dt.mday))
+ if(int c = cmp_(mday, dt.mday))
return c;
- if(int c=cmp_(hour, dt.hour))
+ if(int c = cmp_(hour, dt.hour))
return c;
- if(int c=cmp_(minute, dt.minute))
+ if(int c = cmp_(minute, dt.minute))
return c;
- if(int c=cmp_(second, dt.second))
+ if(int c = cmp_(second, dt.second))
return c;
- if(int c=cmp_(usec, dt.usec))
+ if(int c = cmp_(usec, dt.usec))
return c;
return 0;
}
if(year<-289701 || year>293641)
throw InvalidState("DateTime is not representable as a TimeStamp");
- RawTime raw=(((hour*60LL)+minute)*60+second)*1000000+usec;
- int days=(year-1970)*365;
- days+=(year-1)/4-(year-1)/100+(year-1)/400-477;
+ RawTime raw = (((hour*60LL)+minute)*60+second)*1000000+usec;
+ int days = (year-1970)*365;
+ days += (year-1)/4-(year-1)/100+(year-1)/400-477;
for(unsigned i=1; i<month; ++i)
- days+=month_days(year, i);
- days+=mday-1;
+ days += month_days(year, i);
+ days += mday-1;
- raw+=days*86400000000LL;
+ raw += days*86400000000LL;
return TimeStamp(raw);
}
string DateTime::format_rfc3339() const
{
- string result=format("%Y-%m-%dT%H:%M:%S");
- if(const TimeDelta &offs=zone.get_offset())
+ string result = format("%Y-%m-%dT%H:%M:%S");
+ if(const TimeDelta &offs = zone.get_offset())
{
ostringstream ss;
ss.fill('0');
- int m=abs(static_cast<int>(offs/Time::min));
+ int m = abs(static_cast<int>(offs/Time::min));
ss<<(offs<zero ? '+' : '-')<<setw(2)<<m/60<<':'<<setw(2)<<m%60;
- result+=ss.str();
+ result += ss.str();
}
else
- result+='Z';
+ result += 'Z';
return result;
}
void DateTime::init(const TimeStamp &ts)
{
- year=1970;
- month=1;
- mday=1;
- hour=0;
- minute=0;
- second=0;
- usec=0;
+ year = 1970;
+ month = 1;
+ mday = 1;
+ hour = 0;
+ minute = 0;
+ second = 0;
+ usec = 0;
add_raw(ts.raw());
}
void DateTime::init(int y, unsigned char m, unsigned char d, unsigned char h, unsigned char n, unsigned char s, unsigned u)
{
- year=y;
- month=m;
- mday=d;
- hour=h;
- minute=n;
- second=s;
- usec=u;
+ year = y;
+ month = m;
+ mday = d;
+ hour = h;
+ minute = n;
+ second = s;
+ usec = u;
validate();
}
void DateTime::add_raw(RawTime raw)
{
- int days=static_cast<int>(raw/86400000000LL);
- raw%=86400000000LL;
+ int days = static_cast<int>(raw/86400000000LL);
+ raw %= 86400000000LL;
if(raw<0)
{
--days;
- raw+=86400000000LL;
+ raw += 86400000000LL;
}
- usec+=raw%1000000; raw/=1000000;
- second+=raw%60; raw/=60;
- minute+=raw%60; raw/=60;
- hour+=raw%24; raw/=24;
+ usec+=raw%1000000; raw /= 1000000;
+ second+=raw%60; raw /= 60;
+ minute+=raw%60; raw /= 60;
+ hour+=raw%24; raw /= 24;
add_days(days);
normalize();
void DateTime::normalize()
{
- second+=usec/1000000;
- usec%=1000000;
- minute+=second/60;
- second%=60;
- hour+=minute/60;
- minute%=60;
- mday+=hour/24;
- hour%=24;
+ second += usec/1000000;
+ usec %= 1000000;
+ minute += second/60;
+ second %= 60;
+ hour += minute/60;
+ minute %= 60;
+ mday += hour/24;
+ hour %= 24;
while(mday>month_days(year, month))
{
- mday-=month_days(year, month);
+ mday -= month_days(year, month);
++month;
if(month>12)
{
++year;
- month=1;
+ month = 1;
}
}
}
out<<sep<<setw(2);
out<<value/unit;
- value%=unit;
- first=false;
+ value %= unit;
+ first = false;
}
}
ostringstream ss;
ss.fill('0');
- RawTime value=td.raw();
+ RawTime value = td.raw();
if(value<0)
{
ss<<'-';
- value=-value;
+ value = -value;
}
if(value==0)
else if(value<1000000)
{
ss<<value/1000;
- value%=1000;
+ value %= 1000;
if(value)
ss<<'.'<<setw(3)<<value;
ss<<"ms";
}
else
{
- bool first=true;
+ bool first = true;
print_part(ss, value, 86400000000LL, 0, first);
print_part(ss, value, 3600000000LL, '-', first);
print_part(ss, value, 60000000LL, ':', first);
Fills in a timespec struct. To get a meaningful scalar value from the
TimeDelta, divide with one of the values in units.h.
*/
- void fill_timespec(timespec &ts) const { ts.tv_sec=usec/1000000; ts.tv_nsec=(usec%1000000)*1000; }
+ void fill_timespec(timespec &ts) const { ts.tv_sec=usec/1000000; ts.tv_nsec = (usec%1000000)*1000; }
- void fill_timeval(timeval &tv) const { tv.tv_sec=usec/1000000; tv.tv_usec=usec%1000000; }
+ void fill_timeval(timeval &tv) const { tv.tv_sec=usec/1000000; tv.tv_usec = usec%1000000; }
#endif
TimeDelta operator+(const TimeDelta &t) const { return TimeDelta(usec+t.usec); }
Timer::Slot &Timer::add(const TimeDelta &td)
{
- Slot *s=new Slot(td);
+ Slot *s = new Slot(td);
mutex.lock();
slots.push_back(s);
push_heap(slots.begin(), slots.end());
Timer::Slot &Timer::add(const TimeStamp &ts)
{
- Slot *s=new Slot(ts);
+ Slot *s = new Slot(ts);
{
MutexLock l(mutex);
slots.push_back(s);
void Timer::tick(bool block)
{
- Slot *next=0;
+ Slot *next = 0;
{
MutexLock l(mutex);
while(1)
return;
}
- next=slots.begin()->slot;
- const TimeStamp &stamp=next->get_timeout();
- const TimeStamp t=now();
+ next = slots.begin()->slot;
+ const TimeStamp &stamp = next->get_timeout();
+ const TimeStamp t = now();
if(stamp<=t)
break;
else if(block)
{
if(!interval)
return false;
- timeout+=interval;
+ timeout += interval;
return true;
}
Note: If there are no active timers when a blocking tick is executed, it
won't return until a timer is added from another thread.
*/
- void tick(bool block=true);
+ void tick(bool block = true);
TimeStamp get_next_timeout() const;
};
#ifndef WIN32
long get_long(char *&ptr)
{
- long result=0;
+ long result = 0;
for(unsigned i=0; i<4; ++i)
- result=(result<<8)+static_cast<unsigned char >(*ptr++);
+ result = (result<<8)+static_cast<unsigned char >(*ptr++);
return result;
}
#endif
{
#ifdef WIN32
TIME_ZONE_INFORMATION tzinfo;
- DWORD dst=GetTimeZoneInformation(&tzinfo);
+ DWORD dst = GetTimeZoneInformation(&tzinfo);
if(dst==TIME_ZONE_ID_INVALID)
throw Msp::SystemError("Failed to get time zone information", GetLastError());
- int offset=tzinfo.Bias;
+ int offset = tzinfo.Bias;
if(dst==TIME_ZONE_ID_STANDARD)
- offset+=tzinfo.StandardBias;
+ offset += tzinfo.StandardBias;
else if(dst==TIME_ZONE_ID_DAYLIGHT)
- offset+=tzinfo.DaylightBias;
+ offset += tzinfo.DaylightBias;
return TimeZone(offset);
#else
- int fd=open("/etc/localtime", O_RDONLY);
+ int fd = open("/etc/localtime", O_RDONLY);
if(fd>=-1)
{
char hdr[44];
- int len=read(fd, hdr, sizeof(hdr));
- long gmtoff=-1;
+ int len = read(fd, hdr, sizeof(hdr));
+ long gmtoff = -1;
string name;
if(len==44 && hdr[0]=='T' && hdr[1]=='Z' && hdr[2]=='i' && hdr[3]=='f')
{
- char *ptr=hdr+20;
- long isgmtcnt=get_long(ptr);
- long isstdcnt=get_long(ptr);
- long leapcnt=get_long(ptr);
- long timecnt=get_long(ptr);
- long typecnt=get_long(ptr);
- long charcnt=get_long(ptr);
- int size=timecnt*5+typecnt*6+isgmtcnt+isstdcnt+leapcnt*8+charcnt;
+ char *ptr = hdr+20;
+ long isgmtcnt = get_long(ptr);
+ long isstdcnt = get_long(ptr);
+ long leapcnt = get_long(ptr);
+ long timecnt = get_long(ptr);
+ long typecnt = get_long(ptr);
+ long charcnt = get_long(ptr);
+ int size = timecnt*5+typecnt*6+isgmtcnt+isstdcnt+leapcnt*8+charcnt;
char buf[size];
- len=read(fd, buf, size);
+ len = read(fd, buf, size);
if(len==size)
{
- ptr=buf;
- int index=-1;
- time_t cur_time=Msp::Time::now().to_unixtime();
+ ptr = buf;
+ int index = -1;
+ time_t cur_time = Msp::Time::now().to_unixtime();
for(int i=0; i<timecnt; ++i)
if(get_long(ptr)<=cur_time)
- index=i;
+ index = i;
if(index>0)
- index=ptr[index];
- ptr+=timecnt;
+ index = ptr[index];
+ ptr += timecnt;
- int abbrind=0;
+ int abbrind = 0;
for(int i=0; i<typecnt; ++i)
{
if((index>=0 && i==index) || (index<0 && !ptr[4] && gmtoff==-1))
{
- gmtoff=get_long(ptr);
+ gmtoff = get_long(ptr);
++ptr;
- abbrind=*ptr++;
+ abbrind = *ptr++;
}
else
- ptr+=6;
+ ptr += 6;
}
- name=ptr+abbrind;
+ name = ptr+abbrind;
}
}
close(fd);
{
ostringstream ss;
ss.fill('0');
- int m=abs(minutes_west);
+ int m = abs(minutes_west);
ss<<"UTC"<<(minutes_west<0 ? '-' : '+')<<m/60;
if(m%60)
ss<<':'<<setw(2)<<m%60;
}
else
- name="UTC";
+ name = "UTC";
}
TimeZone::TimeZone(int minutes_west, const string &n):
const TimeZone &TimeZone::local()
{
- static TimeZone tz=get_local_timezone();
+ static TimeZone tz = get_local_timezone();
return tz;
}
gettimeofday(&tv, 0);
return TimeStamp(tv.tv_sec*1000000LL+tv.tv_usec);
#else
- static RawTime epoch=0;
+ static RawTime epoch = 0;
if(!epoch)
{
SYSTEMTIME st;
- st.wYear=1970;
- st.wMonth=1;
- st.wDay=1;
- st.wHour=0;
- st.wMinute=0;
- st.wSecond=0;
- st.wMilliseconds=0;
+ st.wYear = 1970;
+ st.wMonth = 1;
+ st.wDay = 1;
+ st.wHour = 0;
+ st.wMinute = 0;
+ st.wSecond = 0;
+ st.wMilliseconds = 0;
FILETIME ft;
SystemTimeToFileTime(&st, &ft);
- epoch=(ft.dwLowDateTime+(static_cast<RawTime>(ft.dwHighDateTime)<<32))/10;
+ epoch = (ft.dwLowDateTime+(static_cast<RawTime>(ft.dwHighDateTime)<<32))/10;
}
FILETIME ft;