28 #ifndef _ZUPPLY_ZUPPLY_HPP_
29 #define _ZUPPLY_ZUPPLY_HPP_
34 #if ((defined(_MSC_VER) && _MSC_VER >= 1800) || __cplusplus >= 201103L)
37 #error C++11 required, add -std=c++11 to CFLAG.
49 #define __func__ __FUNCTION__
53 #if (!defined(_DEBUG) && !defined(NDEBUG))
58 #define ZUPPLY_NOEXCEPT throw()
63 #ifndef ZUPPLY_NOEXCEPT
64 #define ZUPPLY_NOEXCEPT noexcept
68 #ifdef ZUPPLY_HEADER_ONLY
69 #define ZUPPLY_EXPORT inline
87 #include <unordered_map>
89 #include <type_traits>
112 static const char* kExceptionPrefixGeneral =
"[Zupply Exception] ";
113 static const char* kExceptionPrefixLogic =
"[Zupply Exception->Logic] ";
114 static const char* kExceptionPrefixArgument =
"[Zupply Exception->Logic->Argument] ";
115 static const char* kExceptionPrefixRuntime =
"[Zupply Exception->Runtime] ";
116 static const char* kExceptionPrefixIO =
"[Zupply Exception->Runtime->IO] ";
117 static const char* kExceptionPrefixCast =
"[Zupply Exception->Runtime->Cast] ";
118 static const char* kExceptionPrefixMemory =
"[Zupply Exception->Runtime->Memory] ";
119 static const char* kExceptionPrefixStrictWarn =
"[Zupply Exception->StrictWarn] ";
164 explicit Exception(
const char* message,
const char* prefix = consts::kExceptionPrefixGeneral)
166 message_ = std::string(prefix) + message;
168 explicit Exception(
const std::string message,
const char* prefix = consts::kExceptionPrefixGeneral)
170 message_ = std::string(prefix) + message;
174 const char* what()
const ZUPPLY_NOEXCEPT{
return message_.c_str(); };
176 std::string message_;
200 explicit ArgException(
const std::string &message) :
Exception(message, consts::kExceptionPrefixArgument){};
236 explicit IOException(
const std::string &message) :
Exception(message, consts::kExceptionPrefixIO){};
248 explicit MemException(
const std::string &message) :
Exception(message, consts::kExceptionPrefixMemory){};
260 explicit WarnException(
const std::string &message) :
Exception(message, consts::kExceptionPrefixStrictWarn){};
271 typedef _Tp value_type;
283 Size_(_Tp width, _Tp height);
320 template<
typename _Tp2>
operator Size_<_Tp2>()
const;
354 typedef _Tp value_type;
445 template<
typename _Tp>
class Rect_
448 typedef _Tp value_type;
462 Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
518 template<
typename _Tp2>
operator Rect_<_Tp2>()
const;
559 typedef _Tp value_type;
596 void create(
int rows,
int cols,
int channels);
624 _Tp&
operator() (
int row,
int col,
int channel = 0);
633 const _Tp&
operator() (
int row,
int col,
int channel = 0)
const;
672 _Tp
at(
int row,
int col,
int channel = 0)
const;
681 _Tp*
ptr(
int offset = 0)
const;
692 _Tp*
ptr(
int row,
int col,
int channel = 0)
const;
719 std::vector<_Tp> export_raw()
const;
724 template <
typename _Tp2> std::vector<_Tp2>& export_raw(std::vector<_Tp2>& out)
const;
733 void crop(
int r0,
int c0,
int r1,
int c1);
740 void crop(Point p0, Point p1);
746 void crop(Rect rect);
749 void range_check(
long long pos)
const;
750 void range_check(
int row,
int col,
int channel)
const;
756 std::shared_ptr<std::vector<_Tp>> data_;
786 Image(
const char* filename);
792 void load(
const char* filename);
799 void save(
const char* filename,
int quality = 80)
const;
812 void resize(
int width,
int height);
818 void resize(
double ratio);
858 void load(
const char* filename);
864 void save_hdr(
const char* filename)
const;
891 void resize(
int width,
int height);
897 void resize(
double ratio);
920 template<
class T>
inline const T
clip(
const T& value,
const T& low,
const T& high)
923 T h = (std::max)(low, high);
924 T l = (std::min)(low, high);
925 return (std::max)((std::min)(value, h), l);
932 template <
unsigned long B,
unsigned long E>
935 static const unsigned long result = B *
Pow<B, E - 1>::result;
938 template <
unsigned long B>
941 static const unsigned long result = 1;
953 #if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__) && 0
954 __m128d t = _mm_set_sd(value);
955 return _mm_cvtsd_si32(t);
956 #elif defined _MSC_VER && defined _M_IX86
964 #elif defined _MSC_VER && defined _M_ARM && defined HAVE_TEGRA_OPTIMIZATION
966 #elif defined CV_ICC || defined __GNUC__
967 # ifdef HAVE_TEGRA_OPTIMIZATION
970 return (
int)lrint(value);
973 double intpart, fractpart;
974 fractpart = modf(value, &intpart);
975 if ((fabs(fractpart) != 0.5) || ((((
int)intpart) % 2) != 0))
976 return (
int)(value + (value >= 0 ? 0.5 : -0.5));
1003 template <
typename T>
1004 auto is_iterable_impl(
int)
1006 begin(std::declval<T&>()) != end(std::declval<T&>()),
1007 ++std::declval<decltype(begin(std::declval<T&>()))&>(),
1008 *begin(std::declval<T&>()),
1011 template <
typename T>
1012 std::false_type is_iterable_impl(...);
1016 template <
typename T>
1017 using is_iterable = decltype(detail::is_iterable_impl<T>(0));
1025 Callback(std::function<
void()> f) : f_(f) { f_(); }
1027 std::function<void()> f_;
1037 inline void nop_pause()
1039 #if (defined _MSC_VER) && (defined _M_IX86 || defined _M_X64) && 0
1040 __asm
volatile(
"pause" :::
"memory");
1054 bool try_lock() {
return true; }
1068 while (flag_.test_and_set(std::memory_order_acquire))
1074 inline void unlock()
1076 flag_.clear(std::memory_order_release);
1079 inline bool try_lock()
1081 return !flag_.test_and_set(std::memory_order_acquire);
1084 std::atomic_flag flag_;
1093 enum class LockType {
1112 LockType get_lock_type()
const;
1116 friend RWLock::~RWLock();
1122 uint8_t writeClaim_;
1125 bool is_waiting_for_write()
const;
1126 bool is_waiting_for_read()
const;
1127 bool is_my_turn_to_write(Counters
const & claim)
const;
1129 bool want_to_read(Counters * buf)
const;
1130 bool want_to_write(Counters * buf)
const;
1131 Counters done_reading()
const;
1132 Counters done_writing()
const;
1135 std::atomic<Counters> counters_;
1138 void unlock_write();
1143 bool is_lock_free()
const;
1151 using MapType = std::unordered_map<Key, Value>;
1152 using MapPairType = std::pair<Key, Value>;
1156 bool is_lock_free()
const
1158 return lockable_.is_lock_free();
1161 bool contains(
const Key& key)
1163 auto lock = lockable_.lock_for_read();
1164 return map_.count(key) > 0;
1167 bool get(
const Key& key, Value& dst)
1169 auto lock = lockable_.lock_for_read();
1170 if (map_.count(key) > 0)
1180 auto lock = lockable_.lock_for_read();
1184 bool insert(
const Key& key,
const Value& value)
1186 if (contains(key))
return false;
1187 auto lock = lockable_.lock_for_write();
1192 bool insert(
const MapPairType& pair)
1194 return insert(pair.first, pair.second);
1197 void replace(
const Key& key,
const Value& value)
1199 auto lock = lockable_.lock_for_write();
1203 void replace(
const MapPairType& pair)
1205 replace(pair.first, pair.second);
1208 void erase(
const Key& key)
1210 auto lock = lockable_.lock_for_write();
1216 auto lock = lockable_.lock_for_write();
1238 bool is_lock_free()
const
1240 return lockable_.is_lock_free();
1245 auto lock = lockable_.lock_for_read();
1249 void set(
const T& t)
1252 auto lock = lockable_.lock_for_write();
1268 using MapType = std::unordered_map<Key, Value>;
1269 using MapPairType = std::pair<Key, Value>;
1273 bool is_lock_free()
const
1278 bool contains(
const Key& key)
1280 std::lock_guard<std::mutex> lock(mutex_);
1281 return map_.count(key) > 0;
1284 bool get(
const Key& key, Value& dst)
1286 std::lock_guard<std::mutex> lock(mutex_);
1287 if (map_.count(key) > 0)
1297 std::lock_guard<std::mutex> lock(mutex_);
1301 bool insert(
const Key& key,
const Value& value)
1303 if (contains(key))
return false;
1304 std::lock_guard<std::mutex> lock(mutex_);
1309 bool insert(
const MapPairType& pair)
1311 return insert(pair.first, pair.second);
1314 void replace(
const Key& key,
const Value& value)
1316 std::lock_guard<std::mutex> lock(mutex_);
1320 void replace(
const MapPairType& pair)
1322 replace(pair.first, pair.second);
1325 void erase(
const Key& key)
1327 std::lock_guard<std::mutex> lock(mutex_);
1333 std::lock_guard<std::mutex> lock(mutex_);
1355 bool is_lock_free()
const
1362 std::lock_guard<std::mutex> lock(mutex_);
1366 void set(
const T& t)
1368 std::lock_guard<std::mutex> lock(mutex_);
1633 int system(
const char *
const command,
const char *
const module_name = 0);
1662 std::tm
gmtime(std::time_t t);
1684 bool path_exists(std::string path,
bool considerFile =
true);
1691 bool is_file(std::string path);
1707 void fstream_open(std::fstream &stream, std::string filename, std::ios::openmode openmode);
1716 void ifstream_open(std::ifstream &stream, std::string filename, std::ios::openmode openmode);
1724 bool rename(std::string oldName, std::string newName);
1733 bool copyfile(std::string src, std::string dst,
bool replaceDst =
false);
1742 bool movefile(std::string src, std::string dst,
bool replaceDst =
false);
1759 bool remove_dir(std::string root,
bool recursive =
true);
1806 std::vector<std::string>
path_split(std::string path);
1816 bool path_identical(std::string first, std::string second,
bool forceCaseSensitve =
false);
1826 std::string
path_join(std::vector<std::string> elems);
1932 std::string
to_string(
const char *format =
"%y-%m-%d %H:%M:%S.%frac");
1947 std::time_t timeStamp_;
1949 std::string fractionStr_;
1950 struct std::tm calendar_;
2038 std::string
to_string(
const char *format =
"[%ms ms]");
2041 std::chrono::steady_clock::time_point timeStamp_;
2042 std::size_t elapsed_;
2055 if (milliseconds > 0)
2057 std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
2071 static const int kDefaultFileOpenRetryTimes = 5;
2072 static const int kDefaultFileOpenRetryInterval = 10;
2081 Path(std::string path,
bool isAbsolute =
false);
2134 std::string abspath_;
2143 using iterator = std::vector<Path>::iterator;
2144 using const_iterator = std::vector<Path>::const_iterator;
2159 Directory(std::string root,
const std::string pattern,
bool recursive =
false);
2167 Directory(std::string root,
const std::vector<std::string> patternList,
bool recursive);
2175 Directory(std::string root,
const std::vector<const char*> patternList,
bool recursive);
2181 iterator
begin() {
return paths_.begin(); }
2187 iterator
end() {
return paths_.end(); }
2193 const_iterator
cbegin()
const {
return paths_.cbegin(); }
2199 const_iterator
cend()
const {
return paths_.cend(); }
2205 std::size_t
size()
const {
return paths_.size(); }
2217 std::string
root()
const;
2223 void filter(
const std::string pattern);
2229 void filter(
const std::vector<const char*> patternList);
2235 void filter(
const std::vector<std::string> patternList);
2246 std::vector<Path>
to_list()
const;
2253 std::vector<Path> paths_;
2274 int retryTimes = consts::kDefaultFileOpenRetryTimes,
2275 int retryInterval = consts::kDefaultFileOpenRetryInterval);
2294 template <
typename T>
2311 bool open(std::string filename,
bool truncateOrNot =
false,
2312 int retryTimes = consts::kDefaultFileOpenRetryTimes,
2313 int retryInterval = consts::kDefaultFileOpenRetryInterval);
2323 bool open(
const char* filename,
bool truncateOrNot =
false,
2324 int retryTimes = consts::kDefaultFileOpenRetryTimes,
2325 int retryInterval = consts::kDefaultFileOpenRetryInterval);
2332 bool open(
bool truncateOrNot =
false);
2339 bool reopen(
bool truncateOrNot =
true);
2356 bool is_open()
const {
return stream_.is_open(); }
2364 bool try_open(
int retryTime,
int retryInterval,
bool truncateOrNot =
false);
2367 std::string filename_;
2368 std::fstream stream_;
2369 std::streampos readPos_;
2370 std::streampos writePos_;
2389 FileReader(std::string filename,
int retryTimes = consts::kDefaultFileOpenRetryTimes,
2390 int retryInterval = consts::kDefaultFileOpenRetryInterval);
2408 bool is_open()
const {
return istream_.is_open(); }
2438 std::string
next_line(
bool trimWhiteSpaces =
false);
2450 bool try_open(
int retryTime,
int retryInterval);
2452 std::string filename_;
2453 std::ifstream istream_;
2474 static const std::string kFormatSpecifierPlaceHolder = std::string(
"{}");
2479 template<
class Facet>
2482 template<
class ...Args>
2483 DeletableFacet(Args&& ...args) : Facet(std::forward<Args>(args)...) {}
2496 std::ostringstream ss;
2497 ss << std::setw(length) << std::setfill(
'0') << num;
2523 bool starts_with(
const std::string& str,
const std::string& start);
2531 bool ends_with(
const std::string& str,
const std::string& end);
2540 std::string&
replace_all(std::string& str,
const std::string& replaceWhat,
const std::string& replaceWith);
2549 std::string&
replace_all(std::string& str,
char replaceWhat,
char replaceWith);
2559 bool str_equals(
const char* s1,
const char* s2);
2566 std::string
ltrim(std::string str);
2573 std::string
rtrim(std::string str);
2580 std::string
trim(std::string str);
2589 std::string
lstrip(std::string str, std::string what);
2598 std::string
rstrip(std::string str, std::string what);
2606 std::string
lskip(std::string str, std::string delim);
2614 std::string
rskip(std::string str, std::string delim);
2622 std::string
rskip_all(std::string str, std::string delim);
2630 std::vector<std::string>
split(
const std::string s,
char delim =
' ');
2639 std::vector<std::string>
split(
const std::string s, std::string delim);
2647 std::vector<std::string>
split_multi_delims(
const std::string s, std::string delims);
2670 std::string
join(std::vector<std::string> elems,
char delim);
2678 std::vector<std::string>&
erase_empty(std::vector<std::string>& vec);
2696 void replace_all_with_escape(std::string &str,
const std::string &replaceWhat,
const std::string &replaceWith);
2757 template<
typename Arg>
2760 std::stringstream ss;
2772 template<
typename Arg,
typename... Args>
2773 inline void format_string(std::string &fmt,
const Arg& current,
const Args&... more)
2775 std::stringstream ss;
2822 std::string
str()
const {
return str_; }
2828 bool empty()
const {
return str_.empty(); }
2854 template <
typename T> std::string
store(T t);
2861 template <
typename T> std::string
store(std::vector<T> t);
2868 template <
typename T> T
load(T& t);
2875 template <
typename T> std::vector<T>
load(std::vector<T>& t);
2889 template <
typename T> T
load() { T t;
return load(t); }
2901 CfgLevel() : parent(
nullptr), depth(0) {}
2904 using value_map_t = std::map<std::string, Value>;
2905 using section_map_t = std::map<std::string, CfgLevel>;
2908 section_map_t sections;
2913 Value operator[](
const std::string& name) {
return values[name]; }
2914 CfgLevel& operator()(
const std::string& name) {
return sections[name]; }
2915 std::string to_string()
2918 for (
auto v : values)
2920 ret += prefix + v.first +
" = " + v.second.str() +
"\n";
2922 for (
auto s : sections)
2924 ret += s.second.to_string();
2946 CfgParser(std::istream& s) : pstream_(&s), ln_(0) { parse(root_); }
2972 std::string split_key_value(std::string& line);
2973 void error_handler(std::string msg);
2976 std::ifstream stream_;
2977 std::istream *pstream_;
2995 ArgOption(
char shortKey, std::string longKey);
3026 ArgOption&
call(std::function<
void()> todo, std::function<
void()> otherwise);
3090 std::string get_help();
3091 std::string get_short_help();
3094 std::string longKey_;
3097 std::string default_;
3105 std::vector<std::function<void()>> callback_;
3106 std::vector<std::function<void()>> othercall_;
3167 T& dst, T defaultValue, std::string help =
"", std::string type =
"",
int min = 1,
int max = 1);
3178 ArgOption&
add_opt_flag(
char shortKey, std::string longKey, std::string help =
"",
bool* dst =
nullptr);
3187 void add_opt_help(
char shortKey, std::string longKey, std::string help =
"print this help and exit");
3196 void add_opt_version(
char shortKey, std::string longKey, std::string
version, std::string help =
"print version and exit");
3210 void parse(
int argc,
char** argv,
bool ignoreUnknown =
false);
3223 int count(
char shortKey);
3230 int count(std::string longKey);
3266 enum class Type { SHORT_KEY, LONG_KEY, ARGUMENT, INVALID };
3267 using ArgQueue = std::vector<std::pair<std::string, Type>>;
3269 ArgOption& add_opt_internal(
char shortKey, std::string longKey);
3270 void register_keys(
char shortKey, std::string longKey, std::size_t pos);
3271 Type check_type(std::string str);
3272 ArgQueue pretty_arguments(
int argc,
char** argv);
3273 void error_option(std::string opt, std::string msg =
"");
3274 void parse_option(ArgOption* ptr);
3275 void parse_value(ArgOption* ptr,
const std::string& value);
3277 std::vector<ArgOption> options_;
3278 std::unordered_map<char, std::size_t> shortKeys_;
3279 std::unordered_map<std::string, std::size_t> longKeys_;
3280 std::vector<Value> args_;
3281 std::vector<std::string> errors_;
3282 std::vector<std::string> info_;
3290 std::ostringstream oss;
3298 std::ostringstream oss;
3309 std::istringstream iss(str_);
3318 std::istringstream iss(lowered);
3319 iss >> std::boolalpha >> b;
3323 template <
typename T>
inline std::vector<T>
Value::load(std::vector<T>& t)
3325 std::istringstream iss(str_);
3329 while (iss >> val || !iss.eof())
3343 T& dst, T defaultValue, std::string help, std::string type,
int min,
int max)
3347 dfltValue.
store(defaultValue);
3348 auto pos = options_.size();
3349 auto& opt =
add_opt(shortKey, longKey).
call([&, pos] {options_[pos].get_value().load(dst); });
3350 opt.default_ = dfltValue.
str();
3351 return opt.set_help(help).set_type(type).set_min(min).set_max(max);
3366 void zupply_internal_warn(std::string msg);
3367 void zupply_internal_error(std::string msg);
3369 class ScopedRedirect
3372 ScopedRedirect(std::ostream &orig) : backup_(orig)
3374 old = orig.rdbuf(buffer_.rdbuf());
3380 backup_ << buffer_.str();
3384 ScopedRedirect(
const ScopedRedirect&);
3385 ScopedRedirect& operator=(
const ScopedRedirect&);
3387 std::ostream &backup_;
3388 std::streambuf *old;
3389 std::ostringstream buffer_;
3407 ProgBar(
unsigned range = 100, std::string info =
"");
3418 void step(
unsigned size = 1);
3431 void calc_rate(
unsigned size);
3435 std::atomic<unsigned> pos_;
3436 std::thread worker_;
3437 std::atomic_bool running_;
3438 std::streambuf *oldCout_;
3439 std::streambuf *oldCerr_;
3441 std::ostringstream buffer_;
3447 typedef enum LogLevelEnum
3461 static const char *kLevelNames[] {
"TRACE",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"FATAL",
"OFF"};
3462 static const char *kShortLevelNames[] {
"T",
"D",
"I",
"W",
"E",
"F",
"O"};
3463 static const char *kZupplyInternalLoggerName =
"zupply";
3464 static const int kAsyncQueueSize = 4096;
3466 static const char *kSinkDatetimeSpecifier =
"%datetime";
3467 static const char *kSinkLoggerNameSpecifier =
"%logger";
3468 static const char *kSinkThreadSpecifier =
"%thread";
3469 static const char *kSinkLevelSpecifier =
"%level";
3470 static const char *kSinkLevelShortSpecifier =
"%lvl";
3471 static const char *kSinkMessageSpecifier =
"%msg";
3472 static const char *kStdoutSinkName =
"stdout";
3473 static const char *kStderrSinkName =
"stderr";
3474 static const char *kSimplefileSinkType =
"simplefile";
3475 static const char *kRotatefileSinkType =
"rotatefile";
3476 static const char *kOstreamSinkType =
"ostream";
3477 static const char *kDefaultLoggerFormat =
"[%datetime][T%thread][%logger][%level] %msg";
3478 static const char *kDefaultLoggerDatetimeFormat =
"%y-%m-%d %H:%M:%S.%frac";
3481 static const char *KConfigGlobalSectionSpecifier =
"global";
3482 static const char *KConfigLoggerSectionSpecifier =
"loggers";
3483 static const char *KConfigSinkSectionSpecifier =
"sinks";
3484 static const char *kConfigFormatSpecifier =
"format";
3485 static const char *kConfigLevelsSpecifier =
"levels";
3486 static const char *kConfigDateTimeFormatSpecifier =
"datetime_format";
3487 static const char *kConfigSinkListSpecifier =
"sink_list";
3488 static const char *kConfigSinkTypeSpecifier =
"type";
3489 static const char *kConfigSinkFilenameSpecifier =
"filename";
3497 class SinkInterface;
3499 typedef std::shared_ptr<detail::SinkInterface> SinkPtr;
3501 inline bool level_should_log(
int levelMask, LogLevels lvl)
3503 return (LogLevels::sentinel & levelMask & (1 << lvl)) > 0;
3506 std::string level_mask_to_string(
int levelMask);
3508 LogLevels level_from_str(std::string level);
3510 int level_mask_from_string(std::string levels);
3606 std::atomic_int logLevelMask_;
3635 levelMask_ = levelMask;
3644 template <
typename... Args> detail::LineLogger
trace(
const char* fmt,
const Args&... args);
3651 template <
typename... Args> detail::LineLogger
debug(
const char* fmt,
const Args&... args);
3658 template <
typename... Args> detail::LineLogger
info(
const char* fmt,
const Args&... args);
3665 template <
typename... Args> detail::LineLogger
warn(
const char* fmt,
const Args&... args);
3672 template <
typename... Args> detail::LineLogger
error(
const char* fmt,
const Args&... args);
3679 template <
typename... Args> detail::LineLogger
fatal(
const char* fmt,
const Args&... args);
3688 template <
typename T> detail::LineLogger
trace(
const T& msg);
3695 template <
typename T> detail::LineLogger
debug(
const T& msg);
3702 template <
typename T> detail::LineLogger
info(
const T& msg);
3709 template <
typename T> detail::LineLogger
warn(
const T& msg);
3716 template <
typename T> detail::LineLogger
error(
const T& msg);
3723 template <
typename T> detail::LineLogger
fatal(
const T& msg);
3732 detail::LineLogger
trace();
3738 detail::LineLogger
debug();
3744 detail::LineLogger
info();
3750 detail::LineLogger
warn();
3756 detail::LineLogger
error();
3762 detail::LineLogger
fatal();
3775 levelMask_ = levelMask & LogLevels::sentinel;
3785 return level_should_log(levelMask_, msgLevel);
3792 std::string
name()
const {
return name_; };
3845 friend detail::LineLogger;
3847 detail::LineLogger log_if_enabled(LogLevels lvl);
3849 template <
typename... Args>
3850 detail::LineLogger log_if_enabled(LogLevels lvl,
const char* fmt,
const Args&... args);
3852 template<
typename T>
3853 detail::LineLogger log_if_enabled(LogLevels lvl,
const T& msg);
3855 void log_msg(detail::LogMessage msg);
3858 std::atomic_int levelMask_;
3861 typedef std::shared_ptr<Logger> LoggerPtr;
3867 template<
typename T>
3868 class mpmc_bounded_queue
3872 using item_type = T;
3873 mpmc_bounded_queue(
size_t buffer_size)
3874 : buffer_(new cell_t[buffer_size]),
3875 buffer_mask_(buffer_size - 1)
3878 if (!((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0)))
3879 throw ArgException(
"async logger queue size must be power of two");
3881 for (
size_t i = 0; i != buffer_size; i += 1)
3882 buffer_[i].sequence_.store(i, std::memory_order_relaxed);
3883 enqueue_pos_.store(0, std::memory_order_relaxed);
3884 dequeue_pos_.store(0, std::memory_order_relaxed);
3887 ~mpmc_bounded_queue()
3893 bool enqueue(T&& data)
3896 size_t pos = enqueue_pos_.load(std::memory_order_relaxed);
3899 cell = &buffer_[pos & buffer_mask_];
3900 size_t seq = cell->sequence_.load(std::memory_order_acquire);
3901 intptr_t dif = (intptr_t)seq - (intptr_t)pos;
3904 if (enqueue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed))
3913 pos = enqueue_pos_.load(std::memory_order_relaxed);
3916 cell->data_ = std::move(data);
3917 cell->sequence_.store(pos + 1, std::memory_order_release);
3921 bool dequeue(T& data)
3924 size_t pos = dequeue_pos_.load(std::memory_order_relaxed);
3927 cell = &buffer_[pos & buffer_mask_];
3929 cell->sequence_.load(std::memory_order_acquire);
3930 intptr_t dif = (intptr_t)seq - (intptr_t)(pos + 1);
3933 if (dequeue_pos_.compare_exchange_weak(pos, pos + 1, std::memory_order_relaxed))
3939 pos = dequeue_pos_.load(std::memory_order_relaxed);
3941 data = std::move(cell->data_);
3942 cell->sequence_.store(pos + buffer_mask_ + 1, std::memory_order_release);
3949 std::atomic<size_t> sequence_;
3953 static size_t const cacheline_size = 64;
3954 typedef char cacheline_pad_t[cacheline_size];
3956 cacheline_pad_t pad0_;
3957 cell_t*
const buffer_;
3958 size_t const buffer_mask_;
3959 cacheline_pad_t pad1_;
3960 std::atomic<size_t> enqueue_pos_;
3961 cacheline_pad_t pad2_;
3962 std::atomic<size_t> dequeue_pos_;
3963 cacheline_pad_t pad3_;
3965 mpmc_bounded_queue(mpmc_bounded_queue
const&);
3966 void operator = (mpmc_bounded_queue
const&);
3971 std::string loggerName_;
3973 time::DateTime dateTime_;
3975 std::string buffer_;
3978 class LineLogger :
private UnCopyable
3981 LineLogger(Logger* callbacker, LogLevels lvl,
bool enable) :callbackLogger_(callbacker), enabled_(enable)
3986 LineLogger(LineLogger&& other) :
3987 callbackLogger_(other.callbackLogger_),
3988 msg_(std::move(other.msg_)),
3989 enabled_(other.enabled_)
3998 msg_.loggerName_ = callbackLogger_->name();
4001 callbackLogger_->log_msg(msg_);
4005 LineLogger& operator=(LineLogger&&) =
delete;
4007 void write(
const char* what)
4010 msg_.buffer_ += what;
4013 template <
typename... Args>
4014 void write(
const char* fmt,
const Args&... args)
4016 if (!enabled_)
return;
4017 std::string buf(fmt);
4019 msg_.buffer_ += buf;
4023 LineLogger& operator<<(
const char* what)
4025 if (enabled_) msg_.buffer_ += what;
4029 LineLogger& operator<<(
const std::string& what)
4031 if (enabled_) msg_.buffer_ += what;
4035 template<
typename T>
4036 LineLogger& operator<<(
const T& what)
4040 std::ostringstream oss;
4041 oss << std::dec << what;
4042 msg_.buffer_ += oss.str();
4052 bool is_enabled()
const
4057 Logger *callbackLogger_;
4065 virtual ~SinkInterface() {};
4066 virtual void log(
const LogMessage& msg) = 0;
4067 virtual void flush() = 0;
4068 virtual std::string name()
const = 0;
4069 virtual std::string to_string()
const = 0;
4070 virtual void set_level_mask(
int levelMask) = 0;
4071 virtual void set_format(
const std::string &fmt) = 0;
4077 class AsyncSink :
public SinkInterface,
private UnCopyable
4082 class Sink :
public SinkInterface,
private UnCopyable
4093 void log(
const LogMessage& msg)
override
4095 if (!level_should_log(levelMask_, msg.level_))
return;
4096 std::string finalMessage = format_message(msg);
4099 std::lock_guard<std::mutex> lock(mutex_);
4100 sink_it(finalMessage);
4103 void set_level_mask(
int levelMask)
override
4105 levelMask_ = levelMask & LogLevels::sentinel;
4108 int level_mask()
const
4113 void set_format(
const std::string &format)
override
4115 format_.set(format);
4118 virtual void sink_it(
const std::string &finalMsg) = 0;
4121 std::string format_message(
const LogMessage &msg)
4123 std::string ret(format_.get());
4124 auto dt = msg.dateTime_;
4136 std::atomic_int levelMask_;
4138 cds::lockbased::NonTrivialContainer<std::string> format_;
4141 class SimpleFileSink :
public Sink
4144 SimpleFileSink(
const std::string filename,
bool truncate) :fileEditor_(filename, truncate)
4148 void flush()
override
4150 fileEditor_.flush();
4153 void sink_it(
const std::string &finalMsg)
override
4155 fileEditor_ << finalMsg;
4158 std::string name()
const override
4160 return fileEditor_.filename();
4163 std::string to_string()
const override
4165 return "SimpleFileSink->" + name() +
" " + level_mask_to_string(level_mask());
4169 fs::FileEditor fileEditor_;
4172 class RotateFileSink :
public Sink
4175 RotateFileSink(
const std::string filename, std::size_t maxSizeInByte,
bool backup);
4177 void flush()
override
4179 fileEditor_.flush();
4182 void sink_it(
const std::string &finalMsg)
override
4184 currentSize_ += finalMsg.length();
4185 if (currentSize_ > maxSizeInByte_)
4189 fileEditor_ << finalMsg;
4192 std::string name()
const override
4194 return fileEditor_.filename();
4197 std::string to_string()
const override
4199 return "RotateFileSink->" + name() +
" " + level_mask_to_string(level_mask());
4203 void back_up(std::string oldFile);
4206 fs::FileEditor fileEditor_;
4208 std::size_t maxSizeInByte_;
4209 std::atomic<std::size_t> currentSize_;
4213 class OStreamSink :
public Sink
4216 explicit OStreamSink(std::ostream& os,
const char *name,
bool forceFlush =
false)
4217 :ostream_(os), name_(name), forceFlush_(forceFlush)
4221 std::string name()
const override
4226 std::string to_string()
const override
4228 return "OStreamSink->" + name() +
" " + level_mask_to_string(level_mask());
4232 void sink_it(
const std::string &finalMsg)
override
4234 ostream_ << finalMsg;
4235 if (forceFlush_) ostream_.flush();
4238 void flush()
override
4243 std::ostream& ostream_;
4248 class StdoutSink :
public OStreamSink
4251 StdoutSink() : OStreamSink(std::cout, consts::kStdoutSinkName, true)
4257 static std::shared_ptr<StdoutSink> instance()
4259 static std::shared_ptr<StdoutSink> instance = std::make_shared<StdoutSink>();
4263 std::string to_string()
const override
4265 return "StdoutSink->" + name() +
" " + level_mask_to_string(level_mask());
4269 class StderrSink :
public OStreamSink
4272 StderrSink() : OStreamSink(std::cerr, consts::kStderrSinkName, true)
4277 static std::shared_ptr<StderrSink> instance()
4279 static std::shared_ptr<StderrSink> instance = std::make_shared<StderrSink>();
4283 std::string to_string()
const override
4285 return "StderrSink->" + name() +
" " + level_mask_to_string(level_mask());
4289 class LoggerRegistry : UnMovable
4292 static LoggerRegistry& instance();
4293 LoggerPtr create(
const std::string &name);
4294 LoggerPtr ensure_get(std::string &name);
4295 LoggerPtr
get(std::string &name);
4296 std::vector<LoggerPtr> get_all();
4297 void drop(
const std::string &name);
4301 bool is_locked()
const;
4304 LoggerRegistry(){ lock_ =
false; }
4306 LoggerPtr new_registry(
const std::string &name);
4308 cds::lockbased::UnorderedMap<std::string, LoggerPtr> loggers_;
4309 std::atomic_bool lock_;
4313 inline detail::LineLogger Logger::log_if_enabled(LogLevels lvl)
4315 detail::LineLogger l(
this, lvl,
should_log(lvl));
4319 template <
typename... Args>
4320 inline detail::LineLogger Logger::log_if_enabled(LogLevels lvl,
const char* fmt,
const Args&... args)
4322 detail::LineLogger l(
this, lvl,
should_log(lvl));
4323 l.write(fmt, args...);
4327 template<
typename T>
4328 inline detail::LineLogger Logger::log_if_enabled(LogLevels lvl,
const T& msg)
4330 detail::LineLogger l(
this, lvl,
should_log(lvl));
4336 template <
typename... Args>
4337 inline detail::LineLogger
Logger::trace(
const char* fmt,
const Args&... args)
4339 return log_if_enabled(LogLevels::trace, fmt, args...);
4341 template <
typename... Args>
4342 inline detail::LineLogger
Logger::debug(
const char* fmt,
const Args&... args)
4344 return log_if_enabled(LogLevels::debug, fmt, args...);
4346 template <
typename... Args>
4347 inline detail::LineLogger
Logger::info(
const char* fmt,
const Args&... args)
4349 return log_if_enabled(LogLevels::info, fmt, args...);
4351 template <
typename... Args>
4352 inline detail::LineLogger
Logger::warn(
const char* fmt,
const Args&... args)
4354 return log_if_enabled(LogLevels::warn, fmt, args...);
4356 template <
typename... Args>
4357 inline detail::LineLogger
Logger::error(
const char* fmt,
const Args&... args)
4359 return log_if_enabled(LogLevels::error, fmt, args...);
4361 template <
typename... Args>
4362 inline detail::LineLogger
Logger::fatal(
const char* fmt,
const Args&... args)
4364 return log_if_enabled(LogLevels::fatal, fmt, args...);
4369 template <
typename T>
4372 return log_if_enabled(LogLevels::trace, msg);
4374 template <
typename T>
4377 return log_if_enabled(LogLevels::debug, msg);
4379 template <
typename T>
4382 return log_if_enabled(LogLevels::info, msg);
4384 template <
typename T>
4387 return log_if_enabled(LogLevels::warn, msg);
4389 template <
typename T>
4392 return log_if_enabled(LogLevels::error, msg);
4394 template <
typename T>
4397 return log_if_enabled(LogLevels::fatal, msg);
4408 LoggerPtr
get_logger(std::string name,
bool createIfNotExists =
true);
4427 SinkPtr
get_sink(std::string name);
4442 SinkPtr
new_ostream_sink(std::ostream &stream, std::string name,
bool forceFlush =
false);
4459 SinkPtr
new_rotate_file_sink(std::string filename, std::size_t maxSizeInByte = 4194304,
bool backupOld =
false);
4493 void sink_list_revise(std::vector<std::string> &list, std::map<std::string, std::string> &map);
4495 void config_loggers_from_section(cfg::CfgLevel::section_map_t §ion, std::map<std::string, std::string> &map);
4497 LoggerPtr get_hidden_logger();
4499 std::map<std::string, std::string> config_sinks_from_section(cfg::CfgLevel::section_map_t §ion);
4502 void zupply_internal_warn(std::string msg);
4504 void zupply_internal_error(std::string msg);
4506 void config_from_parser(cfg::CfgParser& parser);
4527 template<
typename _Tp>
static inline _Tp saturate_cast(
unsigned char v) {
return _Tp(v); }
4528 template<
typename _Tp>
static inline _Tp saturate_cast(
char v) {
return _Tp(v); }
4529 template<
typename _Tp>
static inline _Tp saturate_cast(
unsigned short v) {
return _Tp(v); }
4530 template<
typename _Tp>
static inline _Tp saturate_cast(
short v) {
return _Tp(v); }
4531 template<
typename _Tp>
static inline _Tp saturate_cast(
unsigned v) {
return _Tp(v); }
4532 template<
typename _Tp>
static inline _Tp saturate_cast(
int v) {
return _Tp(v); }
4533 template<
typename _Tp>
static inline _Tp saturate_cast(
float v) {
return _Tp(v); }
4534 template<
typename _Tp>
static inline _Tp saturate_cast(
double v) {
return _Tp(v); }
4536 template<>
inline unsigned char saturate_cast<
unsigned char>(
char v) {
return (
unsigned char)(std::max)((
int)v, 0); }
4537 template<>
inline unsigned char saturate_cast<
unsigned char>(
unsigned char v) {
return (
unsigned char)(std::min)((
unsigned)v, (unsigned)UCHAR_MAX); }
4538 template<>
inline unsigned char saturate_cast<
unsigned char>(
int v) {
return (
unsigned char)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); }
4539 template<>
inline unsigned char saturate_cast<
unsigned char>(
short v) {
return saturate_cast<
unsigned char>((int)v); }
4540 template<>
inline unsigned char saturate_cast<
unsigned char>(
unsigned v) {
return (
unsigned char)(std::min)(v, (
unsigned)UCHAR_MAX); }
4541 template<>
inline unsigned char saturate_cast<
unsigned char>(
float v) {
int iv =
math::round(v);
return saturate_cast<
unsigned char>(iv); }
4542 template<>
inline unsigned char saturate_cast<
unsigned char>(
double v) {
int iv =
math::round(v);
return saturate_cast<
unsigned char>(iv); }
4544 template<>
inline char saturate_cast<
char>(
unsigned char v) {
return (
char)(std::min)((
int)v, SCHAR_MAX); }
4545 template<>
inline char saturate_cast<
char>(
unsigned short v) {
return (
char)(std::min)((
unsigned)v, (unsigned)SCHAR_MAX); }
4546 template<>
inline char saturate_cast<
char>(
int v) {
return (
char)((unsigned)(v - SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); }
4547 template<>
inline char saturate_cast<
char>(
short v) {
return saturate_cast<
char>((int)v); }
4548 template<>
inline char saturate_cast<
char>(
unsigned int v) {
return (
char)(std::min)(v, (
unsigned)SCHAR_MAX); }
4549 template<>
inline char saturate_cast<
char>(
float v) {
int iv =
math::round(v);
return saturate_cast<
char>(iv); }
4550 template<>
inline char saturate_cast<
char>(
double v) {
int iv =
math::round(v);
return saturate_cast<
char>(iv); }
4552 template<>
inline unsigned short saturate_cast<
unsigned short>(
char v) {
return (
unsigned short)(std::max)((
int)v, 0); }
4553 template<>
inline unsigned short saturate_cast<
unsigned short>(
short v) {
return (
unsigned short)(std::max)((
int)v, 0); }
4554 template<>
inline unsigned short saturate_cast<
unsigned short>(
int v) {
return (
unsigned short)((unsigned)v <= (
unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); }
4555 template<>
inline unsigned short saturate_cast<
unsigned short>(
unsigned v) {
return (
unsigned short)(std::min)(v, (
unsigned)USHRT_MAX); }
4556 template<>
inline unsigned short saturate_cast<
unsigned short>(
float v) {
int iv =
math::round(v);
return saturate_cast<
unsigned short>(iv); }
4557 template<>
inline unsigned short saturate_cast<
unsigned short>(
double v) {
int iv =
math::round(v);
return saturate_cast<
unsigned short>(iv); }
4559 template<>
inline short saturate_cast<
short>(
unsigned short v) {
return (
short)(std::min)((
int)v, SHRT_MAX); }
4560 template<>
inline short saturate_cast<
short>(
int v) {
return (
short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); }
4561 template<>
inline short saturate_cast<
short>(
unsigned v) {
return (
short)(std::min)(v, (
unsigned)SHRT_MAX); }
4562 template<>
inline short saturate_cast<
short>(
float v) {
int iv =
math::round(v);
return saturate_cast<
short>(iv); }
4563 template<>
inline short saturate_cast<
short>(
double v) {
int iv =
math::round(v);
return saturate_cast<
short>(iv); }
4565 template<>
inline int saturate_cast<
int>(
float v) {
return math::round(v); }
4566 template<>
inline int saturate_cast<
int>(
double v) {
return math::round(v); }
4569 template<>
inline unsigned saturate_cast<
unsigned>(
float v) {
return (
unsigned)
math::round(v); }
4570 template<>
inline unsigned saturate_cast<
unsigned>(
double v) {
return (
unsigned)
math::round(v); }
4573 template<
typename _Tp>
inline
4575 : width(0), height(0) {}
4577 template<
typename _Tp>
inline
4579 : width(_width), height(_height) {}
4581 template<
typename _Tp>
inline
4583 : width(sz.width), height(sz.height) {}
4585 template<
typename _Tp>
template<
typename _Tp2>
inline
4586 Size_<_Tp>::operator Size_<_Tp2>()
const
4588 return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height));
4591 template<
typename _Tp>
inline
4594 width = sz.width; height = sz.height;
4598 template<
typename _Tp>
inline
4601 return (width == sz.width) && (height == sz.height);
4604 template<
typename _Tp>
inline
4607 return (width != sz.width) || (height != sz.height);
4610 template<
typename _Tp>
inline
4613 return width * height;
4616 template<
typename _Tp>
static inline
4617 Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b)
4624 template<
typename _Tp>
static inline
4625 Size_<_Tp> operator * (
const Size_<_Tp>& a, _Tp b)
4632 template<
typename _Tp>
static inline
4633 Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b)
4640 template<
typename _Tp>
static inline
4641 Size_<_Tp> operator / (
const Size_<_Tp>& a, _Tp b)
4648 template<
typename _Tp>
static inline
4649 Size_<_Tp>& operator += (Size_<_Tp>& a,
const Size_<_Tp>& b)
4652 a.height += b.height;
4656 template<
typename _Tp>
static inline
4657 Size_<_Tp> operator + (
const Size_<_Tp>& a,
const Size_<_Tp>& b)
4664 template<
typename _Tp>
static inline
4665 Size_<_Tp>& operator -= (Size_<_Tp>& a,
const Size_<_Tp>& b)
4668 a.height -= b.height;
4672 template<
typename _Tp>
static inline
4673 Size_<_Tp> operator - (
const Size_<_Tp>& a,
const Size_<_Tp>& b)
4680 template<
typename _Tp>
static inline
4681 bool operator == (
const Size_<_Tp>& a,
const Size_<_Tp>& b)
4683 return a.width == b.width && a.height == b.height;
4686 template<
typename _Tp>
static inline
4687 bool operator != (
const Size_<_Tp>& a,
const Size_<_Tp>& b)
4693 template<
typename _Tp>
inline
4697 template<
typename _Tp>
inline
4701 template<
typename _Tp>
inline
4703 : x(pt.x), y(pt.y) {}
4706 template<
typename _Tp>
inline
4713 template<
typename _Tp>
template<
typename _Tp2>
inline
4714 Point_<_Tp>::operator Point_<_Tp2>()
const
4716 return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y));
4719 template<
typename _Tp>
static inline
4720 Point_<_Tp>& operator += (Point_<_Tp>& a,
const Point_<_Tp>& b)
4727 template<
typename _Tp>
static inline
4728 Point_<_Tp>& operator -= (Point_<_Tp>& a,
const Point_<_Tp>& b)
4735 template<
typename _Tp>
static inline
4736 Point_<_Tp>& operator *= (Point_<_Tp>& a,
int b)
4738 a.x = saturate_cast<_Tp>(a.x * b);
4739 a.y = saturate_cast<_Tp>(a.y * b);
4743 template<
typename _Tp>
static inline
4744 Point_<_Tp>& operator *= (Point_<_Tp>& a,
float b)
4746 a.x = saturate_cast<_Tp>(a.x * b);
4747 a.y = saturate_cast<_Tp>(a.y * b);
4751 template<
typename _Tp>
static inline
4752 Point_<_Tp>& operator *= (Point_<_Tp>& a,
double b)
4754 a.x = saturate_cast<_Tp>(a.x * b);
4755 a.y = saturate_cast<_Tp>(a.y * b);
4759 template<
typename _Tp>
static inline
4760 Point_<_Tp>& operator /= (Point_<_Tp>& a,
int b)
4762 a.x = saturate_cast<_Tp>(a.x / b);
4763 a.y = saturate_cast<_Tp>(a.y / b);
4767 template<
typename _Tp>
static inline
4768 Point_<_Tp>& operator /= (Point_<_Tp>& a,
float b)
4770 a.x = saturate_cast<_Tp>(a.x / b);
4771 a.y = saturate_cast<_Tp>(a.y / b);
4775 template<
typename _Tp>
static inline
4776 Point_<_Tp>& operator /= (Point_<_Tp>& a,
double b)
4778 a.x = saturate_cast<_Tp>(a.x / b);
4779 a.y = saturate_cast<_Tp>(a.y / b);
4783 template<
typename _Tp>
static inline
4784 bool operator == (
const Point_<_Tp>& a,
const Point_<_Tp>& b)
4786 return a.x == b.x && a.y == b.y;
4789 template<
typename _Tp>
static inline
4790 bool operator != (
const Point_<_Tp>& a,
const Point_<_Tp>& b)
4792 return a.x != b.x || a.y != b.y;
4795 template<
typename _Tp>
static inline
4796 Point_<_Tp> operator + (
const Point_<_Tp>& a,
const Point_<_Tp>& b)
4798 return Point_<_Tp>(saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y));
4801 template<
typename _Tp>
static inline
4802 Point_<_Tp> operator - (
const Point_<_Tp>& a,
const Point_<_Tp>& b)
4804 return Point_<_Tp>(saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y));
4807 template<
typename _Tp>
static inline
4808 Point_<_Tp> operator - (
const Point_<_Tp>& a)
4810 return Point_<_Tp>(saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y));
4813 template<
typename _Tp>
static inline
4814 Point_<_Tp> operator * (
const Point_<_Tp>& a,
int b)
4816 return Point_<_Tp>(saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b));
4819 template<
typename _Tp>
static inline
4820 Point_<_Tp> operator * (
int a,
const Point_<_Tp>& b)
4822 return Point_<_Tp>(saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a));
4825 template<
typename _Tp>
static inline
4826 Point_<_Tp> operator * (
const Point_<_Tp>& a,
float b)
4828 return Point_<_Tp>(saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b));
4831 template<
typename _Tp>
static inline
4832 Point_<_Tp> operator * (
float a,
const Point_<_Tp>& b)
4834 return Point_<_Tp>(saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a));
4837 template<
typename _Tp>
static inline
4838 Point_<_Tp> operator * (
const Point_<_Tp>& a,
double b)
4840 return Point_<_Tp>(saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b));
4843 template<
typename _Tp>
static inline
4844 Point_<_Tp> operator * (
double a,
const Point_<_Tp>& b)
4846 return Point_<_Tp>(saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a));
4850 template<
typename _Tp>
static inline
4851 Point_<_Tp> operator / (
const Point_<_Tp>& a,
int b)
4858 template<
typename _Tp>
static inline
4859 Point_<_Tp> operator / (
const Point_<_Tp>& a,
float b)
4866 template<
typename _Tp>
static inline
4867 Point_<_Tp> operator / (
const Point_<_Tp>& a,
double b)
4874 template<
typename _Tp>
inline
4877 return saturate_cast<_Tp>(x*pt.x + y*pt.y);
4880 template<
typename _Tp>
inline
4883 return (
double)x*pt.x + (double)y*pt.y;
4886 template<
typename _Tp>
inline
4889 return (
double)x*pt.y - (double)y*pt.x;
4892 template<
typename _Tp>
inline bool
4895 return r.contains(*
this);
4900 template<
typename _Tp>
inline
4902 : x(0), y(0), width(0), height(0) {}
4904 template<
typename _Tp>
inline
4906 : x(_x), y(_y), width(_width), height(_height) {}
4908 template<
typename _Tp>
inline
4910 : x(r.x), y(r.y), width(r.width), height(r.height) {}
4912 template<
typename _Tp>
inline
4914 : x(org.x), y(org.y), width(sz.width), height(sz.height) {}
4916 template<
typename _Tp>
inline
4919 x = (std::min)(pt1.x, pt2.x);
4920 y = (std::min)(pt1.y, pt2.y);
4921 width = (std::max)(pt1.x, pt2.x) - x;
4922 height = (std::max)(pt1.y, pt2.y) - y;
4925 template<
typename _Tp>
inline
4935 template<
typename _Tp>
inline
4938 return Point_<_Tp>(x, y);
4941 template<
typename _Tp>
inline
4944 return Point_<_Tp>(x + width, y + height);
4947 template<
typename _Tp>
inline
4950 return Size_<_Tp>(width, height);
4953 template<
typename _Tp>
inline
4956 return width * height;
4959 template<
typename _Tp>
template<
typename _Tp2>
inline
4960 Rect_<_Tp>::operator Rect_<_Tp2>()
const
4962 return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height));
4965 template<
typename _Tp>
inline
4968 return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height;
4972 template<
typename _Tp>
static inline
4973 Rect_<_Tp>& operator += (Rect_<_Tp>& a,
const Point_<_Tp>& b)
4980 template<
typename _Tp>
static inline
4981 Rect_<_Tp>& operator -= (Rect_<_Tp>& a,
const Point_<_Tp>& b)
4988 template<
typename _Tp>
static inline
4989 Rect_<_Tp>& operator += (Rect_<_Tp>& a,
const Size_<_Tp>& b)
4992 a.height += b.height;
4996 template<
typename _Tp>
static inline
4997 Rect_<_Tp>& operator -= (Rect_<_Tp>& a,
const Size_<_Tp>& b)
5000 a.height -= b.height;
5004 template<
typename _Tp>
static inline
5005 Rect_<_Tp>& operator &= (Rect_<_Tp>& a,
const Rect_<_Tp>& b)
5007 _Tp x1 = (std::max)(a.x, b.x);
5008 _Tp y1 = (std::max)(a.y, b.y);
5009 a.width = (std::min)(a.x + a.width, b.x + b.width) - x1;
5010 a.height = (std::min)(a.y + a.height, b.y + b.height) - y1;
5013 if (a.width <= 0 || a.height <= 0)
5018 template<
typename _Tp>
static inline
5019 Rect_<_Tp>& operator |= (Rect_<_Tp>& a,
const Rect_<_Tp>& b)
5021 _Tp x1 = (std::min)(a.x, b.x);
5022 _Tp y1 = (std::min)(a.y, b.y);
5023 a.width = (std::max)(a.x + a.width, b.x + b.width) - x1;
5024 a.height = (std::max)(a.y + a.height, b.y + b.height) - y1;
5030 template<
typename _Tp>
static inline
5031 bool operator == (
const Rect_<_Tp>& a,
const Rect_<_Tp>& b)
5033 return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height;
5036 template<
typename _Tp>
static inline
5037 bool operator != (
const Rect_<_Tp>& a,
const Rect_<_Tp>& b)
5039 return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height;
5042 template<
typename _Tp>
static inline
5043 Rect_<_Tp> operator + (
const Rect_<_Tp>& a,
const Point_<_Tp>& b)
5045 return Rect_<_Tp>(a.x + b.x, a.y + b.y, a.width, a.height);
5048 template<
typename _Tp>
static inline
5049 Rect_<_Tp> operator - (
const Rect_<_Tp>& a,
const Point_<_Tp>& b)
5051 return Rect_<_Tp>(a.x - b.x, a.y - b.y, a.width, a.height);
5054 template<
typename _Tp>
static inline
5055 Rect_<_Tp> operator + (
const Rect_<_Tp>& a,
const Size_<_Tp>& b)
5057 return Rect_<_Tp>(a.x, a.y, a.width + b.width, a.height + b.height);
5060 template<
typename _Tp>
static inline
5061 Rect_<_Tp> operator & (
const Rect_<_Tp>& a,
const Rect_<_Tp>& b)
5067 template<
typename _Tp>
static inline
5068 Rect_<_Tp> operator | (
const Rect_<_Tp>& a,
const Rect_<_Tp>& b)
5077 template<
typename _Tp>
inline
5078 ImageBase<_Tp>::ImageBase()
5079 :rows_(0), cols_(0), channels_(0), data_(nullptr)
5083 template<
typename _Tp>
inline
5084 ImageBase<_Tp>::ImageBase(
int rows,
int cols,
int channels)
5086 create(rows, cols, channels);
5089 template<
typename _Tp>
inline
5090 ImageBase<_Tp>::ImageBase(
const ImageBase& other)
5092 rows_ = other.rows_;
5093 cols_ = other.cols_;
5094 channels_ = other.channels_;
5095 data_ = other.data_;
5098 template<
typename _Tp>
template<
typename _Tp2>
inline
5099 ImageBase<_Tp>::operator ImageBase<_Tp2>()
const
5101 ImageBase<_Tp2> tmp(rows_, cols_, channels_);
5102 _Tp2* p = tmp.ptr(0);
5104 for (
long i = 0; i < rows_ * cols_ * channels_; ++i)
5106 *p = saturate_cast<_Tp>(*p_);
5113 template<
typename _Tp>
inline
5114 ImageBase<_Tp>::ImageBase(ImageBase&& other)
5116 rows_ = other.rows_;
5117 cols_ = other.cols_;
5118 channels_ = other.channels_;
5119 data_ = other.data_;
5123 template<
typename _Tp>
inline
5124 ImageBase<_Tp>::~ImageBase()
5129 template<
typename _Tp>
inline
5130 void ImageBase<_Tp>::create(
int rows,
int cols,
int channels)
5132 assert(rows > 0 && cols > 0 && channels > 0);
5135 channels_ = channels;
5136 data_ = std::make_shared<std::vector<_Tp>>(rows * cols * channels);
5139 template<
typename _Tp>
inline
5140 void ImageBase<_Tp>::release()
5148 template<
typename _Tp>
inline
5149 ImageBase<_Tp>& ImageBase<_Tp>::operator= (
const ImageBase<_Tp>& other)
5151 rows_ = other.rows_;
5152 cols_ = other.cols_;
5153 channels_ = other.channels_;
5154 data_ = other.data_;
5158 template<
typename _Tp>
inline
5159 ImageBase<_Tp>& ImageBase<_Tp>::operator= (ImageBase<_Tp>&& other)
5161 rows_ = other.rows_;
5162 cols_ = other.cols_;
5163 channels_ = other.channels_;
5164 data_ = other.data_;
5169 template<
typename _Tp>
inline
5170 _Tp& ImageBase<_Tp>::operator() (
int row,
int col,
int channel)
5173 long pos = row * cols_ * channels_ + col * channels_ + channel;
5174 range_check(row, col, channel);
5175 return (*data_)[pos];
5178 template<
typename _Tp>
inline
5179 const _Tp& ImageBase<_Tp>::operator() (
int row,
int col,
int channel)
const
5182 long pos = row * cols_ * channels_ + col * channels_ + channel;
5183 range_check(row, col, channel);
5184 return (*data_)[pos];
5187 template<
typename _Tp>
inline
5188 bool ImageBase<_Tp>::empty()
const
5190 return (rows_ < 1 || cols_ < 1 || channels_ < 1 || (!data_));
5193 template<
typename _Tp>
inline
5194 int ImageBase<_Tp>::rows()
const
5199 template<
typename _Tp>
inline
5200 int ImageBase<_Tp>::cols()
const
5205 template<
typename _Tp>
inline
5206 int ImageBase<_Tp>::channels()
const
5211 template<
typename _Tp>
inline
5212 void ImageBase<_Tp>::range_check(
long long pos)
const
5215 if (empty())
throw RuntimeException(
"Accessing emtpy image!");
5216 if (pos >= rows_ * cols_ * channels_)
throw RuntimeException(
"Access out of range!");
5219 template<
typename _Tp>
inline
5220 void ImageBase<_Tp>::range_check(
int row,
int col,
int channel)
const
5222 assert(row >= 0 && col >= 0 && channel >= 0);
5223 if (empty())
throw RuntimeException(
"Accessing emtpy image!");
5224 if (row >= rows_ || col >= cols_ || channel >= channels_)
throw RuntimeException(
"Access out of range!");
5227 template<
typename _Tp>
inline
5228 _Tp ImageBase<_Tp>::at(
int row,
int col,
int channel)
const
5230 range_check(row, col, channel);
5231 long pos = row * cols_ * channels_ + col * channels_ + channel;
5232 return (*data_)[pos];
5235 template<
typename _Tp>
inline
5236 _Tp* ImageBase<_Tp>::ptr(
int offset)
const
5238 range_check(offset);
5239 return (*data_).data() + offset;
5242 template<
typename _Tp>
inline
5243 _Tp* ImageBase<_Tp>::ptr(
int row,
int col,
int channel)
const
5245 range_check(row, col, channel);
5246 long pos = row * cols_ * channels_ + col * channels_ + channel;
5247 return (*data_).data() + pos;
5250 template<
typename _Tp>
inline
5251 void ImageBase<_Tp>::import(_Tp* data,
int rows,
int cols,
int channels)
5253 assert(rows > 0 && cols > 0 && channels > 0 &&
"import size should be positive");
5254 create(rows, cols, channels);
5255 std::memcpy((*data_).data(), data,
sizeof(_Tp)* rows * cols * channels);
5258 template<
typename _Tp>
inline
5259 void ImageBase<_Tp>::import(std::vector<_Tp> data,
int rows,
int cols,
int channels)
5261 assert(rows > 0 && cols > 0 && channels > 0 && data.size() >= rows * cols * channels);
5262 create(rows, cols, channels);
5263 std::memcpy((*data_).data(), data.data(),
sizeof(_Tp)* rows * cols * channels);
5266 template<
typename _Tp>
inline
5267 std::vector<_Tp> ImageBase<_Tp>::export_raw()
const
5272 template<
typename _Tp>
template<
typename _Tp2>
inline
5273 std::vector<_Tp2>& ImageBase<_Tp>::export_raw(std::vector<_Tp2>& out)
const
5275 out.resize(rows_ * cols_ * channels_);
5276 auto p = out.begin();
5277 for (
auto i = (*data_).begin(); i != (*data_).end(); ++i, ++p)
5279 *p = saturate_cast<_Tp2>(*i);
5284 template<
typename _Tp>
inline
5285 void ImageBase<_Tp>::crop(
int r0,
int c0,
int r1,
int c1)
5287 assert(r0 >= 0 && c0 >= 0 && r1 >= 0 && c1 >= 0 &&
"crop region should be positive!");
5288 assert(r0 < rows_ && r1 < rows_ && c0 < cols_ && c1 < cols_ &&
"crop point should in image!");
5289 assert(r0 != r1 && (c0 != c1) &&
"need a rectangle region!");
5291 int width = std::abs(c0 - c1);
5292 int height = std::abs(r0 - r1);
5293 int i0 = (std::min)(r0, r1);
5294 int i1 = (std::max)(r0, r1);
5295 int j0 = (std::min)(c0, c1);
5296 int j1 = (std::max)(c0, c1);
5298 ImageBase<_Tp> tmp(height, width, channels_);
5301 _Tp* pOld = ptr(i0, j0, 0);
5302 _Tp* pNew = tmp.ptr(0);
5303 int step = cols_ * channels_;
5304 int bulkSize = width * channels_;
5305 for (
auto r = 0; r < height; ++r)
5308 std::memcpy(pNew, pOld,
sizeof(_Tp)* bulkSize);
5312 std::swap(*
this, tmp);
5315 template<
typename _Tp>
inline
5316 void ImageBase<_Tp>::crop(Point p0, Point p1)
5318 crop(p0.y, p0.x, p1.y, p1.x);
5321 template<
typename _Tp>
inline
5322 void ImageBase<_Tp>::crop(Rect rect)
5324 crop(rect.y, rect.x, rect.y + rect.height, rect.y + rect.width);
5327 template<
typename _Tp>
inline
5328 void ImageBase<_Tp>::detach()
5330 if (data_.use_count() < 2)
return;
5332 std::shared_ptr<std::vector<_Tp>> tmp = std::make_shared<std::vector<_Tp>>();
5342 #endif //END _ZUPPLY_ZUPPLY_HPP_
Size_< _Tp > size() const
Get size of rectangle.
void detach_all_sinks()
Detach all sinks from this logger.
Definition: zupply.cpp:13514
Definition: zupply.hpp:1115
void load(const char *filename)
load Load image from disk file, HDR image(*.hdr) supported.
Definition: zupply.cpp:13848
void from_normal(const Image &from, float range=1.0f)
from_normal Convert from an 8-bit image.
Definition: zupply.cpp:13882
void to_utc_time()
Convert to UTC time zone.
Definition: zupply.cpp:11208
Directory(std::string root, bool recursive=false)
Directory constructor.
Definition: zupply.cpp:10821
std::u16string utf8_to_utf16(std::string u8str)
C++ 11 UTF-8 string to UTF-16 string.
Definition: zupply.cpp:10673
int log_level_mask()
Get default log level mask.
Definition: zupply.cpp:13435
void resume()
Resume timer.
Definition: zupply.cpp:11264
static void set_default_datetime_format(std::string dateFormat)
Set default datetime format for all future loggers.
Definition: zupply.cpp:13410
int round(double value)
fast round utilizing hardware acceleration features
Definition: zupply.hpp:951
std::string endl()
Gets the OS dependent line end characters.
Definition: zupply.cpp:11766
std::size_t size() const
Return number of contained directories or files.
Definition: zupply.hpp:2205
const_iterator cbegin() const
Return const begin iterator.
Definition: zupply.hpp:2193
Rect_< double > Rect2d
Rect2d Double version.
Definition: zupply.hpp:543
Exception for signalling memory errors.
Definition: zupply.hpp:244
ArgParser()
ArgParser default constructor.
Definition: zupply.cpp:12502
std::string next_line(bool trimWhiteSpaces=false)
Get next line.
Definition: zupply.cpp:11112
const_iterator cend() const
Return const end iterator.
Definition: zupply.hpp:2199
void replace_all_with_escape(std::string &str, const std::string &replaceWhat, const std::string &replaceWith)
Replace every occurance of one string with specified another string. Replace in-place.
Definition: zupply.cpp:10605
void add_opt_version(char shortKey, std::string longKey, std::string version, std::string help="print version and exit")
Add a special option used to display version information for argument parser. When triggered...
Definition: zupply.cpp:12586
void replace_sequential_with_escape(std::string &str, const std::string &replaceWhat, const std::vector< std::string > &replaceWith)
Replace every occurance of one string with specified list of strings sequentially. Replace in-place.
Definition: zupply.cpp:10623
Value operator[](const std::string &name)
Overloaded operator [] for config values.
Definition: zupply.hpp:2959
Exception for signalling unsuccessful cast operations.
Definition: zupply.hpp:220
bool operator!=(const Size_ &other)
Compare operator.
bool movefile(std::string src, std::string dst, bool replaceDst)
Move file, support unicode filename/path.
Definition: zupply.cpp:11614
int goto_line(int n)
Count number of lines in text file If reached end of file, will return the number of lines...
Definition: zupply.cpp:11134
std::string version() const
Return version info.
Definition: zupply.hpp:3202
bool create_directory_recursive(std::string path)
Create directory recursively if not exist.
Definition: zupply.cpp:11984
Definition: zupply.hpp:1265
A simple spin lock utilizing c++11 atomic_flag.
Definition: zupply.hpp:1062
bool open(std::string filename, bool truncateOrNot=false, int retryTimes=consts::kDefaultFileOpenRetryTimes, int retryInterval=consts::kDefaultFileOpenRetryInterval)
Open file.
Definition: zupply.cpp:10999
bool is_file(std::string path)
Check if path is file and exists.
Definition: zupply.cpp:11849
ArgOption & require(bool require=true)
Set this option to required or not. After parsing arguments, if this set to required but not found...
Definition: zupply.cpp:12364
void add_opt_help(char shortKey, std::string longKey, std::string help="print this help and exit")
Add a special option used to display help information for argument parser. When triggered, program will print help info and exit.
Definition: zupply.cpp:12575
void unlock_loggers()
Unlock all loggers. When locked, loggers cannot be modified.
Definition: zupply.cpp:13696
std::string path_split_extension(std::string path)
Split extension if any.
Definition: zupply.cpp:11531
std::string elapsed_us_str()
Return string of elapsed time quantized in microsecond.
Definition: zupply.cpp:11288
A null mutex, no cost.
Definition: zupply.hpp:1049
SinkPtr new_rotate_file_sink(std::string filename, std::size_t maxSizeInByte, bool backupOld)
Create new rotate file sink.
Definition: zupply.cpp:13660
ImageHdr()
ImageHdr Default(empty) constructor.
Definition: zupply.hpp:831
std::pair< std::string, std::string > split_first_occurance(const std::string s, char delim)
Split string in two parts with specified delim.
Definition: zupply.cpp:10522
The 2D size class The class represents the size of a 2D rectangle, image size, matrix size etc...
Definition: zupply.hpp:268
bool create_directory(std::string path)
Create directory if not exist.
Definition: zupply.cpp:11965
Value(const char *cstr)
Value constructor from raw string.
Definition: zupply.hpp:2804
CfgParser(std::string filename)
CfgParser constructor from filename.
Definition: zupply.cpp:12230
T load()
Template for load function with no input.
Definition: zupply.hpp:2889
void save(const char *filename, int quality=80) const
save Save image to file.
Definition: zupply.cpp:13787
void resize(Size sz)
resize Resize image given new size
Definition: zupply.cpp:13833
The ArgOption class for ArgParser.
Definition: zupply.hpp:2985
double ddot(const Point_ &pt) const
dot product computed in double-precision arithmetics
Namespace for zupply.
Definition: zupply.cpp:103
double cross(const Point_ &pt) const
cross-product
int count(char shortKey)
Count the occurance of the option by short key.
Definition: zupply.cpp:12887
std::string lskip(std::string str, std::string delim)
Skip from left until delimiter string found.
Definition: zupply.cpp:10427
std::string utf32_to_utf8(std::u32string u32str)
C++ 11 UTF-32 string to UTF-8 string.
Definition: zupply.cpp:10716
CfgParser(std::istream &s)
CfgParser constructor from stream.
Definition: zupply.hpp:2946
std::vector< std::string > list_directory(std::string root)
List directory contents.
Definition: zupply.cpp:12005
std::string store(T t)
Store value from template type T Support type that can << to a stringstream.
Definition: zupply.hpp:3288
std::string abs_path() const
Return Absolute path.
Definition: zupply.cpp:10762
bool remove_all(std::string path)
Remove path, whatever file or directory. Dangerous! Cannot revert.
Definition: zupply.cpp:11623
bool operator==(const Value &other)
Overloaded operator == for comparison.
Definition: zupply.hpp:2840
std::string filename() const
FileReader move constructor.
Definition: zupply.hpp:2402
void attach_console()
Attach stdout and stderr to the logger. Special case of attach_sink()
Definition: zupply.cpp:13602
static LogConfig & instance()
Get instance of LogConfig class. LogConfig is a singleton class, so use this to get the instance...
Definition: zupply.cpp:13399
Point_< double > Point2d
Point2d Double version.
Definition: zupply.hpp:428
void release()
release Destroy memory storage
std::string str() const
Return stored string.
Definition: zupply.hpp:2822
Definition: zupply.hpp:1089
void set_log_level_mask(int newMask)
Set default log level mask.
Definition: zupply.cpp:13440
std::size_t count_error()
Get error count generated during parsing.
Definition: zupply.hpp:3216
Exception for signalling argument errors.
Definition: zupply.hpp:196
ArgOption & call(std::function< void()> todo)
Set callback function when this option is triggered. One can use lambda function as callback...
Definition: zupply.cpp:12345
std::string name() const
Get name of the logger.
Definition: zupply.hpp:3792
static DateTime utc_time()
Static function to return in utc_time.
Definition: zupply.cpp:11237
std::string ltrim(std::string str)
Left trim whitespace.
Definition: zupply.cpp:10390
std::string to_string(const char *format="%y-%m-%d %H:%M:%S.%frac")
Convert date to user friendly string. Support various formats.
Definition: zupply.cpp:11213
_Tp at(int row, int col, int channel=0) const
at Access pixel, immutable version. This is guanranteed to be faster than () operator if you don't ne...
LoggerPtr get_logger(std::string name, bool createIfNotExists)
Get logger by name.
Definition: zupply.cpp:13580
bool empty() const
Check if path is empty.
Definition: zupply.cpp:10741
Point_< int > Point2i
Point2i Int version.
Definition: zupply.hpp:418
std::string absolute_path(std::string reletivePath)
Convert reletive path to absolute path.
Definition: zupply.cpp:11896
void drop_all_loggers()
Delete all loggers.
Definition: zupply.cpp:13706
_Tp & operator()(int row, int col, int channel=0)
operator () Access pixel element
std::vector< std::string > sink_list()
Get default sink list.
Definition: zupply.cpp:13425
void set_sink_list(std::vector< std::string > &list)
Set default sink list.
Definition: zupply.cpp:13430
void dump_loggers(std::ostream &out)
Dump all loggers info.
Definition: zupply.cpp:13629
void step(unsigned size=1)
Step forward for the progress.
Definition: zupply.cpp:12945
void sleep(int milliseconds)
Sleep for specified milliseconds.
Definition: zupply.hpp:2053
Exception for signalling logic errors.
Definition: zupply.hpp:184
ArgOption & set_max(int maxCount)
Set maximum number of argument this option take. If maximum number not satisfied, ArgParser will gene...
Definition: zupply.cpp:12388
bool starts_with(const std::string &str, const std::string &start)
Check if string starts with specified sub-string.
Definition: zupply.cpp:10560
SinkPtr get_sink(std::string name)
Get the sink pointer from name provided. Return nullptr if sink does not exist.
Definition: zupply.cpp:13614
std::string datetime_format()
Get default datetime format.
Definition: zupply.cpp:13455
The Path class to resolve filesystem path.
Definition: zupply.hpp:2078
bool is_directory(std::string path)
Check if path is directory and exists.
Definition: zupply.cpp:11867
CfgLevel & root()
Get root section of configuration.
Definition: zupply.hpp:2952
detail::LineLogger error()
Error level overloaded with stream style message.
Definition: zupply.cpp:13482
ProgBar(unsigned range=100, std::string info="")
Constructor of ProgBar.
Definition: zupply.cpp:12929
bool is_file() const
Check if path is a file and exist.
Definition: zupply.cpp:10752
Definition: zupply.hpp:1233
void drop_sink(std::string name)
Delete the sink, detach it from every logger.
Definition: zupply.cpp:13711
void attach_sink(SinkPtr sink)
Attach a sink to this logger.
Definition: zupply.cpp:13501
void clear()
Clear stored string.
Definition: zupply.hpp:2833
Rect_< int > Rect2i
Rect2i Int version.
Definition: zupply.hpp:533
std::string wstring_to_utf8(std::wstring &wstr)
Convert wstring to UTF-8.
Definition: zupply.cpp:11470
void fstream_open(std::fstream &stream, std::string filename, std::ios::openmode openmode)
Open fstream using UTF-8 string This is a wrapper function because Windows will require wstring to pr...
Definition: zupply.cpp:11570
SinkPtr new_stdout_sink()
Get the sink pointer to stdout.
Definition: zupply.cpp:13592
std::vector< std::string > path_split(std::string path)
Split path into hierachical sub-folders.
Definition: zupply.cpp:11483
An exception with customized prefix information.
Definition: zupply.hpp:161
std::size_t elapsed_ms()
Return elapsed time quantized in millisecond.
Definition: zupply.cpp:11293
bool exist() const
Check path existance, whatever file/dir/device...
Definition: zupply.cpp:10746
bool ends_with(const std::string &str, const std::string &end)
Check if string ends with specified sub-string.
Definition: zupply.cpp:10565
bool path_exists(std::string path, bool considerFile)
Check if path exist in filesystem.
Definition: zupply.cpp:11833
Exception for signalling warning errors when strict warning is enabled.
Definition: zupply.hpp:256
static void set_default_format(std::string format)
Set default format for all future loggers.
Definition: zupply.cpp:13405
The general functor Callback class.
Definition: zupply.hpp:1022
The ImageHdr class. Image container specifically good for HDR images which uses 32bit float precison...
Definition: zupply.hpp:825
The FileEditor class to modify file This class is derived from UnCopyable, so no copy operation...
Definition: zupply.hpp:2261
bool copyfile(std::string src, std::string dst, bool replaceDst)
Copy file, support unicode filename/path.
Definition: zupply.cpp:11599
Logger(std::string name)
Logger default constructor.
Definition: zupply.hpp:3623
Value(const Value &other)
Value copy constructor.
Definition: zupply.hpp:2816
SinkPtr new_stderr_sink()
Get the sink pointer to stderr.
Definition: zupply.cpp:13597
void config_from_stringstream(std::stringstream &ss)
Config loggers from a stringstream.
Definition: zupply.cpp:13757
void format_string(std::string &fmt, const Arg &last)
Format function to replace each {} with templated type variable.
Definition: zupply.hpp:2758
int is_atty()
Check if stdout is associated with console.
Definition: zupply.cpp:11402
std::string utf16_to_utf8(std::u16string u16str)
C++ 11 UTF-16 string to UTF-8 string.
Definition: zupply.cpp:10687
detail::LineLogger fatal()
Fatal level overloaded with stream style message.
Definition: zupply.cpp:13486
bool inside(const Rect_< _Tp > &r) const
checks whether the point is inside the specified rectangle
Point_< float > Point2f
Point2f Float version.
Definition: zupply.hpp:423
SinkPtr new_simple_file_sink(std::string filename, bool truncate)
Create new simple file sink withe filename provided.
Definition: zupply.cpp:13650
void add_info(std::string info)
Add info to parser.
Definition: zupply.cpp:12508
std::string filename() const
Return filename.
Definition: zupply.hpp:2301
Image()
Image Default(empty) constructor.
Definition: zupply.hpp:772
void reset()
Reset timer to record new process.
Definition: zupply.cpp:11249
std::string to_upper_ascii(std::string mixed)
Convert string to upper case. Support ASCII characters only. Unicode string will trigger undefined be...
Definition: zupply.cpp:10667
std::string elapsed_ns_str()
Return string of elapsed time quantized in nanosecond.
Definition: zupply.cpp:11278
bool is_dir() const
Check if path is a directory and exist.
Definition: zupply.cpp:10757
Logger(std::string name, int levelMask)
Logger constructor with name and mask.
Definition: zupply.hpp:3633
void parse(int argc, char **argv, bool ignoreUnknown=false)
Start parsing arguments.
Definition: zupply.cpp:12708
ArgOption(char shortKey, std::string longKey)
ArgOption constructor with short key and long key.
Definition: zupply.cpp:12332
ArgOption & add_opt(char shortKey, std::string longKey)
Add option. Use -1 for shortkey if you don't want to specify short key. Use "" for longkey if you don...
Definition: zupply.cpp:12560
bool is_recursive() const
Check if directory is resursively searched.
Definition: zupply.cpp:10848
Rect_()
Default constructor.
std::string path_split_filename(std::string path)
Split filename from path.
Definition: zupply.cpp:11502
The Directory class for filesystem directory operations.
Definition: zupply.hpp:2140
int cols() const
cols Get number of columns(width, x...)
Value(std::string str)
Value constrctor from string.
Definition: zupply.hpp:2810
std::string lstrip(std::string str, std::string what)
Strip specified sub-string from left. The strip will do strict check from left, even whitespace...
Definition: zupply.cpp:10407
A not movable/copyable base class, should be inheritated privately.
Definition: zupply.hpp:142
bool is_valid() const
Check if valid filename is set.
Definition: zupply.hpp:2414
ArgOption & set_once(bool onlyOnce=true)
Set this option to allow option be called only once. This is set to disable accidentally set a variab...
Definition: zupply.cpp:12370
A calendar date class.
Definition: zupply.hpp:1910
The Logger class Logger is the object to be called to log some message. Each logger may links to seve...
Definition: zupply.hpp:3616
static DateTime local_time()
Static function to return in local_time.
Definition: zupply.cpp:11231
static void set_default_level_mask(int levelMask)
Set default level mask for all future loggers. Level mask is an int. Each bit control if correspondin...
Definition: zupply.cpp:13420
void create(int rows, int cols, int channels)
create Create storage with specified size
int rows() const
rows Get number of rows(height, y...)
bool str_equals(const char *s1, const char *s2)
Compare c style raw string Will take care of string not ends with '\0'(ignore it), which is unsafe using strcmp().
Definition: zupply.cpp:10643
_Tp dot(const Point_ &pt) const
dot product
std::string get_help()
Get help information of entire parser.
Definition: zupply.cpp:12816
std::size_t elapsed_ns()
Return elapsed time quantized in nanosecond.
Definition: zupply.cpp:11271
bool rename(std::string oldName, std::string newName)
Rename file, support unicode filename/path.
Definition: zupply.cpp:11590
bool contains(const Point_< _Tp > &pt) const
Checks whether the rectangle contains the point.
std::string elapsed_ms_str()
Return string of elapsed time quantized in millisecond.
Definition: zupply.cpp:11298
bool operator==(const Size_ &other)
Compare operator.
_Tp y
the point coordinates
Definition: zupply.hpp:412
Value get_value()
Return the stored value.
Definition: zupply.cpp:12395
SinkPtr get_sink(std::string name)
Get pointer to a sink by name.
Definition: zupply.cpp:13491
detail::LineLogger trace()
Trace level overloaded with stream style message.
Definition: zupply.cpp:13466
std::string to_string(const char *format="[%ms ms]")
Convert timer to user friendly string. Support various formats.
Definition: zupply.cpp:11318
std::size_t elapsed_sec()
Return elapsed time quantized in second.
Definition: zupply.cpp:11303
Exception for signalling unexpected runtime errors.
Definition: zupply.hpp:208
_Tp * ptr(int offset=0) const
ptr Data pointer given specifed position. Use with cautious. This is provided for performance conside...
std::string rtrim(std::string str)
Right trim whitespace.
Definition: zupply.cpp:10396
Point2i Point
Point By default using Point2i.
Definition: zupply.hpp:433
Point_()
Default constructor.
std::vector< std::string > split(const std::string s, char delim)
Split string into parts with specified single char delimiter.
Definition: zupply.cpp:10468
void ifstream_open(std::ifstream &stream, std::string filename, std::ios::openmode openmode)
Open ifstream using UTF-8 string This is a wrapper function because Windows will require wstring to p...
Definition: zupply.cpp:11581
std::string last_error()
Retrieve the last error in errno.
Definition: zupply.cpp:11733
~ProgBar()
Destructor will stop background thread.
Definition: zupply.cpp:12940
std::string trim(std::string str)
Left and right trim whitespace.
Definition: zupply.cpp:10402
void detach_console()
Detach stdout and stderr from the logger if exist. Special case of detach_sink()
Definition: zupply.cpp:13608
_Tp height
the top-left corner, as well as width and height of the rectangle
Definition: zupply.hpp:527
The Value class for store/load various type to/from string.
Definition: zupply.hpp:2792
void attach_sink_list(std::vector< std::string > &sinkList)
Attach the entire vector of sinks to the logger.
Definition: zupply.cpp:13670
void to_local_time()
Convert to local time zone.
Definition: zupply.cpp:11203
std::string int_to_zero_pad_str(int num, int length)
Convert int to left zero padded string.
Definition: zupply.hpp:2494
std::vector< std::string > split_multi_delims(const std::string s, std::string delims)
Split string into parts with multiple single char delimiter.
Definition: zupply.cpp:10495
std::size_t count_lines()
Count number of lines in text file.
Definition: zupply.cpp:11077
_Tp area() const
Get area of rectagle.
std::u32string utf8_to_utf32(std::string u8str)
C++ 11 UTF-8 string to UTF-32 string.
Definition: zupply.cpp:10702
std::string join(std::vector< std::string > elems, char delim)
Concatenates a std::vector of strings into a string with delimiters.
Definition: zupply.cpp:10546
std::vector< std::string > split_whitespace(const std::string s)
Special case to split_multi_delims(), split all whitespace.
Definition: zupply.cpp:10510
void close()
Close file handler.
Definition: zupply.hpp:2419
ArgOption & add_opt_flag(char shortKey, std::string longKey, std::string help="", bool *dst=nullptr)
Add an toggle option. When this option found, dst = true, otherwise dst = false.
Definition: zupply.cpp:12598
bool is_digit(char c)
Check if is digit.
Definition: zupply.cpp:10361
bool empty() const
Check if stored string is empty.
Definition: zupply.hpp:2828
std::string elapsed_sec_str()
Return string of elapsed time quantized in second.
Definition: zupply.cpp:11308
_Tp area() const
area Calculate area
std::string path_delim()
Gets the OS dependent path delim.
Definition: zupply.cpp:11775
std::string path_split_basename(std::string path)
Split basename.
Definition: zupply.cpp:11542
void pause()
Pause recording timelapse.
Definition: zupply.cpp:11256
iterator end()
Return end iterator.
Definition: zupply.hpp:2187
bool should_log(LogLevels msgLevel) const
Check if a specific level should be logged in this logger.
Definition: zupply.hpp:3783
std::tm gmtime(std::time_t t)
Thread-safe version of gmtime.
Definition: zupply.cpp:11443
std::string rskip_all(std::string str, std::string delim)
Skip from right, remove all stuff right to left-most delim.
Definition: zupply.cpp:10455
Definition: zupply.hpp:1148
bool is_open() const
Check if is opened.
Definition: zupply.hpp:2408
std::size_t get_file_size(std::string filename)
Get file size in byte.
Definition: zupply.cpp:11167
std::string relative_path() const
Return relative path to current working directory.
Definition: zupply.cpp:10767
Size console_size()
Return the Size of console window.
Definition: zupply.cpp:11412
static void set_default_sink_list(std::vector< std::string > list)
Set default sink list for all future loggers.
Definition: zupply.cpp:13415
double elapsed_sec_double()
Return elapsed time in second, no quantization.
Definition: zupply.cpp:11313
detail::LineLogger info()
Info level overloaded with stream style message.
Definition: zupply.cpp:13474
std::size_t elapsed_us()
Return elapsed time quantized in microsecond.
Definition: zupply.cpp:11283
void config_from_file(std::string cfgFilename)
Config loggers from a config file.
Definition: zupply.cpp:13751
std::string root() const
Return root of directory.
Definition: zupply.cpp:10853
ImageHdr(int rows, int cols, int channels)
ImageHdr Constructor given specific size.
Definition: zupply.hpp:839
std::string rstrip(std::string str, std::string what)
Strip specified sub-string from right. The strip will do strict check from right, even whitespace...
Definition: zupply.cpp:10417
void detach_sink(SinkPtr sink)
Detach a sink from this logger.
Definition: zupply.cpp:13509
const T clip(const T &value, const T &low, const T &high)
Clip values in-between low and high values.
Definition: zupply.hpp:920
std::vector< std::string > & erase_empty(std::vector< std::string > &vec)
Go through vector and erase empty ones. Erase in-place in vector.
Definition: zupply.cpp:10530
Rect_ & operator=(const Rect_ &r)
Copy operator.
Base image storage class This defines the storage and pixel-wise access to a image like 3-D matrix...
Definition: zupply.hpp:556
Definition: zupply.hpp:933
ImageBase & operator=(const ImageBase &other)
operator = Copy operator, again, shallow copy
Value & operator=(const Value &other)
Overloaded operator = for copy.
Definition: zupply.hpp:2847
void set_datetime_format(std::string newDatetimeFormat)
Set default datetime format.
Definition: zupply.cpp:13460
Point_< _Tp > br() const
Get bottom right corner point.
detail::LineLogger debug()
Debug level overloaded with stream style message.
Definition: zupply.cpp:13470
Definition: zupply.hpp:1350
std::wstring utf8_to_wstring(std::string &u8str)
Convert UTF-8 string to wstring.
Definition: zupply.cpp:11457
void set_level_mask(int levelMask)
Set level mask to this logger.
Definition: zupply.hpp:3773
std::string to_lower_ascii(std::string mixed)
Convert string to lower case. Support ASCII characters only. Unicode string will trigger undefined be...
Definition: zupply.cpp:10661
FileEditor & operator<<(T what)
Overload << operator just like a stream.
Definition: zupply.hpp:2295
SinkPtr new_ostream_sink(std::ostream &stream, std::string name, bool forceFlush)
Create new ostream sink from existing ostream.
Definition: zupply.cpp:13640
int get_count()
Return the count.
Definition: zupply.cpp:12400
std::vector< Point > Vecpts
Vecpts 1-D vector of points.
Definition: zupply.hpp:438
bool empty() const
empty Check empty or not
ArgOption & set_type(std::string type)
Set option variable type. Optional. Let user know what type this option take, INT, FLOAT, STRING...
Definition: zupply.cpp:12376
The Progress bar class. For simple progress bar.
Definition: zupply.hpp:3399
std::vector< Path > to_list() const
Return the entire list.
Definition: zupply.cpp:10858
std::string filename() const
Return filename if is file and exist. Will return empty string if path is not a file.
Definition: zupply.cpp:10815
Definition: zupply.hpp:2480
bool reopen(bool truncateOrNot=true)
Reopen current file.
Definition: zupply.cpp:11008
bool wild_card_match(const char *str, const char *pattern)
Match string with wildcard. Match string with wildcard pattern, '*' and '?' supported.
Definition: zupply.cpp:10366
The FileReader class for read-only operations. This class is derived from UnCopyable, so no copy operation. Move operation is allowed by std::move();.
Definition: zupply.hpp:2378
The 2D up-right rectangle class The class represents a 2D rectangle with coordinates of the specified...
Definition: zupply.hpp:344
Point_< _Tp > tl() const
Get top left corner point.
The Image class. Image container for 8-bit image manipulation including read/write. Image is based on detail::ImageBase.
Definition: zupply.hpp:766
void lock_loggers()
Lock all loggers. When locked, loggers cannot be modified.
Definition: zupply.cpp:13691
void drop_logger(std::string name)
Delete a logger with the name given.
Definition: zupply.cpp:13701
void flush()
Flush file stream.
Definition: zupply.hpp:2361
ArgOption & set_help(std::string helpInfo)
Set help info for this option. Use this to add description for this option.
Definition: zupply.cpp:12358
std::string path_append_basename(std::string origPath, std::string whatToAppend)
Append string to basename directly, rather than append to extension This is more practically useful b...
Definition: zupply.cpp:11557
A timer class.
Definition: zupply.hpp:1959
bool is_valid() const
Check whether current file handler is set.
Definition: zupply.hpp:2350
std::string & replace_all(std::string &str, char replaceWhat, char replaceWith)
Replace all from one to another sub-string, char version.
Definition: zupply.cpp:10570
bool path_identical(std::string first, std::string second, bool forceCaseSensitve)
Compare identical path according to OS. By default, windows paths are case-INsensitive.
Definition: zupply.cpp:11883
void load(const char *filename)
load Load image from file.
Definition: zupply.cpp:13770
std::tm localtime(std::time_t t)
Thread-safe version of localtime.
Definition: zupply.cpp:11429
Exception for signalling unexpected IO errors.
Definition: zupply.hpp:232
Value operator[](const std::string &longKey)
Overloaded operator [] to retrieve the value by long key.
Definition: zupply.cpp:12899
void save_hdr(const char *filename) const
save_hdr Save to HDR image
Definition: zupply.cpp:13865
ArgOption & add_opt_value(char shortKey, std::string longKey, T &dst, T defaultValue, std::string help="", std::string type="", int min=1, int max=1)
Template function for an option take a value. This will store the value from argument to dst...
Definition: zupply.hpp:3342
Point_ & operator=(const Point_ &pt)
Copy operator.
int channels() const
channels Get number of channels
Value()
Value default constructor.
Definition: zupply.hpp:2798
void crop(int r0, int c0, int r1, int c1)
crop Crop image given coordinates.
std::string get_error()
Get all errors generated during parsing.
Definition: zupply.cpp:12876
std::string current_working_directory()
Get current working directory.
Definition: zupply.cpp:11784
void replace_first_with_escape(std::string &str, const std::string &replaceWhat, const std::string &replaceWith)
Replace first occurance of one string with specified another string. Replace in-place.
Definition: zupply.cpp:10587
The CfgLevel struct, internal struct for cfgParser. Tree structure for config sections.
Definition: zupply.hpp:2899
The ArgParser class. For parsing command line arguments.
Definition: zupply.hpp:3113
ArgOption & set_min(int minCount)
Set minimum number of argument this option take. If minimum number not satisfied, ArgParser will gene...
Definition: zupply.cpp:12382
Rect_< float > Rect2f
Rect2f Float version.
Definition: zupply.hpp:538
std::string format()
Get default logger format.
Definition: zupply.cpp:13445
The LogConfig class. For get/set logging configurations.
Definition: zupply.hpp:3518
void unused(const T &)
Suppress warning for unused variables, do nothing actually.
Definition: zupply.hpp:995
The CfgParser class for INI/CFG file parsing.
Definition: zupply.hpp:2933
void close()
Close current file.
Definition: zupply.cpp:11014
void set_format(std::string newFormat)
Set default logger format.
Definition: zupply.cpp:13450
Size_ & operator=(const Size_ &sz)
Copy operator.
bool remove_file(std::string path)
Remove file. Dangerous! Cannot revert.
Definition: zupply.cpp:11723
void resize(Size sz)
resize Resize image given new size
Definition: zupply.cpp:13914
Image to_normal(float range=1.0f) const
to_normal Convert to 8-bit image(lose precision)
Definition: zupply.cpp:13870
bool remove_dir(std::string path, bool recursive)
Remove directory and all sub-directories and files if set recursive to true. If recursive set to fals...
Definition: zupply.cpp:11644
void filter(const std::string pattern)
Filter directory with specified pattern.
Definition: zupply.cpp:10895
template 2D point class. The class defines a point in 2D space. Data type of the point coordinates is...
Definition: zupply.hpp:351
std::vector< Value > arguments() const
Return all input arguments that does not belong to any option.
Definition: zupply.cpp:12513
Image(int rows, int cols, int channels)
Image Constructor with specified size.
Definition: zupply.hpp:780
Rect2i Rect
Rect By default use Rect2i, int version.
Definition: zupply.hpp:548
bool is_open() const
Check if file is opened.
Definition: zupply.hpp:2356
int system(const char *const command, const char *const moduleName)
Execute sub-process using system call.
Definition: zupply.cpp:11343
std::string path_join(std::vector< std::string > elems)
Join path from sub-folders This function will handle system dependent path formats such as '/' for un...
Definition: zupply.cpp:11493
ImageBase()
ImageBase Default(empty) constructor.
std::size_t thread_id()
Get thread id.
Definition: zupply.cpp:11380
std::string to_string()
Get user friendly information about this logger. Get informations such as log levels, sink list, etc...
Definition: zupply.cpp:13528
void reset()
Clear filter pattern, redo search in directory.
Definition: zupply.cpp:10952
A not copyable base class, should be inheritated privately.
Definition: zupply.hpp:127
void stop()
Stop the progress bar. Don't call this manully unless you know what u r doing. This will automaticall...
Definition: zupply.cpp:13004
std::size_t file_size()
Get file size in byte, member function.
Definition: zupply.cpp:11064
iterator begin()
Return begin iterator.
Definition: zupply.hpp:2181
detail::LineLogger warn()
Warn level overloaded with stream style message.
Definition: zupply.cpp:13478
std::string rskip(std::string str, std::string delim)
Skip from right until delimiter string found.
Definition: zupply.cpp:10441
std::string path_split_directory(std::string path)
Split the deepest directory.
Definition: zupply.cpp:11517
CfgLevel & operator()(const std::string &name)
Overloaded operator () for config sections.
Definition: zupply.hpp:2966