From 30a1bd63b44a9d59f02231ed7b013164e957da52 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Wed, 8 Jun 2011 16:07:31 +0300 Subject: [PATCH 01/16] Improve exceptions for Regex and RegMatch --- source/strings/regex.cpp | 61 ++++++++++++++++++++++++++----------- source/strings/regex.h | 14 ++++++++- source/strings/regmatch.cpp | 4 +-- 3 files changed, 58 insertions(+), 21 deletions(-) diff --git a/source/strings/regex.cpp b/source/strings/regex.cpp index bfd25c7..5b04764 100644 --- a/source/strings/regex.cpp +++ b/source/strings/regex.cpp @@ -1,6 +1,6 @@ -#include #include -#include +#include +#include #include "format.h" #include "regex.h" @@ -31,6 +31,28 @@ T read_int(Msp::Regex::Code::const_iterator &c) namespace Msp { +bad_regex::bad_regex(const string &w, const string &e, const string::const_iterator &i): + logic_error(w+"\n"+make_where(e, i)) +{ } + +string bad_regex::make_where(const string &e, const string::const_iterator &i) +{ + string result; + string::size_type offset = i-e.begin(); + if(offset>40) + { + result = e.substr(offset-40, 60); + offset = 40; + } + else + result = e.substr(0, 60); + result += '\n'; + result.append(offset, ' '); + result += '^'; + return result; +} + + Regex::Regex(const string &expr) { n_groups = 0; @@ -42,7 +64,7 @@ Regex::Regex(const string &expr) Regex::Code Regex::compile(const string &expr, string::const_iterator &iter, unsigned &group, bool branch) { bool has_branches = false; - unsigned level = 0; + stack parens; bool escape = false; unsigned bracket = 0; string::const_iterator end; @@ -62,19 +84,19 @@ Regex::Code Regex::compile(const string &expr, string::const_iterator &iter, uns else if(*end=='\\') escape = true; else if(*end=='(') - ++level; + parens.push(end); else if(*end==')') { - if(level==0) + if(parens.empty()) { if(group==0) - throw InvalidParameterValue("Unexpected )"); + throw bad_regex("unmatched ')'", expr, end); else break; } - --level; + parens.pop(); } - else if(*end=='|' && level==0) + else if(*end=='|' && parens.empty()) { if(branch) break; @@ -85,8 +107,8 @@ Regex::Code Regex::compile(const string &expr, string::const_iterator &iter, uns bracket = 1; } - if(level>0) - throw InvalidParameterValue("Unmatched ("); + if(!parens.empty()) + throw bad_regex("unmatched '('", expr, parens.top()); Code result; @@ -107,7 +129,7 @@ Regex::Code Regex::compile(const string &expr, string::const_iterator &iter, uns Count repeat_min = 1; Count repeat_max = 1; - parse_repeat(i, repeat_min, repeat_max); + parse_repeat(expr, i, repeat_min, repeat_max); for(unsigned j=0; j::max(); @@ -257,7 +281,7 @@ bool Regex::parse_repeat(string::const_iterator &i, Count &rmin, Count &rmax) else rmax = rmin; if(*i!='}') - throw InvalidParameterValue("Invalid bound"); + throw bad_regex("invalid bound", expr, begin); } ++i; @@ -267,6 +291,7 @@ bool Regex::parse_repeat(string::const_iterator &i, Count &rmin, Count &rmax) Regex::Code Regex::parse_brackets(const string &str, string::const_iterator &iter) { + string::const_iterator begin = iter; Code result; ++iter; @@ -280,7 +305,7 @@ Regex::Code Regex::parse_brackets(const string &str, string::const_iterator &ite string::const_iterator end = iter; for(; (end!=str.end() && (end==iter || *end!=']')); ++end) ; if(end==str.end()) - throw InvalidParameterValue("Unmatched '['"); + throw bad_regex("unmatched '['", str, begin); unsigned char mask[32] = {0}; unsigned type = 0; @@ -451,7 +476,7 @@ bool Regex::run(const string &str, const string::const_iterator &begin, RegMatch input_consumed = true; } else - throw Exception("Invalid instruction"); + throw logic_error("invalid instruction in regex bytecode"); if(match_result==negate_match) terminate = true; diff --git a/source/strings/regex.h b/source/strings/regex.h index 5b809ab..6792502 100644 --- a/source/strings/regex.h +++ b/source/strings/regex.h @@ -1,11 +1,23 @@ #ifndef MSP_STRINGS_REGEX_H_ #define MSP_STRINGS_REGEX_H_ +#include #include #include "regmatch.h" namespace Msp { +class bad_regex: public std::logic_error +{ +public: + bad_regex(const std::string &, const std::string &, const std::string::const_iterator &); + virtual ~bad_regex() throw() { } + +private: + std::string make_where(const std::string &, const std::string::const_iterator &); +}; + + /** This class provides regular expression matching. It supports a subset of POSIX.2 extended regex syntax. Character classes, equivalence classes and @@ -108,7 +120,7 @@ private: Code parse_atom(const std::string &, std::string::const_iterator &i, unsigned &); Code parse_brackets(const std::string &, std::string::const_iterator &); - bool parse_repeat(std::string::const_iterator &, Count &, Count &); + bool parse_repeat(const std::string &, std::string::const_iterator &, Count &, Count &); public: /** Matches the regex against a string. Refer to RegMatch documentation for diff --git a/source/strings/regmatch.cpp b/source/strings/regmatch.cpp index 61bed84..4799cfb 100644 --- a/source/strings/regmatch.cpp +++ b/source/strings/regmatch.cpp @@ -1,4 +1,4 @@ -#include +#include #include "regmatch.h" using namespace std; @@ -19,7 +19,7 @@ RegMatch::RegMatch(const string &str, const GroupArray &g): const RegMatch::Group &RegMatch::group(unsigned i) const { if(i>=groups.size()) - throw InvalidParameterValue("Group index out of range"); + throw out_of_range("RegMatch::group"); return groups[i]; } -- 2.43.0 From 62a984b46e08740d19cb055f01be3365982f6b9d Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 11:38:40 +0300 Subject: [PATCH 02/16] Make Time::sleep void Check return value of nanosleep internally and throw if necessary --- source/time/utils.cpp | 9 ++++++--- source/time/utils.h | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/source/time/utils.cpp b/source/time/utils.cpp index 123b2d9..7da0aed 100644 --- a/source/time/utils.cpp +++ b/source/time/utils.cpp @@ -3,7 +3,9 @@ #else #include #include +#include #endif +#include #include "datetime.h" #include "timedelta.h" #include "timestamp.h" @@ -71,14 +73,15 @@ TimeDelta get_cpu_time() /** Sleeps for the given time. */ -int sleep(const TimeDelta &d) +void sleep(const TimeDelta &d) { #ifndef WIN32 timespec ts = d; - return nanosleep(&ts, 0); + while(nanosleep(&ts, 0)==-1) + if(errno!=EINTR) + throw system_error("nanosleep"); #else Sleep((DWORD)(d/msec)); - return 0; #endif } diff --git a/source/time/utils.h b/source/time/utils.h index 2916559..0a2b351 100644 --- a/source/time/utils.h +++ b/source/time/utils.h @@ -12,7 +12,7 @@ class TimeStamp; extern TimeStamp now(); extern std::string format_now(const std::string &); extern TimeDelta get_cpu_time(); -extern int sleep(const TimeDelta &); +extern void sleep(const TimeDelta &); } // namespace Time } // namespace Msp -- 2.43.0 From 1f0843257065789231a9949e0a81b79afd7bbebe Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 11:43:22 +0300 Subject: [PATCH 03/16] Style and comment updates --- source/core/application.h | 7 +++-- source/core/getopt.h | 10 ++++--- source/core/main.cpp | 1 - source/core/mutex.h | 15 +++++----- source/core/thread.cpp | 7 ----- source/core/thread.h | 5 ++++ source/stringcodec/codec.h | 6 ++-- source/stringcodec/jisx0208.h | 4 +-- source/strings/format.cpp | 13 --------- source/strings/format.h | 9 ++++++ source/strings/regex.cpp | 6 ++-- source/time/datetime.cpp | 12 ++++---- source/time/datetime.h | 16 +++++------ source/time/timedelta.h | 54 ++++++++++++++++------------------- source/time/timer.h | 22 +++++--------- source/time/timestamp.h | 42 ++++++++++++--------------- source/time/timezone.cpp | 2 +- source/time/utils.cpp | 9 ------ source/time/utils.h | 14 ++++++--- 19 files changed, 114 insertions(+), 140 deletions(-) diff --git a/source/core/application.h b/source/core/application.h index c7a1af1..08393b7 100644 --- a/source/core/application.h +++ b/source/core/application.h @@ -4,8 +4,7 @@ namespace Msp { /** -Base class for applications. Inherit the main class from this and add a static -member of type RegApp. +Base class for applications. See also RegisteredApplication. */ class Application { @@ -49,6 +48,10 @@ private: }; +/** +Registers the class to be used for program startup. The main application class +should be derived from this. +*/ template class RegisteredApplication: public Application { diff --git a/source/core/getopt.h b/source/core/getopt.h index bfa2ef2..56ab051 100644 --- a/source/core/getopt.h +++ b/source/core/getopt.h @@ -65,6 +65,9 @@ private: template class Option: public OptBase { + private: + T &data; + public: Option(char s, const std::string &l, T &d, ArgType a): OptBase(s, l, a), data(d) { } @@ -81,13 +84,14 @@ private: throw usage_error("Invalid argument for --"+lng+" ("+e.what()+")"); } } - private: - T &data; }; template class ListOption: public OptBase { + private: + T &data; + public: ListOption(char s, const std::string &l, T &d, ArgType a): OptBase(s, l, a), data(d) { if(arg_type!=REQUIRED_ARG) throw std::invalid_argument("ListOption arg_type!=REQUIRED"); } @@ -105,8 +109,6 @@ private: throw usage_error("Invalid argument for --"+lng+" ("+e.what()+")"); } } - private: - T &data; }; bool help; diff --git a/source/core/main.cpp b/source/core/main.cpp index 84e0f42..19791ee 100644 --- a/source/core/main.cpp +++ b/source/core/main.cpp @@ -1,7 +1,6 @@ #ifdef WIN32 #include #endif - #include "application.h" #ifdef WIN32 diff --git a/source/core/mutex.h b/source/core/mutex.h index 18f9039..0fe9e82 100644 --- a/source/core/mutex.h +++ b/source/core/mutex.h @@ -35,21 +35,19 @@ public: }; /** -Locks the mutex for te lifetime of the object. +Locks the mutex for the lifetime of the object. */ class MutexLock { private: Mutex &mutex; + MutexLock(const MutexLock &); public: MutexLock(Mutex &m, bool l = true): mutex(m) { if(l) mutex.lock(); } ~MutexLock() { mutex.unlock(); } void lock() { mutex.lock(); } -private: - MutexLock(const MutexLock &); - MutexLock &operator=(const MutexLock &); }; /** @@ -59,15 +57,16 @@ exists, the mutex will stay locked. template class MutexPtr { +private: + RefPtr mutex; + T *data; + public: MutexPtr(T *d, Mutex &m): mutex(new MutexLock(m)), data(d) { } T &operator*() const { return *data; } T *operator->() const { return data; } - void clear() { mutex=0; data = 0; } -private: - RefPtr mutex; - T *data; + void clear() { mutex = 0; data = 0; } }; } diff --git a/source/core/thread.cpp b/source/core/thread.cpp index a8c80b6..cfc0c37 100644 --- a/source/core/thread.cpp +++ b/source/core/thread.cpp @@ -43,10 +43,6 @@ Thread::~Thread() delete priv_; } -/** -Waits for the thread to exit. Calling this from the thread will cause a -deadlock. -*/ void Thread::join() { if(!launched_) @@ -60,9 +56,6 @@ void Thread::join() launched_ = false; } -/** -Violently terminates the thread. -*/ void Thread::kill() { #ifdef WIN32 diff --git a/source/core/thread.h b/source/core/thread.h index ac7169f..ae25707 100644 --- a/source/core/thread.h +++ b/source/core/thread.h @@ -26,7 +26,12 @@ private: public: virtual ~Thread(); + /** Waits for the thread to exit. Calling this from the thread will cause a + deadlock. */ void join(); + + /** Violently terminates the thread. This should only be used as a last + resort, as the thread gets no chance to clean up. */ void kill(); protected: void launch(); diff --git a/source/stringcodec/codec.h b/source/stringcodec/codec.h index c70e052..e0e0a96 100644 --- a/source/stringcodec/codec.h +++ b/source/stringcodec/codec.h @@ -177,7 +177,7 @@ public: /** Convenience function that decodes a string. */ -template +template ustring decode(const std::string &s) { typename C::Decoder dec; @@ -185,7 +185,7 @@ ustring decode(const std::string &s) } /** Convenience function that encodes a string. */ -template +template std::string encode(const ustring &s) { typename C::Encoder enc; @@ -193,7 +193,7 @@ std::string encode(const ustring &s) } /** Convenience function that transcodes a string from one codec to another. */ -template +template std::string transcode(const std::string &s) { return encode(decode(s)); diff --git a/source/stringcodec/jisx0208.h b/source/stringcodec/jisx0208.h index c59e44f..c8e6944 100644 --- a/source/stringcodec/jisx0208.h +++ b/source/stringcodec/jisx0208.h @@ -48,8 +48,8 @@ struct Kuten operator bool() { return ku!=0 && ten!=0; } }; -extern unichar jisx0208_to_ucs(Kuten); -extern Kuten ucs_to_jisx0208(unichar); +unichar jisx0208_to_ucs(Kuten); +Kuten ucs_to_jisx0208(unichar); } // namespace StringCodec } // namespace Msp diff --git a/source/strings/format.cpp b/source/strings/format.cpp index 4b5bcd0..1b8b465 100644 --- a/source/strings/format.cpp +++ b/source/strings/format.cpp @@ -11,10 +11,6 @@ Formatter::Formatter(const string &f): advance(); } -/** -Returns the result of the formatting operation. Will throw if not enough -values have been fed to the formatter. -*/ const string &Formatter::str() const { if(pos!=fmt.end()) @@ -23,11 +19,6 @@ const string &Formatter::str() const return result; } -/** -Advances the pos iterator to the next conversion, adding literal characters to -the result. The iterator is left at the second character of the conversion -(i.e. after the %). -*/ void Formatter::advance() { for(; pos!=fmt.end(); ++pos) @@ -45,10 +36,6 @@ void Formatter::advance() } } -/** -Reads the next conversion from the format string and returns a corresponding -Fmt object. -*/ Fmt Formatter::get_conversion() { if(pos==fmt.end()) diff --git a/source/strings/format.h b/source/strings/format.h index 9264b10..6d8f739 100644 --- a/source/strings/format.h +++ b/source/strings/format.h @@ -29,9 +29,18 @@ public: return *this; } + /** Returns the result of the formatting operation. Will throw if not + enough values have been fed to the formatter. */ const std::string &str() const; + private: + /** Advances the iterator to the next conversion, adding literal characters + to the result. The iterator is left at the second character of the + conversion (i.e. after the %). */ void advance(); + + /** Reads the next conversion from the format string and returns a + corresponding Fmt object. */ Fmt get_conversion(); }; diff --git a/source/strings/regex.cpp b/source/strings/regex.cpp index 5b04764..60b8ed1 100644 --- a/source/strings/regex.cpp +++ b/source/strings/regex.cpp @@ -13,16 +13,16 @@ template void write_int(T n, Msp::Regex::Code &code) { for(unsigned i=0; i>i*8)&0xFF; + code += (n>>(i*8))&0xFF; } -/** Reads an integer from a Regex code stream, in little-endian order. */ +/** Reads an integer from a Regex code string, in little-endian order. */ template T read_int(Msp::Regex::Code::const_iterator &c) { T result = 0; for(unsigned i=0; i +#include #include #include "rawtime.h" @@ -17,58 +17,52 @@ private: RawTime usec; public: - /** - Constructs a zero TimeDelta. - */ + /** Constructs a zero TimeDelta. */ TimeDelta(): usec(0) { } - /** - Constructs a TimeDelta from a plain number. The purpose of this is to allow - serialization together with the raw() function. For creating TimeDeltas - with a specific length, see units.h. - */ + /** Constructs a TimeDelta from a plain number. The purpose of this is to + allow serialization together with the raw() function. For creating + TimeDeltas with a specific length, see units.h. */ explicit TimeDelta(RawTime u): usec(u) { } - /** - Returns the raw number stored inside the TimeDelta. This should only be used - for serialization and the result should not be interpreted in any way. - */ + /** Returns the raw number stored inside the TimeDelta. This should only be used + for serialization and the result should not be interpreted in any way. */ RawTime raw() const { return usec; } - TimeDelta operator+(const TimeDelta &t) const { return TimeDelta(usec+t.usec); } - TimeDelta &operator+=(const TimeDelta &t) { usec+=t.usec; return *this; } - TimeDelta operator-(const TimeDelta &t) const { return TimeDelta(usec-t.usec); } - TimeDelta &operator-=(const TimeDelta &t) { usec-=t.usec; return *this; } + TimeDelta operator+(const TimeDelta &t) const { return TimeDelta(usec+t.usec); } + TimeDelta &operator+=(const TimeDelta &t) { usec += t.usec; return *this; } + TimeDelta operator-(const TimeDelta &t) const { return TimeDelta(usec-t.usec); } + TimeDelta &operator-=(const TimeDelta &t) { usec -= t.usec; return *this; } template - TimeDelta operator*(T a) const { return TimeDelta(RawTime(usec*a)); } + TimeDelta operator*(T a) const { return TimeDelta(RawTime(usec*a)); } template - TimeDelta &operator*=(T a) { usec=RawTime(usec*a); return *this; } + TimeDelta &operator*=(T a) { usec = RawTime(usec*a); return *this; } template - TimeDelta operator/(T a) const { return TimeDelta(RawTime(usec/a)); } + TimeDelta operator/(T a) const { return TimeDelta(RawTime(usec/a)); } template - TimeDelta &operator/=(T a) { usec=RawTime(usec/a); return *this; } + TimeDelta &operator/=(T a) { usec = RawTime(usec/a); return *this; } - double operator/(const TimeDelta &t) const { return double(usec)/t.usec; } + double operator/(const TimeDelta &t) const { return double(usec)/t.usec; } - bool operator>(const TimeDelta &t) const { return usec>t.usec; } - bool operator>=(const TimeDelta &t) const { return usec>=t.usec; } - bool operator<(const TimeDelta &t) const { return usec(const TimeDelta &t) const { return usec>t.usec; } + bool operator>=(const TimeDelta &t) const { return usec>=t.usec; } + bool operator<(const TimeDelta &t) const { return usec -inline TimeDelta operator*(T a, const TimeDelta &t) { return t*a; } +inline TimeDelta operator*(T a, const TimeDelta &t) { return t*a; } void operator<<(LexicalConverter &, const TimeDelta &); diff --git a/source/time/timer.h b/source/time/timer.h index b080f82..7566c3d 100644 --- a/source/time/timer.h +++ b/source/time/timer.h @@ -53,30 +53,22 @@ private: public: ~Timer(); - /** - Adds a timer that will be executed periodically as long as the timeout - signal hander returns true. - */ + /** Adds a timer that will be executed periodically as long as the timeout + signal hander returns true. */ Slot &add(const TimeDelta &); - /** - Adds a timer that will be executed once at a specific time. The return - value of the timeout signal handler is ignored. - */ + /** Adds a timer that will be executed once at a specific time. The return + value of the timeout signal handler is ignored. */ Slot &add(const TimeStamp &); - /** - Cancels a previously added timer. - */ + /** Cancels a previously added timer. */ void cancel(Slot &); - /** - Checks all timers, executing any that have timed out. If block is true, + /** Checks all timers, executing any that have timed out. If block is true, waits until one times out. 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. - */ + won't return until a timer is added from another thread. */ void tick(bool block = true); TimeStamp get_next_timeout() const; diff --git a/source/time/timestamp.h b/source/time/timestamp.h index cb38279..41fc1e5 100644 --- a/source/time/timestamp.h +++ b/source/time/timestamp.h @@ -19,40 +19,34 @@ private: RawTime usec; public: - /** - Construct a TimeStamp that represents an arbitarily distant point in the - past. It's guaranteed to be less than any valid timestamp. - */ + /** Construct a TimeStamp that represents an arbitarily distant point in the + past. It's guaranteed to be less than any valid timestamp. */ TimeStamp(): usec(0) { } - /** - Constructs a TimeStamp from a plain number. The purpose of this is to allow - serialization together with the raw() function. - */ + /** Constructs a TimeStamp from a plain number. The purpose of this is to allow + serialization together with the raw() function. */ explicit TimeStamp(RawTime u): usec(u) { } - /** - Returns the raw number stored inside the TimeStamp. This value should be - considered opaque and only be used for serialization. - */ + /** Returns the raw number stored inside the TimeStamp. This value should be + considered opaque and only be used for serialization. */ RawTime raw() const { return usec; } time_t to_unixtime() const { return usec/1000000LL; } - TimeStamp operator+(const TimeDelta &t) const { return TimeStamp(usec+t.raw()); } - TimeStamp &operator+=(const TimeDelta &t) { usec+=t.raw(); return *this; } - TimeStamp operator-(const TimeDelta &t) const { return TimeStamp(usec-t.raw()); } - TimeStamp &operator-=(const TimeDelta &t) { usec-=t.raw(); return *this; } - TimeDelta operator-(const TimeStamp &t) const { return TimeDelta(usec-t.usec); } + TimeStamp operator+(const TimeDelta &t) const { return TimeStamp(usec+t.raw()); } + TimeStamp &operator+=(const TimeDelta &t) { usec += t.raw(); return *this; } + TimeStamp operator-(const TimeDelta &t) const { return TimeStamp(usec-t.raw()); } + TimeStamp &operator-=(const TimeDelta &t) { usec -= t.raw(); return *this; } + TimeDelta operator-(const TimeStamp &t) const { return TimeDelta(usec-t.usec); } - bool operator>=(const TimeStamp &t) const { return usec>=t.usec; } - bool operator>(const TimeStamp &t) const { return usec>t.usec; } - bool operator<=(const TimeStamp &t) const { return usec<=t.usec; } - bool operator<(const TimeStamp &t) const { return usec=(const TimeStamp &t) const { return usec>=t.usec; } + bool operator>(const TimeStamp &t) const { return usec>t.usec; } + bool operator<=(const TimeStamp &t) const { return usec<=t.usec; } + bool operator<(const TimeStamp &t) const { return usec0 ? this : 0; } + operator const void *() const { return usec>0 ? this : 0; } #ifndef WIN32 operator timeval() const { return rawtime_to_timeval(usec); } diff --git a/source/time/timezone.cpp b/source/time/timezone.cpp index 56fcf8f..873829d 100644 --- a/source/time/timezone.cpp +++ b/source/time/timezone.cpp @@ -4,8 +4,8 @@ #else #include #endif -#include #include +#include #include "timestamp.h" #include "timezone.h" #include "units.h" diff --git a/source/time/utils.cpp b/source/time/utils.cpp index 7da0aed..d69febc 100644 --- a/source/time/utils.cpp +++ b/source/time/utils.cpp @@ -17,9 +17,6 @@ using namespace std; namespace Msp { namespace Time { -/** -Returns the current timestamp. -*/ TimeStamp now() { #ifndef WIN32 @@ -55,9 +52,6 @@ string format_now(const string &fmt) return DateTime(now()).format(fmt); } -/** -Returns the CPU time used by the program so far. -*/ TimeDelta get_cpu_time() { #ifndef WIN32 @@ -70,9 +64,6 @@ TimeDelta get_cpu_time() #endif } -/** -Sleeps for the given time. -*/ void sleep(const TimeDelta &d) { #ifndef WIN32 diff --git a/source/time/utils.h b/source/time/utils.h index 0a2b351..00b6ef8 100644 --- a/source/time/utils.h +++ b/source/time/utils.h @@ -9,10 +9,16 @@ namespace Time { class TimeDelta; class TimeStamp; -extern TimeStamp now(); -extern std::string format_now(const std::string &); -extern TimeDelta get_cpu_time(); -extern void sleep(const TimeDelta &); +/** Returns the current timestamp. */ +TimeStamp now(); + +std::string format_now(const std::string &); + +/** Returns the CPU time used by the program so far. */ +TimeDelta get_cpu_time(); + +/** Sleeps for the given duration. */ +void sleep(const TimeDelta &); } // namespace Time } // namespace Msp -- 2.43.0 From 73a21b6f495e16707ede460a2c9d8f1474bb4d93 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 13:21:27 +0300 Subject: [PATCH 04/16] Style update: spaces around assignments --- source/base.cpp | 6 ++-- source/buffered.cpp | 46 +++++++++++++------------- source/console.cpp | 38 ++++++++++----------- source/eventdispatcher.cpp | 12 +++---- source/file.cpp | 68 +++++++++++++++++++------------------- source/file.h | 8 ++--- source/filtered.h | 6 ++-- source/memory.cpp | 38 ++++++++++----------- source/mode.h | 12 +++---- source/pipe.cpp | 56 +++++++++++++++---------------- source/poll.cpp | 54 +++++++++++++++--------------- source/poll.h | 10 +++--- source/utils.cpp | 4 +-- 13 files changed, 179 insertions(+), 179 deletions(-) diff --git a/source/base.cpp b/source/base.cpp index 4556b73..3c9923d 100644 --- a/source/base.cpp +++ b/source/base.cpp @@ -21,10 +21,10 @@ bool Base::getline(string &line) while(1) { - int c=get(); + int c = get(); if(c==-1 || c=='\n') break; - line+=c; + line += c; } return !eof_flag || !line.empty(); @@ -59,7 +59,7 @@ Base::Base(): void Base::set_events(PollEvent e) { - events=e; + events = e; signal_events_changed.emit(events); } diff --git a/source/buffered.cpp b/source/buffered.cpp index 32688db..b8a2dbe 100644 --- a/source/buffered.cpp +++ b/source/buffered.cpp @@ -22,7 +22,7 @@ Buffered::Buffered(Base &b, unsigned s): end(buf), cur_op(M_NONE) { - mode=below.get_mode(); + mode = below.get_mode(); below.signal_flush_required.connect(sigc::mem_fun(this, &Buffered::flush)); } @@ -32,7 +32,7 @@ unsigned Buffered::put(char c) if(end(end-begin), size); + len = min(static_cast(end-begin), size); memcpy(data, begin, len); - begin+=len; - ret+=len; + begin += len; + ret += len; } else // Read the rest directly from the underlying object - ret+=below.read(data, size); + ret += below.read(data, size); - eof_flag=(below.eof() && begin==end); + eof_flag = (below.eof() && begin==end); return ret; } diff --git a/source/console.cpp b/source/console.cpp index f606a09..e860436 100644 --- a/source/console.cpp +++ b/source/console.cpp @@ -30,17 +30,17 @@ Console::Console(unsigned n) if(n>2) throw InvalidParameterValue("Invalid parameter for Console::Console"); - mode=(n==0 ? M_READ : M_WRITE); + mode = (n==0 ? M_READ : M_WRITE); #ifdef WIN32 switch(n) { - case 0: handle=GetStdHandle(STD_INPUT_HANDLE); break; - case 1: handle=GetStdHandle(STD_OUTPUT_HANDLE); break; - case 2: handle=GetStdHandle(STD_ERROR_HANDLE); break; + case 0: handle = GetStdHandle(STD_INPUT_HANDLE); break; + case 1: handle = GetStdHandle(STD_OUTPUT_HANDLE); break; + case 2: handle = GetStdHandle(STD_ERROR_HANDLE); break; } #else - handle=n; + handle = n; if(handle==0) tcgetattr(handle, &orig_attr); @@ -64,8 +64,8 @@ void Console::set_block(bool b) // XXX Dunno how to do this in win32 (void)b; #else - int flags=fcntl(0, F_GETFL); - flags=(flags&~O_NONBLOCK) | (b?0:O_NONBLOCK); + int flags = fcntl(0, F_GETFL); + flags = (flags&~O_NONBLOCK) | (b?0:O_NONBLOCK); fcntl(0, F_SETFL, flags); #endif } @@ -82,7 +82,7 @@ void Console::set_local_echo(bool e) #else termios t; tcgetattr(0, &t); - t.c_lflag=(t.c_lflag&~ECHO) | (e?ECHO:0); + t.c_lflag = (t.c_lflag&~ECHO) | (e?ECHO:0); tcsetattr(0, TCSADRAIN, &t); #endif } @@ -100,7 +100,7 @@ void Console::set_line_buffer(bool l) // XXX ICANON does more than just set line buffering, may need a bit more thought termios t; tcgetattr(0, &t); - t.c_lflag=(t.c_lflag&~ICANON) | (l?ICANON:0); + t.c_lflag = (t.c_lflag&~ICANON) | (l?ICANON:0); tcsetattr(0, TCSADRAIN, &t); #endif } @@ -112,13 +112,13 @@ void Console::get_size(unsigned &rows, unsigned &cols) #ifdef WIN32 // XXX Figure out how to do this - rows=24; - cols=80; + rows = 24; + cols = 80; #else struct winsize wsz; ioctl(handle, TIOCGWINSZ, &wsz); - rows=wsz.ws_row; - cols=wsz.ws_col; + rows = wsz.ws_row; + cols = wsz.ws_col; #endif } @@ -137,7 +137,7 @@ unsigned Console::do_write(const char *buf, unsigned len) if(!WriteFile(handle, buf, len, &ret, 0)) throw SystemError("Writing to console failed", GetLastError()); #else - int ret=::write(handle, buf, len); + int ret = ::write(handle, buf, len); if(ret==-1) throw SystemError("Writing to console failed", errno); #endif @@ -155,7 +155,7 @@ unsigned Console::do_read(char *buf, unsigned len) if(!ReadFile(handle, buf, len, &ret, 0)) throw SystemError("Reading from console failed", GetLastError()); #else - int ret=::read(handle, buf, len); + int ret = ::read(handle, buf, len); if(ret==-1) { if(errno==EAGAIN) @@ -164,7 +164,7 @@ unsigned Console::do_read(char *buf, unsigned len) throw SystemError("Reading from console failed", errno); } else if(ret==0) - eof_flag=true; + eof_flag = true; #endif return ret; @@ -186,9 +186,9 @@ Console &Console::instance(unsigned n) throw InvalidParameterValue("Unknown Console instance requested"); } -Console &cin=Console::instance(0); -Console &cout=Console::instance(1); -Console &cerr=Console::instance(2); +Console &cin = Console::instance(0); +Console &cout = Console::instance(1); +Console &cerr = Console::instance(2); } // namespace IO } // namespace Msp diff --git a/source/eventdispatcher.cpp b/source/eventdispatcher.cpp index d7e367c..02330ec 100644 --- a/source/eventdispatcher.cpp +++ b/source/eventdispatcher.cpp @@ -17,12 +17,12 @@ EventDispatcher::EventDispatcher() void EventDispatcher::add(Base &obj) { - SlotMap::iterator i=objects.find(&obj); + SlotMap::iterator i = objects.find(&obj); if(i==objects.end()) { - i=objects.insert(SlotMap::value_type(&obj, Slot(&obj))).first; - i->second.evch_conn=obj.signal_events_changed.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_events_changed), &obj)); - i->second.del_conn=obj.signal_deleted.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_deleted), &obj)); + i = objects.insert(SlotMap::value_type(&obj, Slot(&obj))).first; + i->second.evch_conn = obj.signal_events_changed.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_events_changed), &obj)); + i->second.del_conn = obj.signal_deleted.connect(sigc::bind(sigc::mem_fun(this, &EventDispatcher::object_deleted), &obj)); if(obj.get_events()) poller.set_object(obj, obj.get_events()); @@ -31,7 +31,7 @@ void EventDispatcher::add(Base &obj) void EventDispatcher::remove(Base &obj) { - SlotMap::iterator i=objects.find(&obj); + SlotMap::iterator i = objects.find(&obj); if(i!=objects.end()) { i->second.evch_conn.disconnect(); @@ -72,7 +72,7 @@ void EventDispatcher::object_deleted(Base *obj) void EventDispatcher::dispatch() { - const Poller::SlotSeq &result=poller.get_result(); + const Poller::SlotSeq &result = poller.get_result(); for(Poller::SlotSeq::const_iterator i=result.begin(); i!=result.end(); ++i) i->object->event(i->events); } diff --git a/source/file.cpp b/source/file.cpp index 6ef3388..0b153cf 100644 --- a/source/file.cpp +++ b/source/file.cpp @@ -34,62 +34,62 @@ File::File(const string &fn, Mode m, CreateMode cm) if(cm&~(C_CREATE|C_TRUNCATE)) throw InvalidParameterValue("Invalid create mode"); - mode=m; + mode = m; #ifdef WIN32 - int flags=0; - int create_flags=OPEN_EXISTING; + int flags = 0; + int create_flags = OPEN_EXISTING; if(mode&M_READ) - flags|=GENERIC_READ; + flags |= GENERIC_READ; else if(mode&M_WRITE) { - flags|=GENERIC_WRITE; + flags |= GENERIC_WRITE; switch(static_cast(cm)) { - case C_NONE: create_flags=OPEN_EXISTING; break; - case C_CREATE: create_flags=OPEN_ALWAYS; break; - case C_TRUNCATE: create_flags=TRUNCATE_EXISTING; break; - case C_CREATE+C_TRUNCATE: create_flags=CREATE_ALWAYS; break; + case C_NONE: create_flags = OPEN_EXISTING; break; + case C_CREATE: create_flags = OPEN_ALWAYS; break; + case C_TRUNCATE: create_flags = TRUNCATE_EXISTING; break; + case C_CREATE+C_TRUNCATE: create_flags = CREATE_ALWAYS; break; } } - handle=CreateFile(fn.c_str(), flags, 0, 0, create_flags, FILE_ATTRIBUTE_NORMAL, 0); + handle = CreateFile(fn.c_str(), flags, 0, 0, create_flags, FILE_ATTRIBUTE_NORMAL, 0); if(handle==INVALID_HANDLE_VALUE) { - int err=GetLastError(); + int err = GetLastError(); if(err==ERROR_FILE_NOT_FOUND) throw FileNotFound("Can't find file "+fn, fn); else throw SystemError(format("Can't open file '%s'", fn), GetLastError()); } #else - int flags=0; + int flags = 0; switch(mode&M_RDWR) { - case M_READ: flags|=O_RDONLY; break; - case M_WRITE: flags|=O_WRONLY; break; - case M_RDWR: flags|=O_RDWR; break; + case M_READ: flags |= O_RDONLY; break; + case M_WRITE: flags |= O_WRONLY; break; + case M_RDWR: flags |= O_RDWR; break; default:; } if(mode&M_WRITE) { if(cm&C_CREATE) - flags|=O_CREAT; + flags |= O_CREAT; if(cm&C_TRUNCATE) - flags|=O_TRUNC; + flags |= O_TRUNC; } if(mode&M_APPEND) - flags|=O_APPEND; + flags |= O_APPEND; if(mode&M_NONBLOCK) - flags|=O_NONBLOCK; + flags |= O_NONBLOCK; - handle=::open(fn.c_str(), flags, 0666); + handle = ::open(fn.c_str(), flags, 0666); if(handle==-1) { - int err=errno; + int err = errno; if(err==ENOENT) throw FileNotFound("Can't find file "+fn, fn); else @@ -119,7 +119,7 @@ void File::close() ::close(handle); #endif - handle=MSP_IO_INVALID_HANDLE; + handle = MSP_IO_INVALID_HANDLE; signal_closed.emit(); } @@ -131,11 +131,11 @@ void File::set_block(bool b) { check_access(M_NONE); - mode=(mode&~M_NONBLOCK); + mode = (mode&~M_NONBLOCK); if(b) - mode=(mode|M_NONBLOCK); + mode = (mode|M_NONBLOCK); #ifndef WIN32 - int flags=fcntl(handle, F_GETFD); + int flags = fcntl(handle, F_GETFD); fcntl(handle, F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); #endif } @@ -163,18 +163,18 @@ int File::seek(int off, SeekType st) signal_flush_required.emit(); - int type=sys_seek_type(st); + int type = sys_seek_type(st); #ifdef WIN32 - DWORD ret=SetFilePointer(handle, off, 0, type); + DWORD ret = SetFilePointer(handle, off, 0, type); if(ret==INVALID_SET_FILE_POINTER) throw SystemError("Seek failed", GetLastError()); #else - int ret=lseek(handle, off, type); + int ret = lseek(handle, off, type); if(ret==-1) throw SystemError("Seek failed", errno); #endif - eof_flag=false; + eof_flag = false; return ret; } @@ -187,11 +187,11 @@ int File::tell() const check_access(M_NONE); #ifdef WIN32 - DWORD ret=SetFilePointer(handle, 0, 0, FILE_CURRENT); + DWORD ret = SetFilePointer(handle, 0, 0, FILE_CURRENT); if(ret==INVALID_SET_FILE_POINTER) throw SystemError("Tell failed", GetLastError()); #else - int ret=lseek(handle, 0, SEEK_CUR); + int ret = lseek(handle, 0, SEEK_CUR); if(ret==-1) throw SystemError("Tell failed", errno); #endif @@ -236,7 +236,7 @@ unsigned File::do_write(const char *buf, unsigned size) if(WriteFile(handle, buf, size, &ret, 0)==0) throw SystemError("Writing to file failed", GetLastError()); #else - int ret=::write(handle, buf, size); + int ret = ::write(handle, buf, size); if(ret==-1) { if(errno==EAGAIN) @@ -269,7 +269,7 @@ unsigned File::do_read(char *buf, unsigned size) if(ReadFile(handle, buf, size, &ret, 0)==0) throw SystemError("Reading from file failed", GetLastError()); #else - int ret=::read(handle, buf, size); + int ret = ::read(handle, buf, size); if(ret==-1) { if(errno==EAGAIN) @@ -281,7 +281,7 @@ unsigned File::do_read(char *buf, unsigned size) if(ret==0) { - eof_flag=true; + eof_flag = true; signal_end_of_file.emit(); } diff --git a/source/file.h b/source/file.h index 4e86e29..16f2dcb 100644 --- a/source/file.h +++ b/source/file.h @@ -26,12 +26,12 @@ class File: public Base public: enum CreateMode { - C_NONE=0, - C_CREATE=1, - C_TRUNCATE=2 + C_NONE = 0, + C_CREATE = 1, + C_TRUNCATE = 2 }; - File(const std::string &, Mode=M_READ, CreateMode =CreateMode(C_CREATE+C_TRUNCATE)); + File(const std::string &, Mode = M_READ, CreateMode =CreateMode(C_CREATE+C_TRUNCATE)); void close(); diff --git a/source/filtered.h b/source/filtered.h index e3ff219..ff8577a 100644 --- a/source/filtered.h +++ b/source/filtered.h @@ -19,8 +19,8 @@ private: { Filtered &f; - Activator(Filtered &f_): f(f_) { f.active=true; } - ~Activator() { f.active=false; } + Activator(Filtered &f_): f(f_) { f.active = true; } + ~Activator() { f.active = false; } }; F filter; @@ -28,7 +28,7 @@ private: public: Filtered(): filter(*this), active(false) { } - ~Filtered() { active=true; } + ~Filtered() { active = true; } template Filtered(A0 a0): B(a0), filter(*this), active(false) { } diff --git a/source/memory.cpp b/source/memory.cpp index c44554a..80dde27 100644 --- a/source/memory.cpp +++ b/source/memory.cpp @@ -27,7 +27,7 @@ Memory::Memory(char *b, char *e) Memory::Memory(const char *cd, unsigned s) { - char *d=const_cast(cd); + char *d = const_cast(cd); init(d, d+s, M_READ); } @@ -38,25 +38,25 @@ Memory::Memory(const char *b, const char *e) void Memory::init(char *b, char *e, Mode m) { - begin=b; - end=e; - pos=begin; - mode=m; + begin = b; + end = e; + pos = begin; + mode = m; } unsigned Memory::put(char c) { check_mode(M_WRITE); - *pos++=c; + *pos++ = c; return 1; } bool Memory::getline(string &line) { - char *nl=find(pos, end, '\n'); + char *nl = find(pos, end, '\n'); line.assign(pos, nl); - bool result=(nl!=pos); - pos=nl; + bool result = (nl!=pos); + pos = nl; return result; } @@ -64,7 +64,7 @@ int Memory::get() { if(pos==end) { - eof_flag=true; + eof_flag = true; return -1; } @@ -75,18 +75,18 @@ unsigned Memory::seek(int off, SeekType type) { char *new_pos; if(type==S_BEG) - new_pos=begin+off; + new_pos = begin+off; else if(type==S_CUR) - new_pos=pos+off; + new_pos = pos+off; else if(type==S_END) - new_pos=end+off; + new_pos = end+off; else throw InvalidParameterValue("Invalid seek type"); if(new_posend) throw InvalidParameterValue("Invalid seek offset"); - pos=new_pos; + pos = new_pos; return pos-begin; } @@ -99,9 +99,9 @@ unsigned Memory::do_write(const char *buf, unsigned size) { check_mode(M_WRITE); - size=min(size, end-pos); + size = min(size, end-pos); memcpy(pos, buf, size); - pos+=size; + pos += size; return size; } @@ -109,13 +109,13 @@ unsigned Memory::do_read(char *buf, unsigned size) { if(pos==end) { - eof_flag=true; + eof_flag = true; return 0; } - size=min(size, end-pos); + size = min(size, end-pos); memcpy(buf, pos, size); - pos+=size; + pos += size; return size; } diff --git a/source/mode.h b/source/mode.h index c58ecb0..d807e5f 100644 --- a/source/mode.h +++ b/source/mode.h @@ -12,12 +12,12 @@ namespace IO { enum Mode { - M_NONE=0, - M_READ=1, - M_WRITE=2, - M_RDWR=M_READ|M_WRITE, - M_APPEND=4, - M_NONBLOCK=8 + M_NONE = 0, + M_READ = 1, + M_WRITE = 2, + M_RDWR = M_READ|M_WRITE, + M_APPEND = 4, + M_NONBLOCK = 8 }; inline Mode operator|(Mode m, Mode n) diff --git a/source/pipe.cpp b/source/pipe.cpp index 696abe5..bd90527 100644 --- a/source/pipe.cpp +++ b/source/pipe.cpp @@ -20,25 +20,25 @@ namespace IO { Pipe::Pipe() { #ifdef WIN32 - string name=format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this); - handle[0]=CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0); + string name = format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this); + handle[0] = CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0); if(handle[0]==INVALID_HANDLE_VALUE) throw SystemError("Unable to create pipe", GetLastError()); - handle[1]=CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); + handle[1] = CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if(handle[1]==INVALID_HANDLE_VALUE) { - unsigned err=GetLastError(); + unsigned err = GetLastError(); CloseHandle(handle[0]); throw SystemError("Unable to create pipe", err); } - overlapped=0; - event=CreateEvent(0, true, false, 0); - buf_size=1024; - buffer=new char[buf_size]; - buf_avail=0; - buf_next=buffer; + overlapped = 0; + event = CreateEvent(0, true, false, 0); + buf_size = 1024; + buffer = new char[buf_size]; + buf_avail = 0; + buf_next = buffer; #else if(pipe(handle)==-1) throw SystemError("Unable to create pipe", errno); @@ -49,14 +49,14 @@ Pipe::Pipe() void Pipe::set_block(bool b) { - mode=(mode&~M_NONBLOCK); + mode = (mode&~M_NONBLOCK); if(b) - mode=(mode|M_NONBLOCK); + mode = (mode|M_NONBLOCK); #ifndef WIN32 - int flags=fcntl(handle[0], F_GETFD); + int flags = fcntl(handle[0], F_GETFD); fcntl(handle[0], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); - flags=fcntl(handle[1], F_GETFD); + flags = fcntl(handle[1], F_GETFD); fcntl(handle[1], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); #endif } @@ -81,23 +81,23 @@ Handle Pipe::get_event_handle() #ifdef WIN32 if(!overlapped && !buf_avail) { - overlapped=new OVERLAPPED; + overlapped = new OVERLAPPED; memset(overlapped, 0, sizeof(OVERLAPPED)); - overlapped->hEvent=event; + overlapped->hEvent = event; DWORD ret; - buf_next=buffer; + buf_next = buffer; if(!ReadFile(handle[0], buffer, buf_size, &ret, overlapped)) { - unsigned err=GetLastError(); + unsigned err = GetLastError(); if(err!=ERROR_IO_PENDING) throw SystemError("Failed to start an overlapped read", err); } else { - buf_avail=ret; + buf_avail = ret; delete overlapped; - overlapped=0; + overlapped = 0; SetEvent(event); } } @@ -123,7 +123,7 @@ unsigned Pipe::do_write(const char *buf, unsigned size) if(!WriteFile(handle[1], buf, size, &ret, 0)) throw SystemError("Writing to pipe failed", GetLastError()); #else - int ret=::write(handle[1], buf, size); + int ret = ::write(handle[1], buf, size); if(ret==-1) { if(errno==EAGAIN) @@ -152,21 +152,21 @@ unsigned Pipe::do_read(char *buf, unsigned size) throw SystemError("Reading from pipe failed", GetLastError()); else { - buf_avail+=ret; + buf_avail += ret; delete overlapped; - overlapped=0; + overlapped = 0; } } - unsigned ret=min(buf_avail, size); + unsigned ret = min(buf_avail, size); memcpy(buf, buf_next, ret); - buf_next+=ret; - buf_avail-=ret; + buf_next += ret; + buf_avail -= ret; // Initiate another overlapped read in case someone is polling us get_event_handle(); #else - int ret=::read(handle[0], buf, size); + int ret = ::read(handle[0], buf, size); if(ret==-1) { if(errno==EAGAIN) @@ -178,7 +178,7 @@ unsigned Pipe::do_read(char *buf, unsigned size) if(ret==0) { - eof_flag=true; + eof_flag = true; signal_end_of_file.emit(); } diff --git a/source/poll.cpp b/source/poll.cpp index 659e238..49e4887 100644 --- a/source/poll.cpp +++ b/source/poll.cpp @@ -18,18 +18,18 @@ using namespace Msp::IO; inline int sys_poll_event(PollEvent event) { - int result=0; + int result = 0; if(event&~(P_INPUT|P_PRIO|P_OUTPUT)) throw InvalidParameterValue("Invalid poll events"); #ifndef WIN32 if(event&P_INPUT) - result|=POLLIN; + result |= POLLIN; if(event&P_PRIO) - result|=POLLPRI; + result |= POLLPRI; if(event&P_OUTPUT) - result|=POLLOUT; + result |= POLLOUT; #endif return result; @@ -37,20 +37,20 @@ inline int sys_poll_event(PollEvent event) inline PollEvent poll_event_from_sys(int event) { - PollEvent result=P_NONE; + PollEvent result = P_NONE; #ifdef WIN32 // Stop the compiler from complaining about unused parameter - event=event; + event = event; #else if(event&POLLIN) - result=result|P_INPUT; + result = result|P_INPUT; if(event&POLLPRI) - result=result|P_PRIO; + result = result|P_PRIO; if(event&POLLOUT) - result=result|P_OUTPUT; + result = result|P_OUTPUT; if(event&POLLERR) - result=result|P_ERROR; + result = result|P_ERROR; #endif return result; @@ -60,9 +60,9 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) { #ifdef WIN32 if(timeout<0) - timeout=INFINITE; + timeout = INFINITE; - DWORD ret=WaitForSingleObject(obj.get_event_handle(), timeout); + DWORD ret = WaitForSingleObject(obj.get_event_handle(), timeout); if(ret==WAIT_OBJECT_0) return pe; else if(ret==WAIT_FAILED) @@ -70,9 +70,9 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) return P_NONE; #else - pollfd pfd={obj.get_event_handle(), sys_poll_event(pe), 0}; + pollfd pfd = {obj.get_event_handle(), sys_poll_event(pe), 0}; - int ret=::poll(&pfd, 1, timeout); + int ret = ::poll(&pfd, 1, timeout); if(ret==-1) { if(errno==EINTR) @@ -100,15 +100,15 @@ void Poller::set_object(Base &obj, PollEvent ev) if(ev) obj.get_event_handle(); - SlotMap::iterator i=objects.find(&obj); + SlotMap::iterator i = objects.find(&obj); if(i!=objects.end()) { if(ev) - i->second.events=ev; + i->second.events = ev; else objects.erase(i); - pfd_dirty=true; + pfd_dirty = true; } else if(ev) { @@ -118,7 +118,7 @@ void Poller::set_object(Base &obj, PollEvent ev) #endif objects.insert(SlotMap::value_type(&obj, Slot(&obj, ev))); - pfd_dirty=true; + pfd_dirty = true; } } @@ -143,14 +143,14 @@ void Poller::rebuild_pfd() for(SlotMap::iterator i=objects.begin(); i!=objects.end(); ++i) { - p.fd=i->second.object->get_event_handle(); + p.fd = i->second.object->get_event_handle(); #ifndef WIN32 - p.events=sys_poll_event(i->second.events); + p.events = sys_poll_event(i->second.events); #endif pfd.push_back(p); } - pfd_dirty=false; + pfd_dirty = false; } int Poller::do_poll(int timeout) @@ -162,12 +162,12 @@ int Poller::do_poll(int timeout) #ifdef WIN32 if(timeout<0) - timeout=INFINITE; + timeout = INFINITE; - DWORD ret=WaitForMultipleObjects(pfd.size(), &pfd.front().fd, false, timeout); + DWORD ret = WaitForMultipleObjects(pfd.size(), &pfd.front().fd, false, timeout); if(/*ret>=WAIT_OBJECT_0 &&*/ retsecond.object, i->second.events)); @@ -178,7 +178,7 @@ int Poller::do_poll(int timeout) return 0; #else - int ret=::poll(&pfd.front(), pfd.size(), timeout); + int ret = ::poll(&pfd.front(), pfd.size(), timeout); if(ret==-1) { if(errno==EINTR) @@ -187,8 +187,8 @@ int Poller::do_poll(int timeout) throw SystemError("Poll failed", errno); } - int n=ret; - SlotMap::iterator j=objects.begin(); + int n = ret; + SlotMap::iterator j = objects.begin(); for(std::vector::iterator i=pfd.begin(); (i!=pfd.end() && n>0); ++i,++j) if(i->revents) { diff --git a/source/poll.h b/source/poll.h index 3bc1470..3566b92 100644 --- a/source/poll.h +++ b/source/poll.h @@ -23,11 +23,11 @@ class Base; enum PollEvent { - P_NONE=0, - P_INPUT=1, - P_PRIO=2, - P_OUTPUT=4, - P_ERROR=8 + P_NONE = 0, + P_INPUT = 1, + P_PRIO = 2, + P_OUTPUT = 4, + P_ERROR = 8 }; inline PollEvent operator|(PollEvent e, PollEvent f) diff --git a/source/utils.cpp b/source/utils.cpp index 8ce5bf3..1905fe0 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -12,9 +12,9 @@ namespace IO { unsigned read_all(Base &obj, char *buf, unsigned size) { - unsigned pos=0; + unsigned pos = 0; while(pos Date: Thu, 9 Jun 2011 15:04:21 +0300 Subject: [PATCH 05/16] Drop copyright and license notices from files --- source/base.cpp | 6 ------ source/base.h | 6 ------ source/buffered.cpp | 7 ------- source/buffered.h | 6 ------ source/console.cpp | 7 ------- source/console.h | 7 ------- source/eventdispatcher.cpp | 6 ------ source/eventdispatcher.h | 6 ------ source/except.h | 6 ------ source/file.cpp | 6 ------ source/file.h | 6 ------ source/filtered.h | 7 ------- source/memory.cpp | 7 ------- source/memory.h | 7 ------- source/mode.h | 6 ------ source/pipe.cpp | 7 ------- source/pipe.h | 6 ------ source/poll.cpp | 6 ------ source/poll.h | 6 ------ source/print.h | 7 ------- source/seek.cpp | 6 ------ source/seek.h | 6 ------ source/serial.cpp | 7 ------- source/serial.h | 7 ------- source/types.h | 6 ------ source/utils.cpp | 6 ------ source/utils.h | 6 ------ 27 files changed, 172 deletions(-) diff --git a/source/base.cpp b/source/base.cpp index 3c9923d..a740433 100644 --- a/source/base.cpp +++ b/source/base.cpp @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #include "base.h" #include "poll.h" diff --git a/source/base.h b/source/base.h index c4d4ed9..584c14e 100644 --- a/source/base.h +++ b/source/base.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_BASE_H_ #define MSP_IO_BASE_H_ diff --git a/source/buffered.cpp b/source/buffered.cpp index b8a2dbe..e36aef4 100644 --- a/source/buffered.cpp +++ b/source/buffered.cpp @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #include #include "buffered.h" #include "except.h" diff --git a/source/buffered.h b/source/buffered.h index 8d52d1d..9142a47 100644 --- a/source/buffered.h +++ b/source/buffered.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_BUFFERED_H_ #define MSP_IO_BUFFERED_H_ diff --git a/source/console.cpp b/source/console.cpp index e860436..fed47be 100644 --- a/source/console.cpp +++ b/source/console.cpp @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2008 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef WIN32 #include #include diff --git a/source/console.h b/source/console.h index d12697f..2d425c8 100644 --- a/source/console.h +++ b/source/console.h @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2008 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef MSP_IO_CONSOLE_H_ #define MSP_IO_CONSOLE_H_ diff --git a/source/eventdispatcher.cpp b/source/eventdispatcher.cpp index 02330ec..06a594f 100644 --- a/source/eventdispatcher.cpp +++ b/source/eventdispatcher.cpp @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #include #include "base.h" #include "eventdispatcher.h" diff --git a/source/eventdispatcher.h b/source/eventdispatcher.h index 8142b08..dca6592 100644 --- a/source/eventdispatcher.h +++ b/source/eventdispatcher.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef EVENTDISPATCHER_H_ #define EVENTDISPATCHER_H_ diff --git a/source/except.h b/source/except.h index b277b8d..5770f64 100644 --- a/source/except.h +++ b/source/except.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_EXCEPT_H_ #define MSP_IO_EXCEPT_H_ diff --git a/source/file.cpp b/source/file.cpp index 0b153cf..8182e4a 100644 --- a/source/file.cpp +++ b/source/file.cpp @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef WIN32 #include #include diff --git a/source/file.h b/source/file.h index 16f2dcb..6353a46 100644 --- a/source/file.h +++ b/source/file.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_FILE_H_ #define MSP_IO_FILE_H_ diff --git a/source/filtered.h b/source/filtered.h index ff8577a..98cda47 100644 --- a/source/filtered.h +++ b/source/filtered.h @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2008 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef MSP_IO_FILTERED_H_ #define MSP_IO_FILTERED_H_ diff --git a/source/memory.cpp b/source/memory.cpp index 80dde27..13a6606 100644 --- a/source/memory.cpp +++ b/source/memory.cpp @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2009 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #include #include #include "except.h" diff --git a/source/memory.h b/source/memory.h index 7ff5316..80f884e 100644 --- a/source/memory.h +++ b/source/memory.h @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2009 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef MSP_IO_MEMORY_H_ #define MSP_IO_MEMORY_H_ diff --git a/source/mode.h b/source/mode.h index d807e5f..5e103f2 100644 --- a/source/mode.h +++ b/source/mode.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_MODE_H_ #define MSP_IO_MODE_H_ diff --git a/source/pipe.cpp b/source/pipe.cpp index bd90527..7f0ff70 100644 --- a/source/pipe.cpp +++ b/source/pipe.cpp @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef WIN32 #include #include diff --git a/source/pipe.h b/source/pipe.h index 2ad83f8..b67cd79 100644 --- a/source/pipe.h +++ b/source/pipe.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_PIPE_H_ #define MSP_IO_PIPE_H_ diff --git a/source/poll.cpp b/source/poll.cpp index 49e4887..dce1912 100644 --- a/source/poll.cpp +++ b/source/poll.cpp @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #include #include #include diff --git a/source/poll.h b/source/poll.h index 3566b92..0f97cb1 100644 --- a/source/poll.h +++ b/source/poll.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_POLL_H_ #define MSP_IO_POLL_H_ diff --git a/source/print.h b/source/print.h index 10fb02e..65744cb 100644 --- a/source/print.h +++ b/source/print.h @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef MSP_IO_PRINT_H_ #define MSP_IO_PRINT_H_ diff --git a/source/seek.cpp b/source/seek.cpp index 88ba033..b10c5a0 100644 --- a/source/seek.cpp +++ b/source/seek.cpp @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifdef WIN32 #include #endif diff --git a/source/seek.h b/source/seek.h index 6d15437..3c6c331 100644 --- a/source/seek.h +++ b/source/seek.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_SEEK_H_ #define MSP_IO_SEEK_H_ diff --git a/source/serial.cpp b/source/serial.cpp index 1aedd41..0a5eca0 100644 --- a/source/serial.cpp +++ b/source/serial.cpp @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2010 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifdef WIN32 #include #else diff --git a/source/serial.h b/source/serial.h index fd34cde..d5f1de7 100644 --- a/source/serial.h +++ b/source/serial.h @@ -1,10 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2010 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - #ifndef MSP_IO_SERIAL_H_ #define MSP_IO_SERIAL_H_ diff --git a/source/types.h b/source/types.h index bb8b923..f18b7cb 100644 --- a/source/types.h +++ b/source/types.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_TYPES_H_ #define MSP_IO_TYPES_H_ diff --git a/source/utils.cpp b/source/utils.cpp index 1905fe0..eee51cc 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #include "base.h" #include "utils.h" diff --git a/source/utils.h b/source/utils.h index fc51d45..066b15b 100644 --- a/source/utils.h +++ b/source/utils.h @@ -1,9 +1,3 @@ -/* $Id$ - -This file is part of libmspio -Copyright © 2007 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ #ifndef MSP_IO_UTILS_H_ #define MSP_IO_UTILS_H_ -- 2.43.0 From 9519381422961a538a3ebbd1e6563d170215f14e Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 16:02:55 +0300 Subject: [PATCH 06/16] Add utility functions for getting an item from an std::map --- source/core/maputils.cpp | 12 ++++++++++++ source/core/maputils.h | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 source/core/maputils.cpp create mode 100644 source/core/maputils.h diff --git a/source/core/maputils.cpp b/source/core/maputils.cpp new file mode 100644 index 0000000..4fcc8e2 --- /dev/null +++ b/source/core/maputils.cpp @@ -0,0 +1,12 @@ +#include +#include "maputils.h" + +using namespace std; + +namespace Msp { + +key_error::key_error(const type_info &t): + runtime_error(Debug::demangle(t.name())) +{ } + +} // namespace Msp diff --git a/source/core/maputils.h b/source/core/maputils.h new file mode 100644 index 0000000..1a7c0ae --- /dev/null +++ b/source/core/maputils.h @@ -0,0 +1,38 @@ +#ifndef MSP_CORE_MAPUTILS_H_ +#define MSP_CORE_MAPUTILS_H_ + +#include +#include + +namespace Msp { + +class key_error: public std::runtime_error +{ +public: + key_error(const std::type_info &); +}; + + +template +typename T::mapped_type &get_item(T &map, const typename T::key_type &key) +{ + typename T::iterator i = map.find(key); + if(i==map.end()) + throw key_error(typeid(T)); + + return i->second; +} + +template +const typename T::mapped_type &get_item(const T &map, const typename T::key_type &key) +{ + typename T::const_iterator i = map.find(key); + if(i==map.end()) + throw key_error(typeid(T)); + + return i->second; +} + +} // namespace Msp + +#endif -- 2.43.0 From f4cf84ddec17f4fec0d9ba7e6814a8af8ff50395 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 16:03:37 +0300 Subject: [PATCH 07/16] Use the get_item function in Profiler::get_scope --- source/debug/profiler.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/source/debug/profiler.cpp b/source/debug/profiler.cpp index 0167ff9..e3d9840 100644 --- a/source/debug/profiler.cpp +++ b/source/debug/profiler.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include "profiler.h" @@ -72,11 +72,7 @@ void Profiler::record(const string &scope_name, const string &parent, const Time const Profiler::ScopeInfo &Profiler::scope(const string &sn) const { - map::const_iterator i = scopes.find(sn); - if(i==scopes.end()) - throw KeyError("Unknown scope"); - - return i->second; + return get_item(scopes, sn); } -- 2.43.0 From a268ee8d1990eca21155137d0245b2985579d064 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 9 Jun 2011 17:07:55 +0300 Subject: [PATCH 08/16] Exception changes in strings/utils.cpp --- source/strings/utils.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/strings/utils.cpp b/source/strings/utils.cpp index 93bbbbf..fff6cdb 100644 --- a/source/strings/utils.cpp +++ b/source/strings/utils.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include "utils.h" using namespace std; @@ -148,7 +148,7 @@ string c_unescape(const std::string &str) else if(*i>='A' && *i<='F') digit = *i-'A'+10; else - throw InvalidParameterValue("Invalid hexadecimal digit"); + throw invalid_argument("c_unescape"); numeric_value = (numeric_value<<4 | digit); ++numeric_pos; @@ -164,7 +164,7 @@ string c_unescape(const std::string &str) if(*i>='0' && *i<='7') digit = *i-'0'; else - throw InvalidParameterValue("Invalid octal digit"); + throw invalid_argument("c_unescape"); numeric_value = (numeric_value<<3 | digit); ++numeric_pos; @@ -209,7 +209,7 @@ string c_unescape(const std::string &str) else if(*i=='\\') result += '\\'; else - throw InvalidParameterValue("Invalid escape sequence"); + throw invalid_argument("c_unescape"); escape = false; } @@ -220,7 +220,7 @@ string c_unescape(const std::string &str) } if(escape) - throw InvalidParameterValue("Stray backslash at end of string"); + throw invalid_argument("c_unescape"); return result; } -- 2.43.0 From b97d4e9f86e90254ab9edef7ee62a910f6333c78 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Fri, 10 Jun 2011 21:00:11 +0300 Subject: [PATCH 09/16] Move class members and comments around --- source/base.cpp | 34 ++++---- source/base.h | 146 +++++++++++++-------------------- source/buffered.cpp | 130 +++++++++++++++--------------- source/buffered.h | 32 +++++--- source/console.cpp | 10 +-- source/console.h | 9 ++- source/eventdispatcher.h | 32 ++++---- source/file.cpp | 170 +++++++++++++++------------------------ source/file.h | 32 +++++--- source/filtered.h | 12 +-- source/memory.cpp | 48 +++++------ source/memory.h | 7 +- source/pipe.cpp | 86 ++++++++++---------- source/pipe.h | 31 ++++--- source/poll.h | 16 ++-- source/serial.cpp | 36 ++++----- source/serial.h | 10 ++- source/utils.h | 9 +-- 18 files changed, 404 insertions(+), 446 deletions(-) diff --git a/source/base.cpp b/source/base.cpp index a740433..48de3ee 100644 --- a/source/base.cpp +++ b/source/base.cpp @@ -6,6 +6,17 @@ using namespace std; namespace Msp { namespace IO { +Base::Base(): + mode(M_READ), + events(P_NONE), + eof_flag(false) +{ } + +Base::~Base() +{ + signal_deleted.emit(); +} + bool Base::getline(string &line) { line.clear(); @@ -32,6 +43,12 @@ int Base::get() return static_cast(c); } +void Base::set_events(PollEvent e) +{ + events = e; + signal_events_changed.emit(events); +} + void Base::event(PollEvent ev) { if(ev&P_INPUT) @@ -40,22 +57,5 @@ void Base::event(PollEvent ev) on_event(ev); } -Base::~Base() -{ - signal_deleted.emit(); -} - -Base::Base(): - mode(M_READ), - events(P_NONE), - eof_flag(false) -{ } - -void Base::set_events(PollEvent e) -{ - events = e; - signal_events_changed.emit(events); -} - } // namespace IO } // namespace Msp diff --git a/source/base.h b/source/base.h index 584c14e..774d034 100644 --- a/source/base.h +++ b/source/base.h @@ -18,135 +18,101 @@ leaving stale pointers in an EventDispatcher. class Base { public: - /** - Emitted when there is data available for reading. If all data is not read, - the signal is emitted again immediately. - */ + /** Emitted when there is data available for reading. If all data is not + read, the signal is emitted again immediately. */ sigc::signal signal_data_available; - /** - Emitted when there is no more data to be read. - */ + /** Emitted when there is no more data to be read. */ sigc::signal signal_end_of_file; - /** - Emitted when there is a nonlinearity in I/O (such as a file being seeked) - and any data buffered by upper layers needs to be flushed. - */ + /** Emitted when there is a nonlinearity in I/O (such as a file being + seeked) and any data buffered by upper layers needs to be flushed. */ sigc::signal signal_flush_required; - /** - Emitted when the I/O object has closed. - */ + /** Emitted when the I/O object has closed. */ sigc::signal signal_closed; - /** - Emitted when the mask of interesting events changes. Mainly for use by - EventDispatcher. - */ + /** Emitted when the mask of interesting events changes. Mainly for use by + EventDispatcher. */ sigc::signal signal_events_changed; - /** - Emitted when the object is deleted. Mainly for use by EventDispatcher. - */ + /** Emitted when the object is deleted. Mainly for use by + EventDispatcher. */ sigc::signal signal_deleted; - /** - Sets blocking mode. When blocking is enabled, most operations won't return - until they can make progress. When blocking is disabled, these operations - may return immediately with a return code indicating that nothing was done. +protected: + Mode mode; + PollEvent events; + bool eof_flag; + + Base(); +private: + Base(const Base &); + Base &operator=(const Base &); +public: + virtual ~Base(); + + /** Sets blocking mode. When blocking is enabled, most operations won't + return until they can make progress. When blocking is disabled, these + operations may return immediately with a return code indicating that nothing + was done. - Blocking is enabled by default. - */ + Blocking is enabled by default. */ virtual void set_block(bool) { } - /** - Returns the current mode flags. - */ + /** Returns the current mode flags. */ Mode get_mode() const { return mode; } - /** - Writes data from a buffer. Subject to blocking. - - @param b Buffer to write from - @param c Number of bytes to write +protected: + virtual unsigned do_write(const char *, unsigned) =0; + virtual unsigned do_read(char *, unsigned) =0; - @return Number of bytes written - */ +public: + /** Writes data from a buffer. Subject to blocking. Returns the number of + bytes written, which may be zero for a non-blockin operation. */ unsigned write(const char *b, unsigned c) { return do_write(b, c); } - /** - Writes a string. This is identical to calling write(s.data(), s.size()). - */ + /** Writes a string. This is identical to calling + write(s.data(), s.size()). */ unsigned write(const std::string &s) { return do_write(s.data(), s.size()); } - /** - Writes a single character. This is identical to calling write(&c, 1). - */ + /** Writes a single character. This is identical to calling + write(&c, 1). */ virtual unsigned put(char c) { return do_write(&c, 1); } - /** - Reads data into a buffer. Subject to blocking. - - @param b Buffer to read into - @param c Maximum number of bytes to read - - @return Number of bytes read - */ + /** Reads data into a buffer. Subject to blocking. Returns the number of + bytes read, which may be zero for a non-blocking operation. */ unsigned read(char *b, unsigned c) { return do_read(b, c); } - /** - Reads characters up to the next linefeed or end-of-file. The linefeed is not - included in the line. - - @param line String to put the characters into - - @return Whether anything was read - */ + /** Reads characters up to the next linefeed or end-of-file. The linefeed + is not included in the line. Returns true if a line was successfully read, + false otherwise. */ virtual bool getline(std::string &); - /** - Reads a single character. - - @return A character, or -1 if none were available - */ + /** Reads a single character. Returns -1 if no character was available due + to end-of-file or non-blocking operation. */ virtual int get(); - /** - Returns the end-of-file flag. - */ + /** Returns the end-of-file flag. */ bool eof() const { return eof_flag; } - /** - Returns a mask of the currently interesting events. Used by EventDispatcher. - */ +protected: + void set_events(PollEvent); + +public: + /** Returns a mask of the currently interesting events. Used by + EventDispatcher. */ PollEvent get_events() const { return events; } - /** - Returns a handle for polling. Should throw if the object does not have an - event handle. - */ + /** Returns a handle for polling. Should throw if the object does not have + an event handle. */ virtual Handle get_event_handle() =0; - /** - Notifies the object of an event. Used by EventDispatcher. - */ + /** Notifies the object of an event. Used by EventDispatcher. */ void event(PollEvent); - virtual ~Base(); protected: - Mode mode; - PollEvent events; - bool eof_flag; - - Base(); - void set_events(PollEvent); - virtual void on_event(PollEvent) { } - virtual unsigned do_write(const char *, unsigned) =0; - virtual unsigned do_read(char *, unsigned) =0; -private: - Base(const Base &); - Base &operator=(const Base &); + virtual void on_event(PollEvent) { } }; } // namespace IO diff --git a/source/buffered.cpp b/source/buffered.cpp index e36aef4..f53d2fc 100644 --- a/source/buffered.cpp +++ b/source/buffered.cpp @@ -19,17 +19,16 @@ Buffered::Buffered(Base &b, unsigned s): below.signal_flush_required.connect(sigc::mem_fun(this, &Buffered::flush)); } -unsigned Buffered::put(char c) +Buffered::~Buffered() { - set_op(M_WRITE); - - if(end(*begin++); - - char c; - if(do_read(&c, 1)==0) - return -1; - return static_cast(c); -} - -Handle Buffered::get_event_handle() -{ - throw Exception("Buffered doesn't support events"); -} - -unsigned Buffered::get_current_size() const -{ - return end-begin; -} - -Buffered::~Buffered() -{ - try - { - flush(); - } - catch(...) - { } - - delete[] buf; -} - -void Buffered::set_op(Mode op) -{ - if(op!=cur_op) - flush(); - cur_op = op; -} - unsigned Buffered::do_write(const char *data, unsigned size) { set_op(M_WRITE); @@ -184,5 +126,63 @@ unsigned Buffered::do_read(char *data, unsigned size) } } +unsigned Buffered::put(char c) +{ + set_op(M_WRITE); + + if(end(*begin++); + + char c; + if(do_read(&c, 1)==0) + return -1; + return static_cast(c); +} + +void Buffered::set_op(Mode op) +{ + if(op!=cur_op) + flush(); + cur_op = op; +} + +unsigned Buffered::get_current_size() const +{ + return end-begin; +} + +Handle Buffered::get_event_handle() +{ + throw Exception("Buffered doesn't support events"); +} + } // namespace IO } // namespace Msp diff --git a/source/buffered.h b/source/buffered.h index 9142a47..36d2a11 100644 --- a/source/buffered.h +++ b/source/buffered.h @@ -9,29 +9,35 @@ namespace IO { class Buffered: public Base { private: - Base &below; + Base &below; unsigned buf_size; - char *buf; - char *begin; - char *end; - Mode cur_op; + char *buf; + char *begin; + char *end; + Mode cur_op; public: Buffered(Base &, unsigned =8192); ~Buffered(); - unsigned put(char); void flush(); - bool getline(std::string &); - int get(); - Handle get_event_handle(); - Mode get_current_op() const { return cur_op; } - unsigned get_current_size() const; -private: - void set_op(Mode); + protected: unsigned do_write(const char *, unsigned); unsigned do_read(char *, unsigned); +public: + unsigned put(char); + + bool getline(std::string &); + int get(); + +private: + void set_op(Mode); +public: + Mode get_current_op() const { return cur_op; } + unsigned get_current_size() const; + + virtual Handle get_event_handle(); }; } // namespace IO diff --git a/source/console.cpp b/source/console.cpp index fed47be..9db7737 100644 --- a/source/console.cpp +++ b/source/console.cpp @@ -115,11 +115,6 @@ void Console::get_size(unsigned &rows, unsigned &cols) #endif } -Handle Console::get_event_handle() -{ - return 0; -} - unsigned Console::do_write(const char *buf, unsigned len) { if(!(mode&M_WRITE)) @@ -163,6 +158,11 @@ unsigned Console::do_read(char *buf, unsigned len) return ret; } +Handle Console::get_event_handle() +{ + return 0; +} + Console &Console::instance(unsigned n) { static Console in(0); diff --git a/source/console.h b/source/console.h index 2d425c8..3c0bb71 100644 --- a/source/console.h +++ b/source/console.h @@ -32,16 +32,17 @@ public: */ void set_line_buffer(bool); - /** - Retrieves the size of the Console. Can only be used on an output Console. - */ + /** Retrieves the size of the Console. Can only be used on an output + Console. */ void get_size(unsigned &rows, unsigned &cols); - virtual Handle get_event_handle(); protected: virtual unsigned do_write(const char *, unsigned); virtual unsigned do_read(char *, unsigned); + public: + virtual Handle get_event_handle(); + static Console &instance(unsigned); }; diff --git a/source/eventdispatcher.h b/source/eventdispatcher.h index dca6592..7e89d47 100644 --- a/source/eventdispatcher.h +++ b/source/eventdispatcher.h @@ -14,22 +14,6 @@ on some of them. */ class EventDispatcher: public sigc::trackable { -public: - EventDispatcher(); - void add(Base &); - void remove(Base &); - - /** - Checks for and dispatches events. If there are no events available, blocks - until there are. - */ - void tick(); - - /** - Checks for and dispatches events. If there are no events available, waits - at most the specified time before returning. - */ - void tick(const Time::TimeDelta &); private: struct Slot { @@ -39,11 +23,27 @@ private: Slot(Base *o): obj(o) { } }; + typedef std::map SlotMap; Poller poller; SlotMap objects; +public: + EventDispatcher(); + + void add(Base &); + void remove(Base &); + + /** Checks for and dispatches events. If there are no events available, + blocks until there are. */ + void tick(); + + /** Checks for and dispatches events. If there are no events available, + waits at most the specified time before returning. */ + void tick(const Time::TimeDelta &); + +private: void object_events_changed(PollEvent, Base *); void object_deleted(Base *); void dispatch(); diff --git a/source/file.cpp b/source/file.cpp index 8182e4a..2990d5c 100644 --- a/source/file.cpp +++ b/source/file.cpp @@ -12,15 +12,6 @@ using namespace std; namespace Msp { namespace IO { -/** -Creates a new file object and opens it. If the -create flag is true and write access is requested and the file does exist, it -is created. Otherwise a missing file is an error. - -@param fn Name of the file to open -@param m Open mode -@param cm Flags controlling creation of a new file -*/ File::File(const string &fn, Mode m, CreateMode cm) { if(!(m&M_RDWR)) @@ -94,10 +85,11 @@ File::File(const string &fn, Mode m, CreateMode cm) set_events(P_INPUT); } -/** -Closes the file. Any attempt to access the file after this will cause an -exception to be thrown. -*/ +File::~File() +{ + close(); +} + void File::close() { if(handle==MSP_IO_INVALID_HANDLE) @@ -117,10 +109,6 @@ void File::close() signal_closed.emit(); } -/** -Sets the blocking state of the file. If blocking is disabled, all operations -will return immediately, even if they can't be fully completed. -*/ void File::set_block(bool b) { check_access(M_NONE); @@ -134,88 +122,6 @@ void File::set_block(bool b) #endif } -void File::sync() -{ -#ifndef WIN32 - signal_flush_required.emit(); - - fsync(handle); -#endif -} - -/** -Seeks the file to the given byte offset. - -@param off Offset in bytes -@param st Seek type - -@return The resulting offset -*/ -int File::seek(int off, SeekType st) -{ - check_access(M_NONE); - - signal_flush_required.emit(); - - int type = sys_seek_type(st); -#ifdef WIN32 - DWORD ret = SetFilePointer(handle, off, 0, type); - if(ret==INVALID_SET_FILE_POINTER) - throw SystemError("Seek failed", GetLastError()); -#else - int ret = lseek(handle, off, type); - if(ret==-1) - throw SystemError("Seek failed", errno); -#endif - - eof_flag = false; - - return ret; -} - -/** -Returns the current read/write offset of the file. -*/ -int File::tell() const -{ - check_access(M_NONE); - -#ifdef WIN32 - DWORD ret = SetFilePointer(handle, 0, 0, FILE_CURRENT); - if(ret==INVALID_SET_FILE_POINTER) - throw SystemError("Tell failed", GetLastError()); -#else - int ret = lseek(handle, 0, SEEK_CUR); - if(ret==-1) - throw SystemError("Tell failed", errno); -#endif - - return ret; -} - -File::~File() -{ - close(); -} - -void File::check_access(Mode m) const -{ - if(handle==MSP_IO_INVALID_HANDLE) - throw InvalidState("File is not open"); - if(m==M_READ && !(mode&M_READ)) - throw InvalidState("File is not readable"); - if(m==M_WRITE && !(mode&M_WRITE)) - throw InvalidState("File is not writable"); -} - -/** -Writes data from a buffer to the file. - -@param buf Buffer to write from. -@param size Length of data to write. - -@return The number of bytes written -*/ unsigned File::do_write(const char *buf, unsigned size) { check_access(M_WRITE); @@ -243,14 +149,6 @@ unsigned File::do_write(const char *buf, unsigned size) return ret; } -/** -Reads data from the file. - -@param buf Buffer to read data into. -@param size Maximum size of data to read. - -@return The number of bytes read, possibly zero -*/ unsigned File::do_read(char *buf, unsigned size) { check_access(M_READ); @@ -282,5 +180,63 @@ unsigned File::do_read(char *buf, unsigned size) return ret; } +void File::sync() +{ +#ifndef WIN32 + signal_flush_required.emit(); + + fsync(handle); +#endif +} + +int File::seek(int off, SeekType st) +{ + check_access(M_NONE); + + signal_flush_required.emit(); + + int type = sys_seek_type(st); +#ifdef WIN32 + DWORD ret = SetFilePointer(handle, off, 0, type); + if(ret==INVALID_SET_FILE_POINTER) + throw SystemError("Seek failed", GetLastError()); +#else + int ret = lseek(handle, off, type); + if(ret==-1) + throw SystemError("Seek failed", errno); +#endif + + eof_flag = false; + + return ret; +} + +int File::tell() const +{ + check_access(M_NONE); + +#ifdef WIN32 + DWORD ret = SetFilePointer(handle, 0, 0, FILE_CURRENT); + if(ret==INVALID_SET_FILE_POINTER) + throw SystemError("Tell failed", GetLastError()); +#else + int ret = lseek(handle, 0, SEEK_CUR); + if(ret==-1) + throw SystemError("Tell failed", errno); +#endif + + return ret; +} + +void File::check_access(Mode m) const +{ + if(handle==MSP_IO_INVALID_HANDLE) + throw InvalidState("File is not open"); + if(m==M_READ && !(mode&M_READ)) + throw InvalidState("File is not readable"); + if(m==M_WRITE && !(mode&M_WRITE)) + throw InvalidState("File is not writable"); +} + } // namespace IO } // namespace Msp diff --git a/source/file.h b/source/file.h index 6353a46..05aaf95 100644 --- a/source/file.h +++ b/source/file.h @@ -25,27 +25,39 @@ public: C_TRUNCATE = 2 }; - File(const std::string &, Mode = M_READ, CreateMode =CreateMode(C_CREATE+C_TRUNCATE)); +private: + Handle handle; + +public: + /** Creates a new file object and opens it. If the create flag is set and + write access is requested and the file does exist, it is created. Otherwise + a missing file is an error. */ + File(const std::string &, Mode = M_READ, CreateMode = CreateMode(C_CREATE+C_TRUNCATE)); + virtual ~File(); + /** Closes the file. Any attempt to access the file after this will cause + an exception to be thrown. */ void close(); void set_block(bool); +protected: + virtual unsigned do_write(const char *, unsigned); + virtual unsigned do_read(char *, unsigned); + +public: virtual void sync(); - virtual int seek(int, SeekType); - virtual int tell() const; + /** Changes the read/write offset of the file. Returns the new offset. */ + virtual int seek(int, SeekType); + + /** Returns the current read/write offset of the file. */ + virtual int tell() const; virtual Handle get_event_handle() { return handle; } - virtual ~File(); private: - Handle handle; - - void check_access(Mode) const; -protected: - virtual unsigned do_write(const char *, unsigned); - virtual unsigned do_read(char *, unsigned); + void check_access(Mode) const; }; inline File::CreateMode operator|(File::CreateMode m, File::CreateMode n) diff --git a/source/filtered.h b/source/filtered.h index 98cda47..0d323ec 100644 --- a/source/filtered.h +++ b/source/filtered.h @@ -29,11 +29,6 @@ public: template Filtered(A0 a0, A1 a1): B(a0, a1), filter(*this), active(false) { } - virtual unsigned put(char c) { return filter.put(c); } - virtual bool getline(std::string &l) { return filter.getline(l); } - virtual int get() { return filter.get(); } - - F &get_filter() { return filter; } protected: virtual unsigned do_write(const char *b, unsigned s) { @@ -56,6 +51,13 @@ protected: else return B::do_read(b, s); } + +public: + virtual unsigned put(char c) { return filter.put(c); } + virtual bool getline(std::string &l) { return filter.getline(l); } + virtual int get() { return filter.get(); } + + F &get_filter() { return filter; } }; } // namespace IO diff --git a/source/memory.cpp b/source/memory.cpp index 13a6606..6ea130b 100644 --- a/source/memory.cpp +++ b/source/memory.cpp @@ -37,6 +37,30 @@ void Memory::init(char *b, char *e, Mode m) mode = m; } +unsigned Memory::do_write(const char *buf, unsigned size) +{ + check_mode(M_WRITE); + + size = min(size, end-pos); + memcpy(pos, buf, size); + pos += size; + return size; +} + +unsigned Memory::do_read(char *buf, unsigned size) +{ + if(pos==end) + { + eof_flag = true; + return 0; + } + + size = min(size, end-pos); + memcpy(buf, pos, size); + pos += size; + return size; +} + unsigned Memory::put(char c) { check_mode(M_WRITE); @@ -88,30 +112,6 @@ Handle Memory::get_event_handle() throw Exception("Memory doesn't support events"); } -unsigned Memory::do_write(const char *buf, unsigned size) -{ - check_mode(M_WRITE); - - size = min(size, end-pos); - memcpy(pos, buf, size); - pos += size; - return size; -} - -unsigned Memory::do_read(char *buf, unsigned size) -{ - if(pos==end) - { - eof_flag = true; - return 0; - } - - size = min(size, end-pos); - memcpy(buf, pos, size); - pos += size; - return size; -} - void Memory::check_mode(Mode m) const { if(m==M_WRITE) diff --git a/source/memory.h b/source/memory.h index 80f884e..ba6c4d8 100644 --- a/source/memory.h +++ b/source/memory.h @@ -22,16 +22,19 @@ public: private: void init(char *, char *, Mode); + virtual unsigned do_write(const char *, unsigned); + virtual unsigned do_read(char *, unsigned); public: virtual unsigned put(char); virtual bool getline(std::string &); virtual int get(); + unsigned seek(int, SeekType); unsigned tell() const { return pos-begin; } + virtual Handle get_event_handle(); + private: - virtual unsigned do_write(const char *, unsigned); - virtual unsigned do_read(char *, unsigned); void check_mode(Mode) const; }; diff --git a/source/pipe.cpp b/source/pipe.cpp index 7f0ff70..b3735aa 100644 --- a/source/pipe.cpp +++ b/source/pipe.cpp @@ -40,18 +40,9 @@ Pipe::Pipe() set_events(P_INPUT); } -void Pipe::set_block(bool b) +Pipe::~Pipe() { - mode = (mode&~M_NONBLOCK); - if(b) - mode = (mode|M_NONBLOCK); - -#ifndef WIN32 - int flags = fcntl(handle[0], F_GETFD); - fcntl(handle[0], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); - flags = fcntl(handle[1], F_GETFD); - fcntl(handle[1], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); -#endif + close(); } void Pipe::close() @@ -69,43 +60,20 @@ void Pipe::close() #endif } -Handle Pipe::get_event_handle() +void Pipe::set_block(bool b) { -#ifdef WIN32 - if(!overlapped && !buf_avail) - { - overlapped = new OVERLAPPED; - memset(overlapped, 0, sizeof(OVERLAPPED)); - overlapped->hEvent = event; - - DWORD ret; - buf_next = buffer; - if(!ReadFile(handle[0], buffer, buf_size, &ret, overlapped)) - { - unsigned err = GetLastError(); - if(err!=ERROR_IO_PENDING) - throw SystemError("Failed to start an overlapped read", err); - } - else - { - buf_avail = ret; - delete overlapped; - overlapped = 0; - SetEvent(event); - } - } + mode = (mode&~M_NONBLOCK); + if(b) + mode = (mode|M_NONBLOCK); - return event; -#else - return handle[0]; +#ifndef WIN32 + int flags = fcntl(handle[0], F_GETFD); + fcntl(handle[0], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); + flags = fcntl(handle[1], F_GETFD); + fcntl(handle[1], F_SETFL, (flags&O_NONBLOCK)|(b?0:O_NONBLOCK)); #endif } -Pipe::~Pipe() -{ - close(); -} - unsigned Pipe::do_write(const char *buf, unsigned size) { if(size==0) @@ -178,5 +146,37 @@ unsigned Pipe::do_read(char *buf, unsigned size) return ret; } +Handle Pipe::get_event_handle() +{ +#ifdef WIN32 + if(!overlapped && !buf_avail) + { + overlapped = new OVERLAPPED; + memset(overlapped, 0, sizeof(OVERLAPPED)); + overlapped->hEvent = event; + + DWORD ret; + buf_next = buffer; + if(!ReadFile(handle[0], buffer, buf_size, &ret, overlapped)) + { + unsigned err = GetLastError(); + if(err!=ERROR_IO_PENDING) + throw SystemError("Failed to start an overlapped read", err); + } + else + { + buf_avail = ret; + delete overlapped; + overlapped = 0; + SetEvent(event); + } + } + + return event; +#else + return handle[0]; +#endif +} + } // namespace IO } // namespace Msp diff --git a/source/pipe.h b/source/pipe.h index b67cd79..71edf7e 100644 --- a/source/pipe.h +++ b/source/pipe.h @@ -8,26 +8,31 @@ namespace IO { class Pipe: public Base { -public: - Pipe(); - void set_block(bool); - void close(); - Handle get_event_handle(); - ~Pipe(); private: Handle handle[2]; #ifdef WIN32 OVERLAPPED *overlapped; - Handle event; - unsigned buf_size; - char *buffer; - unsigned buf_avail; - char *buf_next; + Handle event; + unsigned buf_size; + char *buffer; + unsigned buf_avail; + char *buf_next; #endif +public: + Pipe(); + ~Pipe(); + + void close(); + + void set_block(bool); + protected: - unsigned do_write(const char *, unsigned); - unsigned do_read(char *, unsigned); + virtual unsigned do_write(const char *, unsigned); + virtual unsigned do_read(char *, unsigned); + +public: + virtual Handle get_event_handle(); }; } // namespace IO diff --git a/source/poll.h b/source/poll.h index 0f97cb1..6367d8f 100644 --- a/source/poll.h +++ b/source/poll.h @@ -33,6 +33,7 @@ inline PollEvent operator&(PollEvent e, PollEvent f) inline PollEvent operator~(PollEvent e) { return PollEvent(~static_cast(e)); } + class Poller { public: @@ -43,13 +44,8 @@ public: Slot(Base *o, PollEvent e): object(o), events(e) { } }; - typedef std::list SlotSeq; - Poller(); - void set_object(Base &, PollEvent); - int poll(); - int poll(const Time::TimeDelta &); - const SlotSeq &get_result() const { return poll_result; } + typedef std::list SlotSeq; private: typedef std::map SlotMap; @@ -67,6 +63,14 @@ private: void rebuild_pfd(); int do_poll(int); + +public: + Poller(); + + void set_object(Base &, PollEvent); + int poll(); + int poll(const Time::TimeDelta &); + const SlotSeq &get_result() const { return poll_result; } }; PollEvent poll(Base &, PollEvent); diff --git a/source/serial.cpp b/source/serial.cpp index 0a5eca0..ec6a198 100644 --- a/source/serial.cpp +++ b/source/serial.cpp @@ -205,6 +205,15 @@ Serial::~Serial() close(); } +void Serial::close() +{ +#ifdef WIN32 + CloseHandle(handle); +#else + ::close(handle); +#endif +} + void Serial::set_block(bool b) { if(b) @@ -272,24 +281,6 @@ void Serial::set_parameters(const string ¶ms) set_state(handle, state); } -Handle Serial::get_event_handle() -{ -#ifdef WIN32 - throw Exception("Serial port events not supported on win32 yet"); -#else - return handle; -#endif -} - -void Serial::close() -{ -#ifdef WIN32 - CloseHandle(handle); -#else - ::close(handle); -#endif -} - unsigned Serial::do_write(const char *buf, unsigned size) { if(size==0) @@ -336,5 +327,14 @@ unsigned Serial::do_read(char *buf, unsigned size) return ret; } +Handle Serial::get_event_handle() +{ +#ifdef WIN32 + throw Exception("Serial port events not supported on win32 yet"); +#else + return handle; +#endif +} + } // namespace IO } // namespace Msp diff --git a/source/serial.h b/source/serial.h index d5f1de7..069789c 100644 --- a/source/serial.h +++ b/source/serial.h @@ -23,6 +23,10 @@ public: Serial(const std::string &); virtual ~Serial(); +private: + void close(); + +public: virtual void set_block(bool); void set_baud_rate(unsigned); @@ -31,12 +35,12 @@ public: void set_stop_bits(unsigned); void set_parameters(const std::string &); - virtual Handle get_event_handle(); - private: - void close(); virtual unsigned do_write(const char *, unsigned); virtual unsigned do_read(char *, unsigned); + +public: + virtual Handle get_event_handle(); }; } // namespace IO diff --git a/source/utils.h b/source/utils.h index 066b15b..8d4f9dd 100644 --- a/source/utils.h +++ b/source/utils.h @@ -6,13 +6,12 @@ namespace IO { class Base; -/** -Reads data from an object. Does not return until the requested amount of data -is read, regardless of the blocking mode of the object. +/** Reads data from an object. Does not return until the requested amount of +data is read, regardless of the blocking mode of the object. Note: If the data is not immediately available and the object is in non-blocking -mode, this function effectively becomes a busyloop until it can get more data. -*/ +mode, this function effectively becomes a busyloop until it can get more +data. */ unsigned read_all(Base &, char *, unsigned); } // namespace IO -- 2.43.0 From 6e0fd758970bcb5bad5e3f2454b694cc4d7b4b66 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Fri, 10 Jun 2011 21:01:55 +0300 Subject: [PATCH 10/16] Move files to prepare for assimilation into core --- source/{ => io}/base.cpp | 0 source/{ => io}/base.h | 0 source/{ => io}/buffered.cpp | 0 source/{ => io}/buffered.h | 0 source/{ => io}/console.cpp | 0 source/{ => io}/console.h | 0 source/{ => io}/eventdispatcher.cpp | 0 source/{ => io}/eventdispatcher.h | 0 source/{ => io}/except.h | 0 source/{ => io}/file.cpp | 0 source/{ => io}/file.h | 0 source/{ => io}/filtered.h | 0 source/{ => io}/memory.cpp | 0 source/{ => io}/memory.h | 0 source/{ => io}/mode.h | 0 source/{ => io}/pipe.cpp | 0 source/{ => io}/pipe.h | 0 source/{ => io}/poll.cpp | 0 source/{ => io}/poll.h | 0 source/{ => io}/print.h | 0 source/{ => io}/seek.cpp | 0 source/{ => io}/seek.h | 0 source/{ => io}/serial.cpp | 0 source/{ => io}/serial.h | 0 source/{ => io}/types.h | 0 source/{ => io}/utils.cpp | 0 source/{ => io}/utils.h | 0 27 files changed, 0 insertions(+), 0 deletions(-) rename source/{ => io}/base.cpp (100%) rename source/{ => io}/base.h (100%) rename source/{ => io}/buffered.cpp (100%) rename source/{ => io}/buffered.h (100%) rename source/{ => io}/console.cpp (100%) rename source/{ => io}/console.h (100%) rename source/{ => io}/eventdispatcher.cpp (100%) rename source/{ => io}/eventdispatcher.h (100%) rename source/{ => io}/except.h (100%) rename source/{ => io}/file.cpp (100%) rename source/{ => io}/file.h (100%) rename source/{ => io}/filtered.h (100%) rename source/{ => io}/memory.cpp (100%) rename source/{ => io}/memory.h (100%) rename source/{ => io}/mode.h (100%) rename source/{ => io}/pipe.cpp (100%) rename source/{ => io}/pipe.h (100%) rename source/{ => io}/poll.cpp (100%) rename source/{ => io}/poll.h (100%) rename source/{ => io}/print.h (100%) rename source/{ => io}/seek.cpp (100%) rename source/{ => io}/seek.h (100%) rename source/{ => io}/serial.cpp (100%) rename source/{ => io}/serial.h (100%) rename source/{ => io}/types.h (100%) rename source/{ => io}/utils.cpp (100%) rename source/{ => io}/utils.h (100%) diff --git a/source/base.cpp b/source/io/base.cpp similarity index 100% rename from source/base.cpp rename to source/io/base.cpp diff --git a/source/base.h b/source/io/base.h similarity index 100% rename from source/base.h rename to source/io/base.h diff --git a/source/buffered.cpp b/source/io/buffered.cpp similarity index 100% rename from source/buffered.cpp rename to source/io/buffered.cpp diff --git a/source/buffered.h b/source/io/buffered.h similarity index 100% rename from source/buffered.h rename to source/io/buffered.h diff --git a/source/console.cpp b/source/io/console.cpp similarity index 100% rename from source/console.cpp rename to source/io/console.cpp diff --git a/source/console.h b/source/io/console.h similarity index 100% rename from source/console.h rename to source/io/console.h diff --git a/source/eventdispatcher.cpp b/source/io/eventdispatcher.cpp similarity index 100% rename from source/eventdispatcher.cpp rename to source/io/eventdispatcher.cpp diff --git a/source/eventdispatcher.h b/source/io/eventdispatcher.h similarity index 100% rename from source/eventdispatcher.h rename to source/io/eventdispatcher.h diff --git a/source/except.h b/source/io/except.h similarity index 100% rename from source/except.h rename to source/io/except.h diff --git a/source/file.cpp b/source/io/file.cpp similarity index 100% rename from source/file.cpp rename to source/io/file.cpp diff --git a/source/file.h b/source/io/file.h similarity index 100% rename from source/file.h rename to source/io/file.h diff --git a/source/filtered.h b/source/io/filtered.h similarity index 100% rename from source/filtered.h rename to source/io/filtered.h diff --git a/source/memory.cpp b/source/io/memory.cpp similarity index 100% rename from source/memory.cpp rename to source/io/memory.cpp diff --git a/source/memory.h b/source/io/memory.h similarity index 100% rename from source/memory.h rename to source/io/memory.h diff --git a/source/mode.h b/source/io/mode.h similarity index 100% rename from source/mode.h rename to source/io/mode.h diff --git a/source/pipe.cpp b/source/io/pipe.cpp similarity index 100% rename from source/pipe.cpp rename to source/io/pipe.cpp diff --git a/source/pipe.h b/source/io/pipe.h similarity index 100% rename from source/pipe.h rename to source/io/pipe.h diff --git a/source/poll.cpp b/source/io/poll.cpp similarity index 100% rename from source/poll.cpp rename to source/io/poll.cpp diff --git a/source/poll.h b/source/io/poll.h similarity index 100% rename from source/poll.h rename to source/io/poll.h diff --git a/source/print.h b/source/io/print.h similarity index 100% rename from source/print.h rename to source/io/print.h diff --git a/source/seek.cpp b/source/io/seek.cpp similarity index 100% rename from source/seek.cpp rename to source/io/seek.cpp diff --git a/source/seek.h b/source/io/seek.h similarity index 100% rename from source/seek.h rename to source/io/seek.h diff --git a/source/serial.cpp b/source/io/serial.cpp similarity index 100% rename from source/serial.cpp rename to source/io/serial.cpp diff --git a/source/serial.h b/source/io/serial.h similarity index 100% rename from source/serial.h rename to source/io/serial.h diff --git a/source/types.h b/source/io/types.h similarity index 100% rename from source/types.h rename to source/io/types.h diff --git a/source/utils.cpp b/source/io/utils.cpp similarity index 100% rename from source/utils.cpp rename to source/io/utils.cpp diff --git a/source/utils.h b/source/io/utils.h similarity index 100% rename from source/utils.h rename to source/io/utils.h -- 2.43.0 From b3bb66ccc178645893455c16915d1e2e3f1287ad Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Fri, 10 Jun 2011 21:03:12 +0300 Subject: [PATCH 11/16] Convert svn:ignore to .gitignore --- .gitignore | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c200d8f --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +/.deps +/.options.* +/.profile +/debug +/libmspio.a +/libmspio.so +/mspio.pc +/release +/temp +/win32 -- 2.43.0 From 8f2711fba7a2817840038630d9cf9a2060ecbe8e Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Fri, 10 Jun 2011 23:47:05 +0300 Subject: [PATCH 12/16] Rework exceptions for IO --- source/io/buffered.cpp | 6 +++--- source/io/console.cpp | 26 ++++++++++++++------------ source/io/except.h | 22 ---------------------- source/io/file.cpp | 38 +++++++++++++++++--------------------- source/io/file.h | 8 ++++++++ source/io/memory.cpp | 16 +++++----------- source/io/mode.cpp | 13 +++++++++++++ source/io/mode.h | 9 +++++++++ source/io/pipe.cpp | 17 +++++++++-------- source/io/poll.cpp | 21 ++++++++++++--------- source/io/seek.cpp | 6 ++++-- source/io/serial.cpp | 40 ++++++++++++++++++++-------------------- 12 files changed, 114 insertions(+), 108 deletions(-) delete mode 100644 source/io/except.h create mode 100644 source/io/mode.cpp diff --git a/source/io/buffered.cpp b/source/io/buffered.cpp index f53d2fc..f725223 100644 --- a/source/io/buffered.cpp +++ b/source/io/buffered.cpp @@ -1,6 +1,6 @@ #include +#include #include "buffered.h" -#include "except.h" using namespace std; @@ -43,7 +43,7 @@ void Buffered::flush() begin=end = buf; if(len #include #endif -#include +#include #include "console.h" +using namespace std; + namespace { #ifndef WIN32 @@ -21,7 +23,7 @@ namespace IO { Console::Console(unsigned n) { if(n>2) - throw InvalidParameterValue("Invalid parameter for Console::Console"); + throw invalid_argument("Console::Console"); mode = (n==0 ? M_READ : M_WRITE); @@ -66,7 +68,7 @@ void Console::set_block(bool b) void Console::set_local_echo(bool e) { if(!(mode&M_READ)) - throw InvalidState("Local echo can only be set on input console"); + throw invalid_access(M_READ); #ifdef WIN32 DWORD m; @@ -83,7 +85,7 @@ void Console::set_local_echo(bool e) void Console::set_line_buffer(bool l) { if(!(mode&M_READ)) - throw InvalidState("Line buffering can only be set on input console"); + throw invalid_access(M_READ); #ifdef WIN32 DWORD m; @@ -101,7 +103,7 @@ void Console::set_line_buffer(bool l) void Console::get_size(unsigned &rows, unsigned &cols) { if(!(mode&M_WRITE)) - throw InvalidState("Size can only be queried from an output console"); + throw invalid_access(M_WRITE); #ifdef WIN32 // XXX Figure out how to do this @@ -118,16 +120,16 @@ void Console::get_size(unsigned &rows, unsigned &cols) unsigned Console::do_write(const char *buf, unsigned len) { if(!(mode&M_WRITE)) - throw InvalidState("Console is not writable"); + throw invalid_access(M_WRITE); #ifdef WIN32 DWORD ret; if(!WriteFile(handle, buf, len, &ret, 0)) - throw SystemError("Writing to console failed", GetLastError()); + throw system_error("WriteFile"); #else int ret = ::write(handle, buf, len); if(ret==-1) - throw SystemError("Writing to console failed", errno); + throw system_error("write"); #endif return ret; @@ -136,12 +138,12 @@ unsigned Console::do_write(const char *buf, unsigned len) unsigned Console::do_read(char *buf, unsigned len) { if(!(mode&M_READ)) - throw InvalidState("Console is not readable"); + throw invalid_access(M_READ); #ifdef WIN32 DWORD ret; if(!ReadFile(handle, buf, len, &ret, 0)) - throw SystemError("Reading from console failed", GetLastError()); + throw system_error("ReadFile"); #else int ret = ::read(handle, buf, len); if(ret==-1) @@ -149,7 +151,7 @@ unsigned Console::do_read(char *buf, unsigned len) if(errno==EAGAIN) return 0; else - throw SystemError("Reading from console failed", errno); + throw system_error("read"); } else if(ret==0) eof_flag = true; @@ -176,7 +178,7 @@ Console &Console::instance(unsigned n) case 2: return err; } - throw InvalidParameterValue("Unknown Console instance requested"); + throw invalid_argument("Console::instance"); } Console &cin = Console::instance(0); diff --git a/source/io/except.h b/source/io/except.h deleted file mode 100644 index 5770f64..0000000 --- a/source/io/except.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef MSP_IO_EXCEPT_H_ -#define MSP_IO_EXCEPT_H_ - -#include - -namespace Msp { -namespace IO { - -class FileNotFound: public Exception -{ -public: - FileNotFound(const std::string &w_, const std::string &f): Exception(w_), filename(f) { } - const std::string &get_filename() { return filename; } - ~FileNotFound() throw() { } -private: - std::string filename; -}; - -} // namespace IO -} // namespace Msp - -#endif diff --git a/source/io/file.cpp b/source/io/file.cpp index 2990d5c..727542f 100644 --- a/source/io/file.cpp +++ b/source/io/file.cpp @@ -3,8 +3,8 @@ #include #include #endif +#include #include -#include "except.h" #include "file.h" using namespace std; @@ -15,9 +15,9 @@ namespace IO { File::File(const string &fn, Mode m, CreateMode cm) { if(!(m&M_RDWR)) - throw InvalidParameterValue("Invalid read/write mode"); + throw invalid_argument("File::File mode"); if(cm&~(C_CREATE|C_TRUNCATE)) - throw InvalidParameterValue("Invalid create mode"); + throw invalid_argument("File::File create"); mode = m; @@ -45,9 +45,9 @@ File::File(const string &fn, Mode m, CreateMode cm) { int err = GetLastError(); if(err==ERROR_FILE_NOT_FOUND) - throw FileNotFound("Can't find file "+fn, fn); + throw file_not_found(fn); else - throw SystemError(format("Can't open file '%s'", fn), GetLastError()); + throw system_error(format("CreateFile(%s)", fn), err); } #else int flags = 0; @@ -76,9 +76,9 @@ File::File(const string &fn, Mode m, CreateMode cm) { int err = errno; if(err==ENOENT) - throw FileNotFound("Can't find file "+fn, fn); + throw file_not_found(fn); else - throw SystemError(format("Can't open file '%s'", fn), err); + throw system_error(format("open(%s)", fn), err); } #endif @@ -134,7 +134,7 @@ unsigned File::do_write(const char *buf, unsigned size) seek(0, S_END); DWORD ret; if(WriteFile(handle, buf, size, &ret, 0)==0) - throw SystemError("Writing to file failed", GetLastError()); + throw system_error("WriteFile"); #else int ret = ::write(handle, buf, size); if(ret==-1) @@ -142,7 +142,7 @@ unsigned File::do_write(const char *buf, unsigned size) if(errno==EAGAIN) return 0; else - throw SystemError("Writing to file failed", errno); + throw system_error("write"); } #endif @@ -159,7 +159,7 @@ unsigned File::do_read(char *buf, unsigned size) #ifdef WIN32 DWORD ret; if(ReadFile(handle, buf, size, &ret, 0)==0) - throw SystemError("Reading from file failed", GetLastError()); + throw system_error("ReadFile"); #else int ret = ::read(handle, buf, size); if(ret==-1) @@ -167,7 +167,7 @@ unsigned File::do_read(char *buf, unsigned size) if(errno==EAGAIN) return 0; else - throw SystemError("Reading from file failed", errno); + throw system_error("read"); } #endif @@ -199,11 +199,11 @@ int File::seek(int off, SeekType st) #ifdef WIN32 DWORD ret = SetFilePointer(handle, off, 0, type); if(ret==INVALID_SET_FILE_POINTER) - throw SystemError("Seek failed", GetLastError()); + throw system_error("SetFilePointer"); #else int ret = lseek(handle, off, type); if(ret==-1) - throw SystemError("Seek failed", errno); + throw system_error("lseek"); #endif eof_flag = false; @@ -218,11 +218,11 @@ int File::tell() const #ifdef WIN32 DWORD ret = SetFilePointer(handle, 0, 0, FILE_CURRENT); if(ret==INVALID_SET_FILE_POINTER) - throw SystemError("Tell failed", GetLastError()); + throw system_error("SetFilePointer"); #else int ret = lseek(handle, 0, SEEK_CUR); if(ret==-1) - throw SystemError("Tell failed", errno); + throw system_error("lseek"); #endif return ret; @@ -230,12 +230,8 @@ int File::tell() const void File::check_access(Mode m) const { - if(handle==MSP_IO_INVALID_HANDLE) - throw InvalidState("File is not open"); - if(m==M_READ && !(mode&M_READ)) - throw InvalidState("File is not readable"); - if(m==M_WRITE && !(mode&M_WRITE)) - throw InvalidState("File is not writable"); + if(handle==MSP_IO_INVALID_HANDLE || (m && !(mode&m))) + throw invalid_access(m); } } // namespace IO diff --git a/source/io/file.h b/source/io/file.h index 05aaf95..4711160 100644 --- a/source/io/file.h +++ b/source/io/file.h @@ -1,6 +1,7 @@ #ifndef MSP_IO_FILE_H_ #define MSP_IO_FILE_H_ +#include #include #include "base.h" #include "buffered.h" @@ -10,6 +11,13 @@ namespace Msp { namespace IO { +class file_not_found: public std::runtime_error +{ +public: + file_not_found(const std::string &fn): std::runtime_error(fn) { } +}; + + /** A class for reading and writing files. diff --git a/source/io/memory.cpp b/source/io/memory.cpp index 6ea130b..79956cd 100644 --- a/source/io/memory.cpp +++ b/source/io/memory.cpp @@ -1,6 +1,5 @@ #include #include -#include "except.h" #include "memory.h" using namespace std; @@ -98,10 +97,10 @@ unsigned Memory::seek(int off, SeekType type) else if(type==S_END) new_pos = end+off; else - throw InvalidParameterValue("Invalid seek type"); + throw invalid_argument("Memory::seek"); if(new_posend) - throw InvalidParameterValue("Invalid seek offset"); + throw out_of_range("Memory::seek"); pos = new_pos; return pos-begin; @@ -109,18 +108,13 @@ unsigned Memory::seek(int off, SeekType type) Handle Memory::get_event_handle() { - throw Exception("Memory doesn't support events"); + throw logic_error("Memory doesn't support events"); } void Memory::check_mode(Mode m) const { - if(m==M_WRITE) - { - if(!(mode&M_WRITE)) - throw InvalidState("Memory is not writable"); - if(pos==end) - throw InvalidState("Attempt to write past end of Memory"); - } + if(m==M_WRITE && !(mode&M_WRITE)) + throw invalid_access(M_WRITE); } } // namespace IO diff --git a/source/io/mode.cpp b/source/io/mode.cpp new file mode 100644 index 0000000..71d956b --- /dev/null +++ b/source/io/mode.cpp @@ -0,0 +1,13 @@ +#include "mode.h" + +using namespace std; + +namespace Msp { +namespace IO { + +invalid_access::invalid_access(Mode m): + logic_error(m==M_READ ? "read" : m==M_WRITE ? "write" : "generic") +{ } + +} // namespace IO +} // namespace Msp diff --git a/source/io/mode.h b/source/io/mode.h index 5e103f2..5500dff 100644 --- a/source/io/mode.h +++ b/source/io/mode.h @@ -1,6 +1,8 @@ #ifndef MSP_IO_MODE_H_ #define MSP_IO_MODE_H_ +#include + namespace Msp { namespace IO { @@ -23,6 +25,13 @@ inline Mode operator&(Mode m, Mode n) inline Mode operator~(Mode m) { return Mode(~static_cast(m)); } + +class invalid_access: public std::logic_error +{ +public: + invalid_access(Mode); +}; + } // namespace IO } // namespace Msp diff --git a/source/io/pipe.cpp b/source/io/pipe.cpp index b3735aa..afa0c25 100644 --- a/source/io/pipe.cpp +++ b/source/io/pipe.cpp @@ -2,6 +2,7 @@ #include #include #endif +#include #include #include "pipe.h" @@ -16,14 +17,14 @@ Pipe::Pipe() string name = format("\\\\.\\pipe\\%u.%p", GetCurrentProcessId(), this); handle[0] = CreateNamedPipe(name.c_str(), PIPE_ACCESS_INBOUND|FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, 0); if(handle[0]==INVALID_HANDLE_VALUE) - throw SystemError("Unable to create pipe", GetLastError()); + throw system_error("CreateNamedPipe"); handle[1] = CreateFile(name.c_str(), GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if(handle[1]==INVALID_HANDLE_VALUE) { unsigned err = GetLastError(); CloseHandle(handle[0]); - throw SystemError("Unable to create pipe", err); + throw system_error(format("CreateFile(%s)", name), err); } overlapped = 0; @@ -34,7 +35,7 @@ Pipe::Pipe() buf_next = buffer; #else if(pipe(handle)==-1) - throw SystemError("Unable to create pipe", errno); + throw system_error("pipe"); #endif set_events(P_INPUT); @@ -82,7 +83,7 @@ unsigned Pipe::do_write(const char *buf, unsigned size) #ifdef WIN32 DWORD ret; if(!WriteFile(handle[1], buf, size, &ret, 0)) - throw SystemError("Writing to pipe failed", GetLastError()); + throw system_error("WriteFile"); #else int ret = ::write(handle[1], buf, size); if(ret==-1) @@ -90,7 +91,7 @@ unsigned Pipe::do_write(const char *buf, unsigned size) if(errno==EAGAIN) return 0; else - throw SystemError("Writing to pipe failed", errno); + throw system_error("write"); } #endif @@ -110,7 +111,7 @@ unsigned Pipe::do_read(char *buf, unsigned size) { DWORD ret; if(!GetOverlappedResult(handle[0], overlapped, &ret, !buf_avail)) - throw SystemError("Reading from pipe failed", GetLastError()); + throw system_error("GetOverlappedResult"); else { buf_avail += ret; @@ -133,7 +134,7 @@ unsigned Pipe::do_read(char *buf, unsigned size) if(errno==EAGAIN) return 0; else - throw SystemError("Reading from pipe failed", errno); + throw system_error("read"); } #endif @@ -161,7 +162,7 @@ Handle Pipe::get_event_handle() { unsigned err = GetLastError(); if(err!=ERROR_IO_PENDING) - throw SystemError("Failed to start an overlapped read", err); + throw system_error("ReadFile"); } else { diff --git a/source/io/poll.cpp b/source/io/poll.cpp index dce1912..a0ccf84 100644 --- a/source/io/poll.cpp +++ b/source/io/poll.cpp @@ -1,10 +1,13 @@ #include +#include +#include #include #include -#include "except.h" #include "base.h" #include "poll.h" +using namespace std; + namespace { using namespace Msp; @@ -15,7 +18,7 @@ inline int sys_poll_event(PollEvent event) int result = 0; if(event&~(P_INPUT|P_PRIO|P_OUTPUT)) - throw InvalidParameterValue("Invalid poll events"); + throw invalid_argument("sys_poll_event"); #ifndef WIN32 if(event&P_INPUT) @@ -60,7 +63,7 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) if(ret==WAIT_OBJECT_0) return pe; else if(ret==WAIT_FAILED) - throw SystemError("Poll failed", GetLastError()); + throw system_error("WaitForSingleObject"); return P_NONE; #else @@ -72,7 +75,7 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) if(errno==EINTR) return P_NONE; else - throw SystemError("Poll failed", errno); + throw system_error("poll"); } return poll_event_from_sys(pfd.revents); @@ -108,7 +111,7 @@ void Poller::set_object(Base &obj, PollEvent ev) { #ifdef WIN32 if(objects.size()>=MAXIMUM_WAIT_OBJECTS) - throw InvalidState("Maximum number of wait objects reached"); + throw logic_error("Maximum number of wait objects reached"); #endif objects.insert(SlotMap::value_type(&obj, Slot(&obj, ev))); @@ -124,7 +127,7 @@ int Poller::poll() int Poller::poll(const Time::TimeDelta &timeout) { if(timeout(timeout/Time::msec)); } @@ -168,7 +171,7 @@ int Poller::do_poll(int timeout) return 1; } else if(ret==WAIT_FAILED) - throw SystemError("Poll failed", GetLastError()); + throw system_error("WaitForMultipleObjects"); return 0; #else @@ -178,7 +181,7 @@ int Poller::do_poll(int timeout) if(errno==EINTR) return 0; else - throw SystemError("Poll failed", errno); + throw system_error("poll"); } int n = ret; @@ -203,7 +206,7 @@ PollEvent poll(Base &obj, PollEvent pe) PollEvent poll(Base &obj, PollEvent pe, const Time::TimeDelta &timeout) { if(timeout(timeout/Time::msec)); } diff --git a/source/io/seek.cpp b/source/io/seek.cpp index b10c5a0..c0b65ca 100644 --- a/source/io/seek.cpp +++ b/source/io/seek.cpp @@ -1,9 +1,11 @@ #ifdef WIN32 #include #endif -#include "except.h" +#include #include "seek.h" +using namespace std; + namespace Msp { namespace IO { @@ -25,7 +27,7 @@ int sys_seek_type(SeekType st) return SEEK_END; #endif - throw InvalidParameterValue("Invalid seek type"); + throw invalid_argument("Invalid seek type"); } } // namespace IO diff --git a/source/io/serial.cpp b/source/io/serial.cpp index ec6a198..dbfee95 100644 --- a/source/io/serial.cpp +++ b/source/io/serial.cpp @@ -5,8 +5,8 @@ #include #include #endif +#include #include -#include "except.h" #include "serial.h" using namespace std; @@ -35,10 +35,10 @@ void set_state(Handle handle, DeviceState &state) { #ifdef WIN32 if(SetCommState(handle, &state)==0) - throw SystemError("Cannot set serial port parameters", GetLastError()); + throw system_error("SetCommState"); #else if(tcsetattr(handle, TCSADRAIN, &state)==-1) - throw SystemError("Cannot set serial port parameters", errno); + throw system_error("tcsetattr"); #endif } @@ -69,7 +69,7 @@ void set_baud_rate(DeviceState &state, unsigned baud) case 57600: speed = B57600; break; case 115200: speed = B115200; break; case 230400: speed = B230400; break; - default: throw InvalidParameterValue("Invalid baud rate"); + default: throw invalid_argument("set_baud_rate"); } cfsetospeed(&state, speed); @@ -89,7 +89,7 @@ void set_data_bits(DeviceState &state, unsigned bits) case 6: flag = CS6; break; case 7: flag = CS7; break; case 8: flag = CS8; break; - default: throw InvalidParameterValue("Invalid data bit count"); + default: throw invalid_argument("set_data_bits"); } state.c_cflag = (state.c_cflag&~CSIZE)|flag; @@ -104,7 +104,7 @@ void set_parity(DeviceState &state, Serial::Parity par) case Serial::NONE: state.Parity = NOPARITY; break; case Serial::EVEN: state.Parity = EVENPARITY; break; case Serial::ODD: state.Parity = ODDPARITY; break; - default: throw InvalidParameterValue("Invalid parity"); + default: throw invalid_argument("set_parity"); } #else tcflag_t flag; @@ -113,7 +113,7 @@ void set_parity(DeviceState &state, Serial::Parity par) case Serial::NONE: flag = 0; break; case Serial::EVEN: flag = PARENB; break; case Serial::ODD: flag = PARENB|PARODD; break; - default: throw InvalidParameterValue("Invalid parity"); + default: throw invalid_argument("set_parity"); } state.c_cflag = (state.c_cflag&~(PARENB|PARODD))|flag; @@ -127,7 +127,7 @@ void set_stop_bits(DeviceState &state, unsigned bits) { case 1: state.StopBits = ONESTOPBIT; break; case 2: state.StopBits = TWOSTOPBITS; break; - default: throw InvalidParameterValue("Invalid stop bit count"); + default: throw invalid_argument("set_stop_bits"); } #else tcflag_t flag; @@ -135,7 +135,7 @@ void set_stop_bits(DeviceState &state, unsigned bits) { case 1: flag = 0; break; case 2: flag = CSTOPB; break; - default: throw InvalidParameterValue("Invalid stop bit count"); + default: throw invalid_argument("set_stop_bits"); } state.c_cflag = (state.c_cflag&~CSTOPB)|flag; @@ -158,7 +158,7 @@ Serial::Serial(const string &descr) handle = CreateFile(port.c_str(), GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if(handle==INVALID_HANDLE_VALUE) - throw SystemError(format("Can't open serial port '%s'", port), GetLastError()); + throw system_error(format("CreateFile(%s)", port)); mode = M_READ|M_WRITE; COMMTIMEOUTS timeouts; @@ -174,7 +174,7 @@ Serial::Serial(const string &descr) handle = open(port.c_str(), O_RDWR); if(handle==-1) - throw SystemError(format("Can't open serial port '%s'", port), errno); + throw system_error(format("open(%s)", port)); mode = M_READ|M_WRITE; termios t; @@ -264,13 +264,13 @@ void Serial::set_parameters(const string ¶ms) unsigned i; for(i=0; i'8') - throw InvalidParameterValue("Invalid data bit count"); + throw invalid_argument("Serial::set_parameters data_bits"); if(params[i+2]!='N' && params[i+2]!='E' && params[i+2]!='O') - throw InvalidParameterValue("Invalid parity"); + throw invalid_argument("Serial::set_parameters parity"); if(params[i+3]!='1' && params[i+3]!='2') - throw InvalidParameterValue("Invalid stop bit count"); + throw invalid_argument("Serial::set_parameters stop_bits"); DeviceState state; get_state(handle, state); @@ -289,7 +289,7 @@ unsigned Serial::do_write(const char *buf, unsigned size) #ifdef WIN32 DWORD ret; if(WriteFile(handle, buf, size, &ret, 0)==0) - throw SystemError("Writing to serial port failed", GetLastError()); + throw system_error("WriteFile"); #else int ret = ::write(handle, buf, size); if(ret==-1) @@ -297,7 +297,7 @@ unsigned Serial::do_write(const char *buf, unsigned size) if(errno==EAGAIN) return 0; else - throw SystemError("Writing to serial port failed", errno); + throw system_error("write"); } #endif @@ -312,7 +312,7 @@ unsigned Serial::do_read(char *buf, unsigned size) #ifdef WIN32 DWORD ret; if(ReadFile(handle, buf, size, &ret, 0)==0) - throw SystemError("Reading from serial port failed", GetLastError()); + throw system_error("ReadFile"); #else int ret = ::read(handle, buf, size); if(ret==-1) @@ -320,7 +320,7 @@ unsigned Serial::do_read(char *buf, unsigned size) if(errno==EAGAIN) return 0; else - throw SystemError("Reading from serial port failed", errno); + throw system_error("read"); } #endif @@ -330,7 +330,7 @@ unsigned Serial::do_read(char *buf, unsigned size) Handle Serial::get_event_handle() { #ifdef WIN32 - throw Exception("Serial port events not supported on win32 yet"); + throw logic_error("Serial port events not supported on win32 yet"); #else return handle; #endif -- 2.43.0 From 86e0004bd195bc7f7478cf736871339bddf38127 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 11 Jun 2011 00:01:02 +0300 Subject: [PATCH 13/16] Add an intermediate Seekable interface class --- source/io/file.cpp | 12 +++++----- source/io/file.h | 12 ++++------ source/io/memory.h | 9 ++++--- source/io/seek.h | 19 --------------- source/io/{seek.cpp => seekable.cpp} | 4 ++-- source/io/seekable.h | 35 ++++++++++++++++++++++++++++ 6 files changed, 51 insertions(+), 40 deletions(-) delete mode 100644 source/io/seek.h rename source/io/{seek.cpp => seekable.cpp} (87%) create mode 100644 source/io/seekable.h diff --git a/source/io/file.cpp b/source/io/file.cpp index 727542f..74930ba 100644 --- a/source/io/file.cpp +++ b/source/io/file.cpp @@ -189,7 +189,7 @@ void File::sync() #endif } -int File::seek(int off, SeekType st) +unsigned File::seek(int off, SeekType st) { check_access(M_NONE); @@ -201,8 +201,8 @@ int File::seek(int off, SeekType st) if(ret==INVALID_SET_FILE_POINTER) throw system_error("SetFilePointer"); #else - int ret = lseek(handle, off, type); - if(ret==-1) + off_t ret = lseek(handle, off, type); + if(ret==(off_t)-1) throw system_error("lseek"); #endif @@ -211,7 +211,7 @@ int File::seek(int off, SeekType st) return ret; } -int File::tell() const +unsigned File::tell() const { check_access(M_NONE); @@ -220,8 +220,8 @@ int File::tell() const if(ret==INVALID_SET_FILE_POINTER) throw system_error("SetFilePointer"); #else - int ret = lseek(handle, 0, SEEK_CUR); - if(ret==-1) + off_t ret = lseek(handle, 0, SEEK_CUR); + if(ret==(off_t)-1) throw system_error("lseek"); #endif diff --git a/source/io/file.h b/source/io/file.h index 4711160..d59cd57 100644 --- a/source/io/file.h +++ b/source/io/file.h @@ -3,10 +3,9 @@ #include #include -#include "base.h" #include "buffered.h" #include "filtered.h" -#include "seek.h" +#include "seekable.h" namespace Msp { namespace IO { @@ -23,7 +22,7 @@ A class for reading and writing files. Non-blocking mode is not supported on Win32. */ -class File: public Base +class File: public Seekable { public: enum CreateMode @@ -56,11 +55,8 @@ protected: public: virtual void sync(); - /** Changes the read/write offset of the file. Returns the new offset. */ - virtual int seek(int, SeekType); - - /** Returns the current read/write offset of the file. */ - virtual int tell() const; + virtual unsigned seek(int, SeekType); + virtual unsigned tell() const; virtual Handle get_event_handle() { return handle; } diff --git a/source/io/memory.h b/source/io/memory.h index ba6c4d8..27fd6cb 100644 --- a/source/io/memory.h +++ b/source/io/memory.h @@ -1,13 +1,12 @@ #ifndef MSP_IO_MEMORY_H_ #define MSP_IO_MEMORY_H_ -#include "base.h" -#include "seek.h" +#include "seekable.h" namespace Msp { namespace IO { -class Memory: public Base +class Memory: public Seekable { private: char *begin; @@ -29,8 +28,8 @@ public: virtual bool getline(std::string &); virtual int get(); - unsigned seek(int, SeekType); - unsigned tell() const { return pos-begin; } + virtual unsigned seek(int, SeekType); + virtual unsigned tell() const { return pos-begin; } virtual Handle get_event_handle(); diff --git a/source/io/seek.h b/source/io/seek.h deleted file mode 100644 index 3c6c331..0000000 --- a/source/io/seek.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef MSP_IO_SEEK_H_ -#define MSP_IO_SEEK_H_ - -namespace Msp { -namespace IO { - -enum SeekType -{ - S_BEG, - S_CUR, - S_END -}; - -extern int sys_seek_type(SeekType); - -} // namespace IO -} // namespace Msp - -#endif diff --git a/source/io/seek.cpp b/source/io/seekable.cpp similarity index 87% rename from source/io/seek.cpp rename to source/io/seekable.cpp index c0b65ca..101676e 100644 --- a/source/io/seek.cpp +++ b/source/io/seekable.cpp @@ -2,7 +2,7 @@ #include #endif #include -#include "seek.h" +#include "seekable.h" using namespace std; @@ -27,7 +27,7 @@ int sys_seek_type(SeekType st) return SEEK_END; #endif - throw invalid_argument("Invalid seek type"); + throw invalid_argument("sys_seek_type"); } } // namespace IO diff --git a/source/io/seekable.h b/source/io/seekable.h new file mode 100644 index 0000000..cabb9dc --- /dev/null +++ b/source/io/seekable.h @@ -0,0 +1,35 @@ +#ifndef MSP_IO_SEEKABLE_H_ +#define MSP_IO_SEEKABLE_H_ + +#include "base.h" + +namespace Msp { +namespace IO { + +enum SeekType +{ + S_BEG, + S_CUR, + S_END +}; + +int sys_seek_type(SeekType); + + +class Seekable: public Base +{ +protected: + Seekable() { } + +public: + /** Changes the read/write offset. Returns the new offset. */ + virtual unsigned seek(int, SeekType) = 0; + + /** Returns the current read/write offset. */ + virtual unsigned tell() const = 0; +}; + +} // namespace IO +} // namespace Msp + +#endif -- 2.43.0 From d4d2018e1ba971e57eb2d8fee022b70a9c33d2e5 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 11 Jun 2011 13:41:25 +0300 Subject: [PATCH 14/16] Further style fixes Header updates --- source/io/buffered.cpp | 2 +- source/io/poll.cpp | 10 +++++----- source/io/poll.h | 7 ++++--- source/io/serial.cpp | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/source/io/buffered.cpp b/source/io/buffered.cpp index f725223..5dbd494 100644 --- a/source/io/buffered.cpp +++ b/source/io/buffered.cpp @@ -40,7 +40,7 @@ void Buffered::flush() { unsigned len = below.write(begin, used); - begin=end = buf; + begin = end = buf; if(len +#include #include #include -#include +#include #include #include "base.h" #include "poll.h" @@ -37,8 +37,7 @@ inline PollEvent poll_event_from_sys(int event) PollEvent result = P_NONE; #ifdef WIN32 - // Stop the compiler from complaining about unused parameter - event = event; + (void)event; #else if(event&POLLIN) result = result|P_INPUT; @@ -67,7 +66,7 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) return P_NONE; #else - pollfd pfd = {obj.get_event_handle(), sys_poll_event(pe), 0}; + pollfd pfd = { obj.get_event_handle(), sys_poll_event(pe), 0 }; int ret = ::poll(&pfd, 1, timeout); if(ret==-1) @@ -84,6 +83,7 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) } + namespace Msp { namespace IO { diff --git a/source/io/poll.h b/source/io/poll.h index 6367d8f..5952374 100644 --- a/source/io/poll.h +++ b/source/io/poll.h @@ -61,15 +61,16 @@ private: bool pfd_dirty; SlotSeq poll_result; - void rebuild_pfd(); - int do_poll(int); - public: Poller(); void set_object(Base &, PollEvent); int poll(); int poll(const Time::TimeDelta &); +private: + void rebuild_pfd(); + int do_poll(int); +public: const SlotSeq &get_result() const { return poll_result; } }; diff --git a/source/io/serial.cpp b/source/io/serial.cpp index dbfee95..5d5871e 100644 --- a/source/io/serial.cpp +++ b/source/io/serial.cpp @@ -5,8 +5,8 @@ #include #include #endif +#include #include -#include #include "serial.h" using namespace std; -- 2.43.0 From e46de55d3c8f65d3b0eeaee76247476695e9eb7c Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 11 Jun 2011 14:01:43 +0300 Subject: [PATCH 15/16] Use pimpl in Poller --- source/io/eventdispatcher.cpp | 4 +- source/io/poll.cpp | 70 ++++++++++++++++++++++------------- source/io/poll.h | 27 +++++--------- 3 files changed, 55 insertions(+), 46 deletions(-) diff --git a/source/io/eventdispatcher.cpp b/source/io/eventdispatcher.cpp index 06a594f..1583597 100644 --- a/source/io/eventdispatcher.cpp +++ b/source/io/eventdispatcher.cpp @@ -66,8 +66,8 @@ void EventDispatcher::object_deleted(Base *obj) void EventDispatcher::dispatch() { - const Poller::SlotSeq &result = poller.get_result(); - for(Poller::SlotSeq::const_iterator i=result.begin(); i!=result.end(); ++i) + const Poller::SlotList &result = poller.get_result(); + for(Poller::SlotList::const_iterator i=result.begin(); i!=result.end(); ++i) i->object->event(i->events); } diff --git a/source/io/poll.cpp b/source/io/poll.cpp index d610665..d78a2c0 100644 --- a/source/io/poll.cpp +++ b/source/io/poll.cpp @@ -1,5 +1,8 @@ #include #include +#ifndef WIN32 +#include +#endif #include #include #include @@ -87,8 +90,19 @@ inline PollEvent do_poll(Base &obj, PollEvent pe, int timeout) namespace Msp { namespace IO { +struct Poller::Private +{ +#ifdef WIN32 + vector handles; +#else + vector pfd; +#endif +}; + + Poller::Poller(): - pfd_dirty(false) + priv(new Private), + objs_changed(false) { } void Poller::set_object(Base &obj, PollEvent ev) @@ -97,15 +111,15 @@ void Poller::set_object(Base &obj, PollEvent ev) if(ev) obj.get_event_handle(); - SlotMap::iterator i = objects.find(&obj); + EventMap::iterator i = objects.find(&obj); if(i!=objects.end()) { if(ev) - i->second.events = ev; + i->second = ev; else objects.erase(i); - pfd_dirty = true; + objs_changed = true; } else if(ev) { @@ -113,9 +127,9 @@ void Poller::set_object(Base &obj, PollEvent ev) if(objects.size()>=MAXIMUM_WAIT_OBJECTS) throw logic_error("Maximum number of wait objects reached"); #endif - objects.insert(SlotMap::value_type(&obj, Slot(&obj, ev))); + objects.insert(EventMap::value_type(&obj, ev)); - pfd_dirty = true; + objs_changed = true; } } @@ -132,28 +146,32 @@ int Poller::poll(const Time::TimeDelta &timeout) return do_poll(static_cast(timeout/Time::msec)); } -void Poller::rebuild_pfd() +void Poller::rebuild_array() { - pfd.clear(); +#ifdef WIN32 + priv->handles.clear(); - pollfd p; + for(EventMap::iterator i=objects.begin(); i!=objects.end(); ++i) + priv->handles.push_back(i->first->get_event_handle()); +#else + priv->pfd.clear(); - for(SlotMap::iterator i=objects.begin(); i!=objects.end(); ++i) + for(EventMap::iterator i=objects.begin(); i!=objects.end(); ++i) { - p.fd = i->second.object->get_event_handle(); -#ifndef WIN32 - p.events = sys_poll_event(i->second.events); -#endif - pfd.push_back(p); + pollfd p; + p.fd = i->first->get_event_handle(); + p.events = sys_poll_event(i->second); + priv->pfd.push_back(p); } +#endif - pfd_dirty = false; + objs_changed = false; } int Poller::do_poll(int timeout) { - if(pfd_dirty) - rebuild_pfd(); + if(objs_changed) + rebuild_array(); poll_result.clear(); @@ -161,12 +179,12 @@ int Poller::do_poll(int timeout) if(timeout<0) timeout = INFINITE; - DWORD ret = WaitForMultipleObjects(pfd.size(), &pfd.front().fd, false, timeout); - if(/*ret>=WAIT_OBJECT_0 &&*/ rethandles.size(), &priv->handles.front(), false, timeout); + if(/*ret>=WAIT_OBJECT_0 &&*/ rethandles.size()) { - SlotMap::iterator i = objects.begin(); + EventMap::iterator i = objects.begin(); advance(i, ret-WAIT_OBJECT_0); - poll_result.push_back(Slot(i->second.object, i->second.events)); + poll_result.push_back(Slot(i->first, i->second)); return 1; } @@ -175,7 +193,7 @@ int Poller::do_poll(int timeout) return 0; #else - int ret = ::poll(&pfd.front(), pfd.size(), timeout); + int ret = ::poll(&priv->pfd.front(), priv->pfd.size(), timeout); if(ret==-1) { if(errno==EINTR) @@ -185,11 +203,11 @@ int Poller::do_poll(int timeout) } int n = ret; - SlotMap::iterator j = objects.begin(); - for(std::vector::iterator i=pfd.begin(); (i!=pfd.end() && n>0); ++i,++j) + EventMap::iterator j = objects.begin(); + for(vector::iterator i=priv->pfd.begin(); (i!=priv->pfd.end() && n>0); ++i, ++j) if(i->revents) { - poll_result.push_back(Slot(j->second.object, poll_event_from_sys(i->revents))); + poll_result.push_back(Slot(j->first, poll_event_from_sys(i->revents))); --n; } diff --git a/source/io/poll.h b/source/io/poll.h index 5952374..f59b499 100644 --- a/source/io/poll.h +++ b/source/io/poll.h @@ -1,14 +1,10 @@ #ifndef MSP_IO_POLL_H_ #define MSP_IO_POLL_H_ -#ifndef WIN32 -#include -#endif #include #include #include #include -#include "types.h" namespace Msp { namespace IO { @@ -45,21 +41,16 @@ public: Slot(Base *o, PollEvent e): object(o), events(e) { } }; - typedef std::list SlotSeq; + typedef std::list SlotList; private: - typedef std::map SlotMap; + typedef std::map EventMap; -#ifdef WIN32 - struct pollfd - { - Handle fd; - }; -#endif + struct Private; - SlotMap objects; - std::vector pfd; - bool pfd_dirty; - SlotSeq poll_result; + EventMap objects; + Private *priv; + bool objs_changed; + SlotList poll_result; public: Poller(); @@ -68,10 +59,10 @@ public: int poll(); int poll(const Time::TimeDelta &); private: - void rebuild_pfd(); + void rebuild_array(); int do_poll(int); public: - const SlotSeq &get_result() const { return poll_result; } + const SlotList &get_result() const { return poll_result; } }; PollEvent poll(Base &, PollEvent); -- 2.43.0 From 3b8384a993aed55b348bf51bb02900b3aa010ef8 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 11 Jun 2011 14:41:09 +0300 Subject: [PATCH 16/16] Add a pimpl Handle class --- source/io/handle.cpp | 53 ++++++++++++++++++++++++++++++++++++++ source/io/handle.h | 33 ++++++++++++++++++++++++ source/io/handle_private.h | 31 ++++++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 source/io/handle.cpp create mode 100644 source/io/handle.h create mode 100644 source/io/handle_private.h diff --git a/source/io/handle.cpp b/source/io/handle.cpp new file mode 100644 index 0000000..d5183e5 --- /dev/null +++ b/source/io/handle.cpp @@ -0,0 +1,53 @@ +#include "handle.h" +#include "handle_private.h" + +namespace Msp { +namespace IO { + +Handle::Handle(): + priv(new Private) +{ } + +Handle::Handle(const Handle &other): + priv(new Private) +{ + priv->handle = other.priv->handle; +} + +Handle &Handle::operator=(const Handle &other) +{ + priv->handle = other.priv->handle; + return *this; +} + +Handle::~Handle() +{ + delete priv; +} + +Handle::operator const void *() const +{ +#ifdef WIN32 + return priv->handle!=INVALID_HANDLE_VALUE ? this : 0; +#else + return priv->handle!=-1 ? this : 0; +#endif +} + + +Handle::Private::Private(): +#ifdef WIN32 + handle(INVALID_HANDLE_VALUE) +#else + handle(-1) +#endif +{ } + +Handle::Private &Handle::Private::operator=(H h) +{ + handle = h; + return *this; +} + +} // namespace IO +} // namespace Msp diff --git a/source/io/handle.h b/source/io/handle.h new file mode 100644 index 0000000..44b5937 --- /dev/null +++ b/source/io/handle.h @@ -0,0 +1,33 @@ +#ifndef MSP_IO_HANDLE_H_ +#define MSP_IO_HANDLE_H_ + +namespace Msp { +namespace IO { + +class Handle +{ +public: + struct Private; + +private: + Private *priv; + +public: + Handle(); + Handle(const Handle &); + Handle &operator=(const Handle &); + ~Handle(); + + Private &operator*() { return *priv; } + const Private &operator*() const { return *priv; } + + /** This is effectively a boolean conversion, but avoids accidental + conversion to OS native handles. Unix-based systems use int and win32 uses + void *; const void * is not implicitly convertible to either. */ + operator const void *() const; +}; + +} // namespace IO +} // namespace Msp + +#endif diff --git a/source/io/handle_private.h b/source/io/handle_private.h new file mode 100644 index 0000000..d73a2b8 --- /dev/null +++ b/source/io/handle_private.h @@ -0,0 +1,31 @@ +#ifndef MSP_IO_HANDLE_PRIVATE_H_ +#define MSP_IO_HANDLE_PRIVATE_H_ + +#ifdef WIN32 +#include +#endif +#include "handle.h" + +namespace Msp { +namespace IO { + +struct Handle::Private +{ +#ifdef WIN32 + typedef HANDLE H; +#else + typedef int H; +#endif + + H handle; + + Private(); + + Private &operator=(H); + operator H() const { return handle; } +}; + +} // namespace IO +} // namespace Msp + +#endif -- 2.43.0