ithewei %!s(int64=7) %!d(string=hai) anos
pai
achega
dd85a6f2a0
Modificáronse 16 ficheiros con 1955 adicións e 1954 borrados
  1. 39 39
      README.md
  2. 204 204
      hbuf.h
  3. 56 56
      hendian.h
  4. 42 42
      herr.cpp
  5. 73 73
      herr.h
  6. 77 77
      hfile.h
  7. 87 87
      hframe.h
  8. 27 27
      hgl.h
  9. 71 71
      hgui.h
  10. 92 92
      hlog.cpp
  11. 52 52
      hlog.h
  12. 129 129
      hthreadpool.h
  13. 234 234
      iniparser.cpp
  14. 116 116
      iniparser.h
  15. 4 3
      main.cpp.tmpl
  16. 652 652
      msvc_getopt.h

+ 39 - 39
README.md

@@ -1,40 +1,40 @@
-## Intro
-
-hw 是一套跨平台c++工具集,类名以H开头
-
-## platform
-
-- gcc
-- mingw
-- msvc
-
-## required
-
-- c++11
-
-## Module
-
-- h.h:总头文件
-- hversion.h: 版本
-- hdef.h: 宏定义
-- hplatform.h: 平台相关
-- hendian.h: 大小端
-- hlog.h: 日志
-- herr.h: 错误码
-- htime.h: 时间
-- hstring.h: 字符串
-- hfile.h: 文件类
-- hthread.h:线程
-- hthreadpool.h:线程池
-- hmutex.h:同步锁
-- hobj.h: 对象基类
-- hvar.h: var变量
-- hbuf.h: 缓存类
-- iniparser.h: ini解析
-- hscope.h: 作用域RAII机制
-- singleton.h: 单例模式
-
-## other
-
-- Makefile: 通用Makefile模板
+## Intro
+
+hw 是一套跨平台c++工具集,类名以H开头
+
+## platform
+
+- gcc
+- mingw
+- msvc
+
+## required
+
+- c++11
+
+## Module
+
+- h.h:总头文件
+- hversion.h: 版本
+- hdef.h: 宏定义
+- hplatform.h: 平台相关
+- hendian.h: 大小端
+- hlog.h: 日志
+- herr.h: 错误码
+- htime.h: 时间
+- hstring.h: 字符串
+- hfile.h: 文件类
+- hthread.h:线程
+- hthreadpool.h:线程池
+- hmutex.h:同步锁
+- hobj.h: 对象基类
+- hvar.h: var变量
+- hbuf.h: 缓存类
+- iniparser.h: ini解析
+- hscope.h: 作用域RAII机制
+- singleton.h: 单例模式
+
+## other
+
+- Makefile: 通用Makefile模板
 - main.cpp.tmp: 通用main.cpp模板  

+ 204 - 204
hbuf.h

@@ -1,204 +1,204 @@
-#ifndef HW_BUF_H_
-#define HW_BUF_H_
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "hdef.h"
-
-typedef struct hbuf_s {
-    uint8* base;
-    size_t len;
-    bool   cleanup_;
-
-    hbuf_s() {
-        base = NULL;
-        len  = 0;
-        cleanup_ = false;
-    }
-
-    hbuf_s(uint8* base, size_t len) {
-        this->base = base;
-        this->len  = len;
-        cleanup_ = false;
-    }
-
-    virtual ~hbuf_s() {
-        cleanup();
-    }
-
-    // warn: must call cleanup when no longer in use, otherwise memory leak.
-    void init(size_t cap) {
-        if (cap == len) return;
-
-        if (!base) {
-            base = (uint8*)malloc(cap);
-            memset(base, 0, cap);
-        } else {
-            base = (uint8*)realloc(base, cap);
-        }
-        len = cap;
-        cleanup_ = true;
-    }
-
-    void resize(size_t cap) {
-        init(cap);
-    }
-
-    void cleanup() {
-        if (cleanup_) {
-            SAFE_FREE(base);
-            len = 0;
-            cleanup_ = false;
-        }
-    }
-
-    bool isNull() {
-        return base == NULL || len == 0;
-    }
-} hbuf_t;
-
-class HBuf : public hbuf_t {
- public:
-    HBuf() : hbuf_t() {}
-    HBuf(size_t cap) {init(cap);}
-    HBuf(void* data, size_t len) {
-        init(len);
-        memcpy(base, data, len);
-    }
-};
-
-// VL: Variable-Length
-class HVLBuf : public HBuf {
- public:
-    HVLBuf() : HBuf() {_offset = _size = 0;}
-    HVLBuf(size_t cap) : HBuf(cap) {_offset = _size = 0;}
-    HVLBuf(void* data, size_t len) : HBuf(data, len) {_offset = 0; _size = len;}
-    virtual ~HVLBuf() {}
-
-    uint8* data() {return base+_offset;}
-    size_t size() {return _size;}
-
-    void push_front(void* ptr, size_t len) {
-        if (len > this->len - _size) {
-            this->len = MAX(this->len, len)*2;
-            base = (uint8*)realloc(base, this->len);
-        }
-
-        if (_offset < len) {
-            // move => end
-            memmove(base+this->len-_size, data(), _size);
-            _offset = this->len-_size;
-        }
-
-        memcpy(data()-len, ptr, len);
-        _offset -= len;
-        _size += len;
-    }
-
-    void push_back(void* ptr, size_t len) {
-        if (len > this->len - _size) {
-            this->len = MAX(this->len, len)*2;
-            base = (uint8*)realloc(base, this->len);
-        } else if (len > this->len - _offset - _size) {
-            // move => start
-            memmove(base, data(), _size);
-            _offset = 0;
-        }
-        memcpy(data()+_size, ptr, len);
-        _size += len;
-    }
-
-    void pop_front(void* ptr, size_t len) {
-        if (len <= _size) {
-            if (ptr) {
-                memcpy(ptr, data(), len);
-            }
-            _offset += len;
-            if (_offset >= len) _offset = 0;
-            _size   -= len;
-        }
-    }
-
-    void pop_back(void* ptr, size_t len) {
-        if (len <= _size) {
-            if (ptr) {
-                memcpy(ptr, data()+_size-len, len);
-            }
-            _size -= len;
-        }
-    }
-
-    void clear() {
-        _offset = _size = 0;
-    }
-
-    void prepend(void* ptr, size_t len) {
-        push_front(ptr, len);
-    }
-
-    void append(void* ptr, size_t len) {
-        push_back(ptr, len);
-    }
-
-    void insert(void* ptr, size_t len) {
-        push_back(ptr, len);
-    }
-
-    void remove(size_t len) {
-        pop_front(NULL, len);
-    }
-
- private:
-    size_t _offset;
-    size_t _size;
-};
-
-class HRingBuf : public HBuf {
- public:
-    HRingBuf() : HBuf() {_head = _tail = _size = 0;}
-    HRingBuf(size_t cap) : HBuf(cap) {_head = _tail = _size = 0;}
-
-    uint8* alloc(size_t len) {
-        uint8* ret = NULL;
-        if (_head < _tail || _size == 0) {
-            // [_tail, this->len) && [0, _head)
-            if (this->len - _tail >= len) {
-                ret = base + _tail;
-                _tail += len;
-                if (_tail == this->len) _tail = 0;
-            } else if (_head >= len) {
-                ret = base;
-                _tail = len;
-            }
-        } else {
-            // [_tail, _head)
-            if (_head - _tail >= len) {
-                ret = base + _tail;
-                _tail += len;
-            }
-        }
-        _size += ret ? len : 0;
-        return ret;
-    }
-
-    void   free(size_t len) {
-        _size -= len;
-        if (len <= this->len - _head) {
-            _head += len;
-            if (_head == this->len) _head = 0;
-        } else {
-            _head = len;
-        }
-    }
-
-    size_t size() {return _size;}
-
- private:
-    size_t _head;
-    size_t _tail;
-    size_t _size;
-};
-
-#endif  // HW_BUF_H_
+#ifndef HW_BUF_H_
+#define HW_BUF_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "hdef.h"
+
+typedef struct hbuf_s {
+    uint8* base;
+    size_t len;
+    bool   cleanup_;
+
+    hbuf_s() {
+        base = NULL;
+        len  = 0;
+        cleanup_ = false;
+    }
+
+    hbuf_s(uint8* base, size_t len) {
+        this->base = base;
+        this->len  = len;
+        cleanup_ = false;
+    }
+
+    virtual ~hbuf_s() {
+        cleanup();
+    }
+
+    // warn: must call cleanup when no longer in use, otherwise memory leak.
+    void init(size_t cap) {
+        if (cap == len) return;
+
+        if (!base) {
+            base = (uint8*)malloc(cap);
+            memset(base, 0, cap);
+        } else {
+            base = (uint8*)realloc(base, cap);
+        }
+        len = cap;
+        cleanup_ = true;
+    }
+
+    void resize(size_t cap) {
+        init(cap);
+    }
+
+    void cleanup() {
+        if (cleanup_) {
+            SAFE_FREE(base);
+            len = 0;
+            cleanup_ = false;
+        }
+    }
+
+    bool isNull() {
+        return base == NULL || len == 0;
+    }
+} hbuf_t;
+
+class HBuf : public hbuf_t {
+ public:
+    HBuf() : hbuf_t() {}
+    HBuf(size_t cap) {init(cap);}
+    HBuf(void* data, size_t len) {
+        init(len);
+        memcpy(base, data, len);
+    }
+};
+
+// VL: Variable-Length
+class HVLBuf : public HBuf {
+ public:
+    HVLBuf() : HBuf() {_offset = _size = 0;}
+    HVLBuf(size_t cap) : HBuf(cap) {_offset = _size = 0;}
+    HVLBuf(void* data, size_t len) : HBuf(data, len) {_offset = 0; _size = len;}
+    virtual ~HVLBuf() {}
+
+    uint8* data() {return base+_offset;}
+    size_t size() {return _size;}
+
+    void push_front(void* ptr, size_t len) {
+        if (len > this->len - _size) {
+            this->len = MAX(this->len, len)*2;
+            base = (uint8*)realloc(base, this->len);
+        }
+
+        if (_offset < len) {
+            // move => end
+            memmove(base+this->len-_size, data(), _size);
+            _offset = this->len-_size;
+        }
+
+        memcpy(data()-len, ptr, len);
+        _offset -= len;
+        _size += len;
+    }
+
+    void push_back(void* ptr, size_t len) {
+        if (len > this->len - _size) {
+            this->len = MAX(this->len, len)*2;
+            base = (uint8*)realloc(base, this->len);
+        } else if (len > this->len - _offset - _size) {
+            // move => start
+            memmove(base, data(), _size);
+            _offset = 0;
+        }
+        memcpy(data()+_size, ptr, len);
+        _size += len;
+    }
+
+    void pop_front(void* ptr, size_t len) {
+        if (len <= _size) {
+            if (ptr) {
+                memcpy(ptr, data(), len);
+            }
+            _offset += len;
+            if (_offset >= len) _offset = 0;
+            _size   -= len;
+        }
+    }
+
+    void pop_back(void* ptr, size_t len) {
+        if (len <= _size) {
+            if (ptr) {
+                memcpy(ptr, data()+_size-len, len);
+            }
+            _size -= len;
+        }
+    }
+
+    void clear() {
+        _offset = _size = 0;
+    }
+
+    void prepend(void* ptr, size_t len) {
+        push_front(ptr, len);
+    }
+
+    void append(void* ptr, size_t len) {
+        push_back(ptr, len);
+    }
+
+    void insert(void* ptr, size_t len) {
+        push_back(ptr, len);
+    }
+
+    void remove(size_t len) {
+        pop_front(NULL, len);
+    }
+
+ private:
+    size_t _offset;
+    size_t _size;
+};
+
+class HRingBuf : public HBuf {
+ public:
+    HRingBuf() : HBuf() {_head = _tail = _size = 0;}
+    HRingBuf(size_t cap) : HBuf(cap) {_head = _tail = _size = 0;}
+
+    uint8* alloc(size_t len) {
+        uint8* ret = NULL;
+        if (_head < _tail || _size == 0) {
+            // [_tail, this->len) && [0, _head)
+            if (this->len - _tail >= len) {
+                ret = base + _tail;
+                _tail += len;
+                if (_tail == this->len) _tail = 0;
+            } else if (_head >= len) {
+                ret = base;
+                _tail = len;
+            }
+        } else {
+            // [_tail, _head)
+            if (_head - _tail >= len) {
+                ret = base + _tail;
+                _tail += len;
+            }
+        }
+        _size += ret ? len : 0;
+        return ret;
+    }
+
+    void   free(size_t len) {
+        _size -= len;
+        if (len <= this->len - _head) {
+            _head += len;
+            if (_head == this->len) _head = 0;
+        } else {
+            _head = len;
+        }
+    }
+
+    size_t size() {return _size;}
+
+ private:
+    size_t _head;
+    size_t _tail;
+    size_t _size;
+};
+
+#endif  // HW_BUF_H_

+ 56 - 56
hendian.h

@@ -1,56 +1,56 @@
-#ifndef HW_ENDIAN_H_
-#define HW_ENDIAN_H_
-
-#include "hdef.h"
-
-#define LITTLE_ENDIAN   0
-#define BIG_ENDIAN      1
-#define NET_ENDIAN      BIG_ENDIAN
-
-int check_endian() {
-    union {
-        char c;
-        short s;
-    } u;
-    u.s = 0x1122;
-    if (u.c == 0x11) {
-        return BIG_ENDIAN;
-    }
-    return LITTLE_ENDIAN;
-}
-
-template <typename T>
-uint8* serialize(uint8* buf, T value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) {
-    size_t size = sizeof(T);
-    uint8* pDst = buf;
-    uint8* pSrc = (uint8*)&value;
-
-    if (host_endian == buf_endian) {
-        memcpy(pDst, pSrc, size);
-    } else {
-        for (int i = 0; i < size; ++i) {
-            pDst[i] = pSrc[size-i-1];
-        }
-    }
-
-    return buf+size;
-}
-
-template <typename T>
-uint8* deserialize(uint8* buf, T* value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) {
-    size_t size = sizeof(T);
-    uint8* pSrc = buf;
-    uint8* pDst = (uint8*)value;
-
-    if (host_endian == buf_endian) {
-        memcpy(pDst, pSrc, size);
-    } else {
-        for (int i = 0; i < size; ++i) {
-            pDst[i] = pSrc[size-i-1];
-        }
-    }
-
-    return buf+size;
-}
-
-#endif  // HW_ENDIAN_H_
+#ifndef HW_ENDIAN_H_
+#define HW_ENDIAN_H_
+
+#include "hdef.h"
+
+#define LITTLE_ENDIAN   0
+#define BIG_ENDIAN      1
+#define NET_ENDIAN      BIG_ENDIAN
+
+int check_endian() {
+    union {
+        char c;
+        short s;
+    } u;
+    u.s = 0x1122;
+    if (u.c == 0x11) {
+        return BIG_ENDIAN;
+    }
+    return LITTLE_ENDIAN;
+}
+
+template <typename T>
+uint8* serialize(uint8* buf, T value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) {
+    size_t size = sizeof(T);
+    uint8* pDst = buf;
+    uint8* pSrc = (uint8*)&value;
+
+    if (host_endian == buf_endian) {
+        memcpy(pDst, pSrc, size);
+    } else {
+        for (int i = 0; i < size; ++i) {
+            pDst[i] = pSrc[size-i-1];
+        }
+    }
+
+    return buf+size;
+}
+
+template <typename T>
+uint8* deserialize(uint8* buf, T* value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) {
+    size_t size = sizeof(T);
+    uint8* pSrc = buf;
+    uint8* pDst = (uint8*)value;
+
+    if (host_endian == buf_endian) {
+        memcpy(pDst, pSrc, size);
+    } else {
+        for (int i = 0; i < size; ++i) {
+            pDst[i] = pSrc[size-i-1];
+        }
+    }
+
+    return buf+size;
+}
+
+#endif  // HW_ENDIAN_H_

+ 42 - 42
herr.cpp

@@ -1,42 +1,42 @@
-#include "herr.h"
-
-#include <map>
-
-#include "hthread.h"    // for gettid
-
-// id => errcode
-static std::map<int, int>   s_mapErr;
-
-void set_id_errcode(int id, int errcode) {
-    s_mapErr[id] = errcode;
-}
-
-int  get_id_errcode(int id) {
-    auto iter = s_mapErr.find(id);
-    if (iter != s_mapErr.end()) {
-        // note: erase after get
-        s_mapErr.erase(iter);
-        return iter->second;
-    }
-    return ERR_OK;
-}
-
-void set_last_errcode(int errcode) {
-    set_id_errcode(gettid(), errcode);
-}
-
-int  get_last_errcode() {
-    return get_id_errcode(gettid());
-}
-
-const char* get_errmsg(int err) {
-    switch (err) {
-#define CASE_ERR(macro, errcode, errmsg) \
-    case errcode: \
-        return errmsg;
-    FOREACH_ERR(CASE_ERR)
-#undef CASE_ERR
-    default:
-        return "undefined errcode";
-    }
-}
+#include "herr.h"
+
+#include <map>
+
+#include "hthread.h"    // for gettid
+
+// id => errcode
+static std::map<int, int>   s_mapErr;
+
+void set_id_errcode(int id, int errcode) {
+    s_mapErr[id] = errcode;
+}
+
+int  get_id_errcode(int id) {
+    auto iter = s_mapErr.find(id);
+    if (iter != s_mapErr.end()) {
+        // note: erase after get
+        s_mapErr.erase(iter);
+        return iter->second;
+    }
+    return ERR_OK;
+}
+
+void set_last_errcode(int errcode) {
+    set_id_errcode(gettid(), errcode);
+}
+
+int  get_last_errcode() {
+    return get_id_errcode(gettid());
+}
+
+const char* get_errmsg(int err) {
+    switch (err) {
+#define CASE_ERR(macro, errcode, errmsg) \
+    case errcode: \
+        return errmsg;
+    FOREACH_ERR(CASE_ERR)
+#undef CASE_ERR
+    default:
+        return "undefined errcode";
+    }
+}

+ 73 - 73
herr.h

@@ -1,73 +1,73 @@
-#ifndef HW_ERR_H_
-#define HW_ERR_H_
-
-// F(macro, errcode, errmsg)
-#define FOREACH_ERR_COMMON(F) \
-    F(ERR_OK,               0,      "ok")               \
-    F(ERR_UNKNOWN,          1000,   "unknown error")    \
-    F(ERR_NULL_PARAM,       1001,   "null param")       \
-    F(ERR_NULL_POINTER,     1002,   "null pointer")     \
-    F(ERR_NULL_DATA,        1003,   "null data")        \
-    \
-    F(ERR_INVALID_PARAM,    1010,   "invalid param")    \
-    F(ERR_INVALID_HANDLE,   1011,   "invalid handle")   \
-    F(ERR_INVALID_JSON,     1012,   "invalid json")     \
-    F(ERR_INVALID_XML,      1013,   "invalid xml")      \
-    F(ERR_INVALID_FMT,      1014,   "invalid format")   \
-    \
-    F(ERR_MISMATCH,         1020,   "mismatch")         \
-    F(ERR_REQUEST,          1021,   "error request")    \
-    F(ERR_RESPONSE,         1022,   "error response")   \
-    F(ERR_PARSE,            1023,   "parse failed")     \
-    \
-    F(ERR_MALLOC,           1030,   "malloc failed")    \
-    F(ERR_FREE,             1031,   "free failed")      \
-    \
-    F(ERR_TASK_TIMEOUT,     1100,   "task timeout")     \
-    F(ERR_TASK_DEQUE_FULL,  1101,   "task deque full")  \
-    F(ERR_TASK_NOT_CREATE,  1102,   "task not create")  \
-    \
-    F(ERR_OPEN_FILE,        1200,   "open file failed") \
-    F(ERR_SAVE_FILE,        1201,   "save file failed")
-
-#define FOREACH_ERR_NETWORK(F) \
-    F(ERR_ADAPTER_NOT_FOUND,    2001, "adapter not found")  \
-    F(ERR_SERVER_NOT_FOUND,     2002, "server not found")   \
-    F(ERR_SERVER_UNREACHEABLE,  2003, "server unreacheable")    \
-    F(ERR_SERVER_DISCONNECT,    2004, "server disconnect")      \
-    F(ERR_CONNECT_TIMEOUT,      2005, "connect timeout")        \
-    F(ERR_INVALID_PACKAGE,      2006, "invalid package")        \
-    F(ERR_SERVER_NOT_STARTUP,   2007, "server not startup")     \
-    F(ERR_CLIENT_DISCONNECT,    2008, "client disconnect")
-
-#define FOREACH_ERR_SERVICE(F)  \
-    F(ERR_RESOURCE_NOT_FOUND,   3000, "resource not found") \
-    F(ERR_GROUP_NOT_FOUND,      3001, "group not found")    \
-    F(ERR_PERSON_NOT_FOUND,     3002, "person not found")   \
-    F(ERR_FACE_NOT_FOUND,       3003, "face not found")     \
-    F(ERR_DEVICE_NOT_FOUND,     3004, "device not found")
-
-#define FOREACH_ERR(F) \
-    FOREACH_ERR_COMMON(F) \
-    FOREACH_ERR_NETWORK(F)  \
-    FOREACH_ERR_SERVICE(F)
-
-#define ENUM_ERR(macro, errcode, _) macro = errcode,
-enum E_ERR{
-    FOREACH_ERR(ENUM_ERR)
-    ERR_LAST
-};
-#undef ENUM_ERR
-
-// id => errcode
-void set_id_errcode(int id, int errcode);
-int  get_id_errcode(int id);
-
-// id = gettid()
-void set_last_errcode(int errcode);
-int  get_last_errcode();
-
-// errcode => errmsg
-const char* get_errmsg(int errcode);
-
-#endif  // HW_ERR_H_
+#ifndef HW_ERR_H_
+#define HW_ERR_H_
+
+// F(macro, errcode, errmsg)
+#define FOREACH_ERR_COMMON(F) \
+    F(ERR_OK,               0,      "ok")               \
+    F(ERR_UNKNOWN,          1000,   "unknown error")    \
+    F(ERR_NULL_PARAM,       1001,   "null param")       \
+    F(ERR_NULL_POINTER,     1002,   "null pointer")     \
+    F(ERR_NULL_DATA,        1003,   "null data")        \
+    \
+    F(ERR_INVALID_PARAM,    1010,   "invalid param")    \
+    F(ERR_INVALID_HANDLE,   1011,   "invalid handle")   \
+    F(ERR_INVALID_JSON,     1012,   "invalid json")     \
+    F(ERR_INVALID_XML,      1013,   "invalid xml")      \
+    F(ERR_INVALID_FMT,      1014,   "invalid format")   \
+    \
+    F(ERR_MISMATCH,         1020,   "mismatch")         \
+    F(ERR_REQUEST,          1021,   "error request")    \
+    F(ERR_RESPONSE,         1022,   "error response")   \
+    F(ERR_PARSE,            1023,   "parse failed")     \
+    \
+    F(ERR_MALLOC,           1030,   "malloc failed")    \
+    F(ERR_FREE,             1031,   "free failed")      \
+    \
+    F(ERR_TASK_TIMEOUT,     1100,   "task timeout")     \
+    F(ERR_TASK_DEQUE_FULL,  1101,   "task deque full")  \
+    F(ERR_TASK_NOT_CREATE,  1102,   "task not create")  \
+    \
+    F(ERR_OPEN_FILE,        1200,   "open file failed") \
+    F(ERR_SAVE_FILE,        1201,   "save file failed")
+
+#define FOREACH_ERR_NETWORK(F) \
+    F(ERR_ADAPTER_NOT_FOUND,    2001, "adapter not found")  \
+    F(ERR_SERVER_NOT_FOUND,     2002, "server not found")   \
+    F(ERR_SERVER_UNREACHEABLE,  2003, "server unreacheable")    \
+    F(ERR_SERVER_DISCONNECT,    2004, "server disconnect")      \
+    F(ERR_CONNECT_TIMEOUT,      2005, "connect timeout")        \
+    F(ERR_INVALID_PACKAGE,      2006, "invalid package")        \
+    F(ERR_SERVER_NOT_STARTUP,   2007, "server not startup")     \
+    F(ERR_CLIENT_DISCONNECT,    2008, "client disconnect")
+
+#define FOREACH_ERR_SERVICE(F)  \
+    F(ERR_RESOURCE_NOT_FOUND,   3000, "resource not found") \
+    F(ERR_GROUP_NOT_FOUND,      3001, "group not found")    \
+    F(ERR_PERSON_NOT_FOUND,     3002, "person not found")   \
+    F(ERR_FACE_NOT_FOUND,       3003, "face not found")     \
+    F(ERR_DEVICE_NOT_FOUND,     3004, "device not found")
+
+#define FOREACH_ERR(F) \
+    FOREACH_ERR_COMMON(F) \
+    FOREACH_ERR_NETWORK(F)  \
+    FOREACH_ERR_SERVICE(F)
+
+#define ENUM_ERR(macro, errcode, _) macro = errcode,
+enum E_ERR{
+    FOREACH_ERR(ENUM_ERR)
+    ERR_LAST
+};
+#undef ENUM_ERR
+
+// id => errcode
+void set_id_errcode(int id, int errcode);
+int  get_id_errcode(int id);
+
+// id = gettid()
+void set_last_errcode(int errcode);
+int  get_last_errcode();
+
+// errcode => errmsg
+const char* get_errmsg(int errcode);
+
+#endif  // HW_ERR_H_

+ 77 - 77
hfile.h

@@ -1,77 +1,77 @@
-#ifndef HW_FILE_H_
-#define HW_FILE_H_
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include "hdef.h"
-#include "hbuf.h"
-#include "herr.h"
-
-class HFile {
- public:
-    HFile() {
-        _fp = NULL;
-    }
-
-    ~HFile() {
-        close();
-    }
-
-    int open(const char* filepath, const char* mode) {
-        close();
-        strncpy(_filepath, filepath, MAX_PATH);
-        _fp = fopen(filepath, mode);
-        if (_fp == NULL) {
-            return ERR_OPEN_FILE;
-        }
-        return 0;
-    }
-
-    void close() {
-        if (_fp) {
-            fclose(_fp);
-            _fp = NULL;
-        }
-    }
-
-    size_t size() {
-        struct stat st;
-        stat(_filepath, &st);
-        return st.st_size;
-    }
-
-    size_t read(void* ptr, size_t len) {
-        return fread(ptr, 1, len, _fp);
-    }
-
-    size_t readall(hbuf_t& buf) {
-        size_t filesize = size();
-        buf.init(filesize);
-        return fread(buf.base, 1, buf.len, _fp);
-    }
-
-    bool readline(string& str) {
-        str.clear();
-        char ch;
-        while (fread(&ch, 1, 1, _fp)) {
-            if (ch == '\n') {
-                return true;
-            }
-            str += ch;
-        }
-        return str.length() != 0;
-    }
-
-    size_t write(const void* ptr, size_t len) {
-        return fwrite(ptr, 1, len, _fp);
-    }
-
-    char  _filepath[MAX_PATH];
-    FILE* _fp;
-};
-
-#endif  // HW_FILE_H_
+#ifndef HW_FILE_H_
+#define HW_FILE_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include "hdef.h"
+#include "hbuf.h"
+#include "herr.h"
+
+class HFile {
+ public:
+    HFile() {
+        _fp = NULL;
+    }
+
+    ~HFile() {
+        close();
+    }
+
+    int open(const char* filepath, const char* mode) {
+        close();
+        strncpy(_filepath, filepath, MAX_PATH);
+        _fp = fopen(filepath, mode);
+        if (_fp == NULL) {
+            return ERR_OPEN_FILE;
+        }
+        return 0;
+    }
+
+    void close() {
+        if (_fp) {
+            fclose(_fp);
+            _fp = NULL;
+        }
+    }
+
+    size_t size() {
+        struct stat st;
+        stat(_filepath, &st);
+        return st.st_size;
+    }
+
+    size_t read(void* ptr, size_t len) {
+        return fread(ptr, 1, len, _fp);
+    }
+
+    size_t readall(hbuf_t& buf) {
+        size_t filesize = size();
+        buf.init(filesize);
+        return fread(buf.base, 1, buf.len, _fp);
+    }
+
+    bool readline(string& str) {
+        str.clear();
+        char ch;
+        while (fread(&ch, 1, 1, _fp)) {
+            if (ch == '\n') {
+                return true;
+            }
+            str += ch;
+        }
+        return str.length() != 0;
+    }
+
+    size_t write(const void* ptr, size_t len) {
+        return fwrite(ptr, 1, len, _fp);
+    }
+
+    char  _filepath[MAX_PATH];
+    FILE* _fp;
+};
+
+#endif  // HW_FILE_H_

+ 87 - 87
hframe.h

@@ -1,87 +1,87 @@
-#ifndef HW_FRAME_H_
-#define HW_FRAME_H_
-
-#include <deque>
-
-#include "hbuf.h"
-#include "hmutex.h"
-
-typedef struct hframe_s {
-    hbuf_t buf;
-    int w;
-    int h;
-    int type;
-    int bpp;
-    uint64 ts;
-    void* userdata;
-    hframe_s() {
-        w = h = type = bpp = ts = 0;
-        userdata = NULL;
-    }
-
-    bool isNull() {
-        return w == 0 || h == 0 || buf.isNull();
-    }
-
-    // deep copy
-    void copy(const hframe_s& rhs) {
-        this->w = rhs.w;
-        this->h = rhs.h;
-        this->type = rhs.type;
-        this->bpp  = rhs.bpp;
-        this->ts   = rhs.ts;
-        this->userdata = rhs.userdata;
-        if (this->buf.isNull() || this->buf.len != rhs.buf.len) {
-            this->buf.init(rhs.buf.len);
-        }
-        memcpy(this->buf.base, rhs.buf.base, rhs.buf.len);
-    }
-}HFrame;
-
-typedef struct frame_info_s {
-    int w;
-    int h;
-    int type;
-    int bpp;
-} FrameInfo;
-
-typedef struct frame_stats_s {
-    int push_cnt;
-    int pop_cnt;
-
-    int push_ok_cnt;
-    int pop_ok_cnt;
-
-    frame_stats_s() {
-        push_cnt = pop_cnt = push_ok_cnt = pop_ok_cnt = 0;
-    }
-} FrameStats;
-
-#define DEFAULT_FRAME_CACHENUM  10
-
-class HFrameBuf : public HRingBuf {
- public:
-    enum CacheFullPolicy {
-        SQUEEZE,
-        DISCARD,
-    } policy;
-
-    HFrameBuf() : HRingBuf() {
-        cache_num = DEFAULT_FRAME_CACHENUM;
-        policy = SQUEEZE;
-    }
-
-    void setCache(int num) {cache_num = num;}
-    void setPolicy(CacheFullPolicy policy) {this->policy = policy;}
-
-    int push(HFrame* pFrame);
-    int pop(HFrame* pFrame);
-
-    int         cache_num;
-    FrameStats  frame_stats;
-    FrameInfo   frame_info;
-    std::deque<HFrame> frames;
-    std::mutex         mutex;
-};
-
-#endif  // HW_FRAME_H_
+#ifndef HW_FRAME_H_
+#define HW_FRAME_H_
+
+#include <deque>
+
+#include "hbuf.h"
+#include "hmutex.h"
+
+typedef struct hframe_s {
+    hbuf_t buf;
+    int w;
+    int h;
+    int type;
+    int bpp;
+    uint64 ts;
+    void* userdata;
+    hframe_s() {
+        w = h = type = bpp = ts = 0;
+        userdata = NULL;
+    }
+
+    bool isNull() {
+        return w == 0 || h == 0 || buf.isNull();
+    }
+
+    // deep copy
+    void copy(const hframe_s& rhs) {
+        this->w = rhs.w;
+        this->h = rhs.h;
+        this->type = rhs.type;
+        this->bpp  = rhs.bpp;
+        this->ts   = rhs.ts;
+        this->userdata = rhs.userdata;
+        if (this->buf.isNull() || this->buf.len != rhs.buf.len) {
+            this->buf.init(rhs.buf.len);
+        }
+        memcpy(this->buf.base, rhs.buf.base, rhs.buf.len);
+    }
+}HFrame;
+
+typedef struct frame_info_s {
+    int w;
+    int h;
+    int type;
+    int bpp;
+} FrameInfo;
+
+typedef struct frame_stats_s {
+    int push_cnt;
+    int pop_cnt;
+
+    int push_ok_cnt;
+    int pop_ok_cnt;
+
+    frame_stats_s() {
+        push_cnt = pop_cnt = push_ok_cnt = pop_ok_cnt = 0;
+    }
+} FrameStats;
+
+#define DEFAULT_FRAME_CACHENUM  10
+
+class HFrameBuf : public HRingBuf {
+ public:
+    enum CacheFullPolicy {
+        SQUEEZE,
+        DISCARD,
+    } policy;
+
+    HFrameBuf() : HRingBuf() {
+        cache_num = DEFAULT_FRAME_CACHENUM;
+        policy = SQUEEZE;
+    }
+
+    void setCache(int num) {cache_num = num;}
+    void setPolicy(CacheFullPolicy policy) {this->policy = policy;}
+
+    int push(HFrame* pFrame);
+    int pop(HFrame* pFrame);
+
+    int         cache_num;
+    FrameStats  frame_stats;
+    FrameInfo   frame_info;
+    std::deque<HFrame> frames;
+    std::mutex         mutex;
+};
+
+#endif  // HW_FRAME_H_

+ 27 - 27
hgl.h

@@ -1,27 +1,27 @@
-#ifndef HW_GL_H_
-#define HW_GL_H_
-
-#include <GL/glew.h>
-
-#include "hframe.h"
-
-// GL PixelFormat extend
-#define GL_I420             0x1910  // YYYYYYYYUUVV
-#define GL_YV12             0x1911  // YYYYYYYYVVUU
-#define GL_NV12             0x1912  // YYYYYYYYUVUV
-#define GL_NV21             0x1913  // YYYYYYYYVUVU
-
-/*
-#define GL_RGB      0x1907      // RGBRGB
-#define GL_RGBA     0x1908      // RGBARGBA
-
-#define GL_BGR      0x80E0      // BGRBGR       .bmp
-#define GL_BGRA     0x80E1      // BGRABGRA
-*/
-
-typedef struct GLTexture_s {
-    GLuint id;  // for glGenTextures
-    HFrame frame;
-} GLTexture;
-
-#endif  // HW_GL_H_
+#ifndef HW_GL_H_
+#define HW_GL_H_
+
+#include <GL/glew.h>
+
+#include "hframe.h"
+
+// GL PixelFormat extend
+#define GL_I420             0x1910  // YYYYYYYYUUVV
+#define GL_YV12             0x1911  // YYYYYYYYVVUU
+#define GL_NV12             0x1912  // YYYYYYYYUVUV
+#define GL_NV21             0x1913  // YYYYYYYYVUVU
+
+/*
+#define GL_RGB      0x1907      // RGBRGB
+#define GL_RGBA     0x1908      // RGBARGBA
+
+#define GL_BGR      0x80E0      // BGRBGR       .bmp
+#define GL_BGRA     0x80E1      // BGRABGRA
+*/
+
+typedef struct GLTexture_s {
+    GLuint id;  // for glGenTextures
+    HFrame frame;
+} GLTexture;
+
+#endif  // HW_GL_H_

+ 71 - 71
hgui.h

@@ -1,71 +1,71 @@
-#ifndef HW_GUI_H_
-#define HW_GUI_H_
-
-#include "hdef.h"
-
-typedef uint32 HColor;  // 0xAARRGGBB
-
-#define CLR_B(c)    (c         & 0xff)
-#define CLR_G(c)    ((c >> 8)  & 0xff)
-#define CLR_R(c)    ((c >> 16) & 0xff)
-#define CLR_A(c)    ((c >> 24) & 0xff)
-#define ARGB(a, r, g, b) MAKE_FOURCC(a, r, g, b)
-
-typedef struct hpoint_s {
-    int x;
-    int y;
-
-#ifdef __cplusplus
-    hpoint_s() {
-        x = y = 0;
-    }
-
-    hpoint_s(int x, int y) {
-        this->x = x;
-        this->y = y;
-    }
-#endif
-} HPoint;
-
-typedef struct hsize_s {
-    int w;
-    int h;
-
-#ifdef __cplusplus
-    hsize_s() {
-        w = h = 0;
-    }
-
-    hsize_s(int w, int h) {
-        this->w = w;
-        this->h = h;
-    }
-#endif
-}HSize;
-
-typedef struct hrect_s {
-    int x;
-    int y;
-    int w;
-    int h;
-
-#ifdef __cplusplus
-    hrect_s() {
-        x = y = w = h = 0;
-    }
-
-    hrect_s(int x, int y, int w, int h) {
-        this->x = x;
-        this->y = y;
-        this->w = w;
-        this->h = h;
-    }
-
-    int left()     {return x;}
-    int right()    {return x+w;}
-    int top()      {return y;}
-    int bottom()   {return y+h;}
-#endif
-} HRect;
-
-#endif  // HW_GUI_H_
+#ifndef HW_GUI_H_
+#define HW_GUI_H_
+
+#include "hdef.h"
+
+typedef uint32 HColor;  // 0xAARRGGBB
+
+#define CLR_B(c)    (c         & 0xff)
+#define CLR_G(c)    ((c >> 8)  & 0xff)
+#define CLR_R(c)    ((c >> 16) & 0xff)
+#define CLR_A(c)    ((c >> 24) & 0xff)
+#define ARGB(a, r, g, b) MAKE_FOURCC(a, r, g, b)
+
+typedef struct hpoint_s {
+    int x;
+    int y;
+
+#ifdef __cplusplus
+    hpoint_s() {
+        x = y = 0;
+    }
+
+    hpoint_s(int x, int y) {
+        this->x = x;
+        this->y = y;
+    }
+#endif
+} HPoint;
+
+typedef struct hsize_s {
+    int w;
+    int h;
+
+#ifdef __cplusplus
+    hsize_s() {
+        w = h = 0;
+    }
+
+    hsize_s(int w, int h) {
+        this->w = w;
+        this->h = h;
+    }
+#endif
+}HSize;
+
+typedef struct hrect_s {
+    int x;
+    int y;
+    int w;
+    int h;
+
+#ifdef __cplusplus
+    hrect_s() {
+        x = y = w = h = 0;
+    }
+
+    hrect_s(int x, int y, int w, int h) {
+        this->x = x;
+        this->y = y;
+        this->w = w;
+        this->h = h;
+    }
+
+    int left()     {return x;}
+    int right()    {return x+w;}
+    int top()      {return y;}
+    int bottom()   {return y+h;}
+#endif
+} HRect;
+
+#endif  // HW_GUI_H_

+ 92 - 92
hlog.cpp

@@ -1,92 +1,92 @@
-#include "hlog.h"
-
-#include <stdio.h>
-#include <string.h>
-#include <stdarg.h>
-#include <mutex>
-
-#include "htime.h"  // for get_datetime
-
-#define LOGBUF_SIZE         (1<<13)  // 8k
-#define LOGFILE_MAXSIZE     (1<<23)  // 8M
-
-static FILE* s_logfp = NULL;
-static char s_logfile[256] = DEFAULT_LOG_FILE;
-static int s_loglevel = DEFAULT_LOG_LEVEL;
-static bool s_logcolor = false;
-static char s_logbuf[LOGBUF_SIZE];
-static std::mutex s_mutex;
-
-int hlog_set_file(const char* logfile) {
-    if (logfile && strlen(logfile) > 0) {
-        strncpy(s_logfile, logfile, 256);
-    }
-
-    if (s_logfp) {
-        fclose(s_logfp);
-        s_logfp = NULL;
-    }
-
-    s_logfp = fopen(s_logfile, "a");
-
-    return s_logfp ? 0 : -1;
-}
-
-void hlog_set_level(int level) {
-    s_loglevel = level;
-}
-
-void hlog_enable_color(bool enable) {
-    s_logcolor = enable;
-}
-
-int hlog_printf(int level, const char* fmt, ...) {
-    if (level < s_loglevel)
-        return -10;
-
-    const char* pcolor = "";
-    const char* plevel = "";
-#define CASE_LOG(id, str, clr) \
-    case id: plevel = str; pcolor = clr; break;
-
-    switch (level) {
-        FOREACH_LOG(CASE_LOG)
-    }
-#undef CASE_LOG
-
-    if (!s_logcolor)
-        pcolor = "";
-
-    std::lock_guard<std::mutex> locker(s_mutex);
-
-    if (!s_logfp) {
-        if (hlog_set_file(s_logfile) != 0)
-            return -20;
-    }
-
-    if (ftell(s_logfp) > LOGFILE_MAXSIZE) {
-        fclose(s_logfp);
-        s_logfp = fopen(s_logfile, "w");
-        if (!s_logfp)
-            return -30;
-    }
-
-    datetime_t now = get_datetime();
-
-    int len = snprintf(s_logbuf, LOGBUF_SIZE, "%s[%04d-%02d-%02d %02d:%02d:%02d.%03d][%s]: ",
-        pcolor, now.year, now.month, now.day, now.hour, now.min, now.sec, now.ms, plevel);
-
-    va_list ap;
-    va_start(ap, fmt);
-    len += vsnprintf(s_logbuf + len, LOGBUF_SIZE-len, fmt, ap);
-    va_end(ap);
-
-    fprintf(s_logfp, "%s\n", s_logbuf);
-    if (s_logcolor) {
-        fprintf(s_logfp, CL_CLR);
-    }
-
-    fflush(NULL);
-
-    return len;
-}
+#include "hlog.h"
+
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+#include <mutex>
+
+#include "htime.h"  // for get_datetime
+
+#define LOGBUF_SIZE         (1<<13)  // 8k
+#define LOGFILE_MAXSIZE     (1<<23)  // 8M
+
+static FILE* s_logfp = NULL;
+static char s_logfile[256] = DEFAULT_LOG_FILE;
+static int s_loglevel = DEFAULT_LOG_LEVEL;
+static bool s_logcolor = false;
+static char s_logbuf[LOGBUF_SIZE];
+static std::mutex s_mutex;
+
+int hlog_set_file(const char* logfile) {
+    if (logfile && strlen(logfile) > 0) {
+        strncpy(s_logfile, logfile, 256);
+    }
+
+    if (s_logfp) {
+        fclose(s_logfp);
+        s_logfp = NULL;
+    }
+
+    s_logfp = fopen(s_logfile, "a");
+
+    return s_logfp ? 0 : -1;
+}
+
+void hlog_set_level(int level) {
+    s_loglevel = level;
+}
+
+void hlog_enable_color(bool enable) {
+    s_logcolor = enable;
+}
+
+int hlog_printf(int level, const char* fmt, ...) {
+    if (level < s_loglevel)
+        return -10;
+
+    const char* pcolor = "";
+    const char* plevel = "";
+#define CASE_LOG(id, str, clr) \
+    case id: plevel = str; pcolor = clr; break;
+
+    switch (level) {
+        FOREACH_LOG(CASE_LOG)
+    }
+#undef CASE_LOG
+
+    if (!s_logcolor)
+        pcolor = "";
+
+    std::lock_guard<std::mutex> locker(s_mutex);
+
+    if (!s_logfp) {
+        if (hlog_set_file(s_logfile) != 0)
+            return -20;
+    }
+
+    if (ftell(s_logfp) > LOGFILE_MAXSIZE) {
+        fclose(s_logfp);
+        s_logfp = fopen(s_logfile, "w");
+        if (!s_logfp)
+            return -30;
+    }
+
+    datetime_t now = get_datetime();
+
+    int len = snprintf(s_logbuf, LOGBUF_SIZE, "%s[%04d-%02d-%02d %02d:%02d:%02d.%03d][%s]: ",
+        pcolor, now.year, now.month, now.day, now.hour, now.min, now.sec, now.ms, plevel);
+
+    va_list ap;
+    va_start(ap, fmt);
+    len += vsnprintf(s_logbuf + len, LOGBUF_SIZE-len, fmt, ap);
+    va_end(ap);
+
+    fprintf(s_logfp, "%s\n", s_logbuf);
+    if (s_logcolor) {
+        fprintf(s_logfp, CL_CLR);
+    }
+
+    fflush(NULL);
+
+    return len;
+}

+ 52 - 52
hlog.h

@@ -1,52 +1,52 @@
-#ifndef HW_LOG_H_
-#define HW_LOG_H_
-
-#define CL_CLR      "\033[0m"       /* 恢复颜色 */
-#define CL_BLACK    "\033[30m"      /* 黑色字 */
-#define CL_RED      "\e[1;31m"      /* 红色字 */
-#define CL_GREEN    "\e[1;32m"      /* 绿色字 */
-#define CL_YELLOW   "\e[1;33m"      /* 黄色字 */
-#define CL_BLUE     "\033[34m"      /* 蓝色字 */
-#define CL_PURPLE   "\e[1;35m"      /* 紫色字 */
-#define CL_SKYBLUE  "\e[1;36m"      /* 天蓝字 */
-#define CL_WHITE    "\033[37m"      /* 白色字 */
-
-#define CL_BLK_WHT  "\033[40;37m"   /* 黑底白字 */
-#define CL_RED_WHT  "\033[41;37m"   /* 红底白字 */
-#define CL_GRE_WHT  "\033[42;37m"   /* 绿底白字 */
-#define CL_YEW_WHT  "\033[43;37m"   /* 黄底白字 */
-#define CL_BLUE_WHT "\033[44;37m"   /* 蓝底白字 */
-#define CL_PPL_WHT  "\033[45;37m"   /* 紫底白字 */
-#define CL_SKYB_WHT "\033[46;37m"   /* 天蓝底白字 */
-#define CL_WHT_BLK  "\033[47;30m"   /* 白底黑字 */
-
-// F(id, str, clr)
-#define FOREACH_LOG(F) \
-    F(LOG_LEVEL_DEBUG, "DEBUG", CL_WHITE) \
-    F(LOG_LEVEL_INFO,  "INFO ", CL_GREEN) \
-    F(LOG_LEVEL_WARN,  "WARN ", CL_YELLOW) \
-    F(LOG_LEVEL_ERROR, "ERROR", CL_RED) \
-    F(LOG_LEVEL_FATAL, "FATAL", CL_RED_WHT)
-
-enum LOG_LEVEL{
-    LOG_LEVEL_NONE = 0,
-#define ENUM_LOG(id, str, clr) id,
-    FOREACH_LOG(ENUM_LOG)
-#undef  ENUM_LOG
-};
-
-#define DEFAULT_LOG_FILE    "./default.log"
-#define DEFAULT_LOG_LEVEL   LOG_LEVEL_NONE
-
-int     hlog_set_file(const char* file);
-void    hlog_set_level(int level);
-void    hlog_enable_color(bool enable);
-int     hlog_printf(int level, const char* fmt, ...);
-
-#define hlogd(fmt, ...) hlog_printf(LOG_LEVEL_DEBUG, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
-#define hlogi(fmt, ...) hlog_printf(LOG_LEVEL_INFO,  fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
-#define hlogw(fmt, ...) hlog_printf(LOG_LEVEL_WARN,  fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
-#define hloge(fmt, ...) hlog_printf(LOG_LEVEL_ERROR, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
-#define hlogf(fmt, ...) hlog_printf(LOG_LEVEL_FATAL, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
-
-#endif  // HW_LOG_H_
+#ifndef HW_LOG_H_
+#define HW_LOG_H_
+
+#define CL_CLR      "\033[0m"       /* 恢复颜色 */
+#define CL_BLACK    "\033[30m"      /* 黑色字 */
+#define CL_RED      "\e[1;31m"      /* 红色字 */
+#define CL_GREEN    "\e[1;32m"      /* 绿色字 */
+#define CL_YELLOW   "\e[1;33m"      /* 黄色字 */
+#define CL_BLUE     "\033[34m"      /* 蓝色字 */
+#define CL_PURPLE   "\e[1;35m"      /* 紫色字 */
+#define CL_SKYBLUE  "\e[1;36m"      /* 天蓝字 */
+#define CL_WHITE    "\033[37m"      /* 白色字 */
+
+#define CL_BLK_WHT  "\033[40;37m"   /* 黑底白字 */
+#define CL_RED_WHT  "\033[41;37m"   /* 红底白字 */
+#define CL_GRE_WHT  "\033[42;37m"   /* 绿底白字 */
+#define CL_YEW_WHT  "\033[43;37m"   /* 黄底白字 */
+#define CL_BLUE_WHT "\033[44;37m"   /* 蓝底白字 */
+#define CL_PPL_WHT  "\033[45;37m"   /* 紫底白字 */
+#define CL_SKYB_WHT "\033[46;37m"   /* 天蓝底白字 */
+#define CL_WHT_BLK  "\033[47;30m"   /* 白底黑字 */
+
+// F(id, str, clr)
+#define FOREACH_LOG(F) \
+    F(LOG_LEVEL_DEBUG, "DEBUG", CL_WHITE) \
+    F(LOG_LEVEL_INFO,  "INFO ", CL_GREEN) \
+    F(LOG_LEVEL_WARN,  "WARN ", CL_YELLOW) \
+    F(LOG_LEVEL_ERROR, "ERROR", CL_RED) \
+    F(LOG_LEVEL_FATAL, "FATAL", CL_RED_WHT)
+
+enum LOG_LEVEL{
+    LOG_LEVEL_NONE = 0,
+#define ENUM_LOG(id, str, clr) id,
+    FOREACH_LOG(ENUM_LOG)
+#undef  ENUM_LOG
+};
+
+#define DEFAULT_LOG_FILE    "./default.log"
+#define DEFAULT_LOG_LEVEL   LOG_LEVEL_NONE
+
+int     hlog_set_file(const char* file);
+void    hlog_set_level(int level);
+void    hlog_enable_color(bool enable);
+int     hlog_printf(int level, const char* fmt, ...);
+
+#define hlogd(fmt, ...) hlog_printf(LOG_LEVEL_DEBUG, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
+#define hlogi(fmt, ...) hlog_printf(LOG_LEVEL_INFO,  fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
+#define hlogw(fmt, ...) hlog_printf(LOG_LEVEL_WARN,  fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
+#define hloge(fmt, ...) hlog_printf(LOG_LEVEL_ERROR, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
+#define hlogf(fmt, ...) hlog_printf(LOG_LEVEL_FATAL, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__)
+
+#endif  // HW_LOG_H_

+ 129 - 129
hthreadpool.h

@@ -1,129 +1,129 @@
-#ifndef HW_THREAD_POOL_H_
-#define HW_THREAD_POOL_H_
-
-#include <vector>
-#include <thread>
-#include <queue>
-#include <functional>
-#include <atomic>
-#include <mutex>
-#include <condition_variable>
-#include <future>
-#include <memory>
-#include <utility>
-
-#include "hlog.h"
-#include "hthread.h"
-
-class HThreadPool {
- public:
-    using Task = std::function<void()>;
-
-    HThreadPool(int size = std::thread::hardware_concurrency())
-        : pool_size(size), idle_num(size), status(STOP) {
-    }
-
-    ~HThreadPool() {
-        stop();
-    }
-
-    int start() {
-        if (status == STOP) {
-            status = RUNNING;
-            for (int i = 0; i < pool_size; ++i) {
-                workers.emplace_back(std::thread([this]{
-                    hlogd("work thread[%X] running...", gettid());
-                    while (status != STOP) {
-                        while (status == PAUSE) {
-                            std::this_thread::yield();
-                        }
-
-                        Task task;
-                        {
-                            std::unique_lock<std::mutex> locker(mutex);
-                            cond.wait(locker, [this]{
-                                return status == STOP || !tasks.empty();
-                            });
-
-                            if (status == STOP) return;
-
-                            if (!tasks.empty()) {
-                                task = std::move(tasks.front());
-                                tasks.pop();
-                            }
-                        }
-
-                        --idle_num;
-                        task();
-                        ++idle_num;
-                    }
-                }));
-            }
-        }
-        return 0;
-    }
-
-    int stop() {
-        if (status != STOP) {
-            status = STOP;
-            cond.notify_all();
-            for (auto& thread : workers) {
-                thread.join();
-            }
-        }
-        return 0;
-    }
-
-    int pause() {
-        if (status == RUNNING) {
-            status = PAUSE;
-        }
-        return 0;
-    }
-
-    int resume() {
-        if (status == PAUSE) {
-            status = RUNNING;
-        }
-        return 0;
-    }
-
-    // return a future, calling future.get() will wait task done and return RetType.
-    // commit(fn, args...)
-    // commit(std::bind(&Class::mem_fn, &obj))
-    // commit(std::mem_fn(&Class::mem_fn, &obj))
-    template<class Fn, class... Args>
-    auto commit(Fn&& fn, Args&&... args) -> std::future<decltype(fn(args...))> {
-        using RetType = decltype(fn(args...));
-        auto task = std::make_shared<std::packaged_task<RetType()> >(
-            std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...));
-        std::future<RetType> future = task->get_future();
-        {
-            std::lock_guard<std::mutex> locker(mutex);
-            tasks.emplace([task]{
-                (*task)();
-            });
-        }
-
-        cond.notify_one();
-        return future;
-    }
-
- public:
-    int pool_size;
-    std::atomic<int> idle_num;
-
-    enum Status {
-        STOP,
-        RUNNING,
-        PAUSE,
-    };
-    std::atomic<Status> status;
-    std::vector<std::thread> workers;
-
-    std::queue<Task> tasks;
-    std::mutex        mutex;
-    std::condition_variable cond;
-};
-
-#endif  // HW_THREAD_POOL_H_
+#ifndef HW_THREAD_POOL_H_
+#define HW_THREAD_POOL_H_
+
+#include <vector>
+#include <thread>
+#include <queue>
+#include <functional>
+#include <atomic>
+#include <mutex>
+#include <condition_variable>
+#include <future>
+#include <memory>
+#include <utility>
+
+#include "hlog.h"
+#include "hthread.h"
+
+class HThreadPool {
+ public:
+    using Task = std::function<void()>;
+
+    HThreadPool(int size = std::thread::hardware_concurrency())
+        : pool_size(size), idle_num(size), status(STOP) {
+    }
+
+    ~HThreadPool() {
+        stop();
+    }
+
+    int start() {
+        if (status == STOP) {
+            status = RUNNING;
+            for (int i = 0; i < pool_size; ++i) {
+                workers.emplace_back(std::thread([this]{
+                    hlogd("work thread[%X] running...", gettid());
+                    while (status != STOP) {
+                        while (status == PAUSE) {
+                            std::this_thread::yield();
+                        }
+
+                        Task task;
+                        {
+                            std::unique_lock<std::mutex> locker(mutex);
+                            cond.wait(locker, [this]{
+                                return status == STOP || !tasks.empty();
+                            });
+
+                            if (status == STOP) return;
+
+                            if (!tasks.empty()) {
+                                task = std::move(tasks.front());
+                                tasks.pop();
+                            }
+                        }
+
+                        --idle_num;
+                        task();
+                        ++idle_num;
+                    }
+                }));
+            }
+        }
+        return 0;
+    }
+
+    int stop() {
+        if (status != STOP) {
+            status = STOP;
+            cond.notify_all();
+            for (auto& thread : workers) {
+                thread.join();
+            }
+        }
+        return 0;
+    }
+
+    int pause() {
+        if (status == RUNNING) {
+            status = PAUSE;
+        }
+        return 0;
+    }
+
+    int resume() {
+        if (status == PAUSE) {
+            status = RUNNING;
+        }
+        return 0;
+    }
+
+    // return a future, calling future.get() will wait task done and return RetType.
+    // commit(fn, args...)
+    // commit(std::bind(&Class::mem_fn, &obj))
+    // commit(std::mem_fn(&Class::mem_fn, &obj))
+    template<class Fn, class... Args>
+    auto commit(Fn&& fn, Args&&... args) -> std::future<decltype(fn(args...))> {
+        using RetType = decltype(fn(args...));
+        auto task = std::make_shared<std::packaged_task<RetType()> >(
+            std::bind(std::forward<Fn>(fn), std::forward<Args>(args)...));
+        std::future<RetType> future = task->get_future();
+        {
+            std::lock_guard<std::mutex> locker(mutex);
+            tasks.emplace([task]{
+                (*task)();
+            });
+        }
+
+        cond.notify_one();
+        return future;
+    }
+
+ public:
+    int pool_size;
+    std::atomic<int> idle_num;
+
+    enum Status {
+        STOP,
+        RUNNING,
+        PAUSE,
+    };
+    std::atomic<Status> status;
+    std::vector<std::thread> workers;
+
+    std::queue<Task> tasks;
+    std::mutex        mutex;
+    std::condition_variable cond;
+};
+
+#endif  // HW_THREAD_POOL_H_

+ 234 - 234
iniparser.cpp

@@ -1,234 +1,234 @@
-#include "iniparser.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <sstream>
-
-#include "herr.h"
-#include "hfile.h"
-
-IniParser::IniParser() {
-    _comment = DEFAULT_INI_COMMENT;
-    _delim = DEFAULT_INI_DELIM;
-    root_ = NULL;
-}
-
-IniParser::~IniParser() {
-    Unload();
-}
-
-int IniParser::Unload() {
-    SAFE_DELETE(root_);
-    return 0;
-}
-
-int IniParser::LoadFromFile(const char* filepath) {
-    _filepath = filepath;
-
-    HFile file;
-    if (file.open(filepath, "r") != 0) {
-        return ERR_OPEN_FILE;
-    }
-
-    hbuf_t buf;
-    file.readall(buf);
-
-    return LoadFromMem((const char*)buf.base);
-}
-
-int IniParser::LoadFromMem(const char* data) {
-    Unload();
-
-    root_ = new IniNode;
-    root_->type = IniNode::INI_NODE_TYPE_ROOT;
-
-    std::stringstream ss;
-    ss << data;
-    std::string strLine;
-    int line = 0;
-    string::size_type pos;
-
-    string      content;
-    string      comment;
-    string      strDiv;
-    IniNode* pScopeNode = root_;
-    IniNode* pNewNode = NULL;
-    while (std::getline(ss, strLine)) {
-        ++line;
-
-        content = trimL(strLine);
-        if (content.length() == 0)  {
-            // blank line
-            strDiv += '\n';
-            continue;
-        }
-
-        // trim_comment
-        comment = "";
-        pos = content.find_first_of(_comment);
-        if (pos != string::npos) {
-            comment = content.substr(pos);
-            content = content.substr(0, pos);
-        }
-
-        content = trimR(content);
-        if (content.length() == 0) {
-            strDiv += strLine;
-            strDiv += '\n';
-            continue;
-        } else if (strDiv.length() != 0) {
-            IniNode* pNode = new IniNode;
-            pNode->type = IniNode::INI_NODE_TYPE_DIV;
-            pNode->label = strDiv;
-            pScopeNode->Add(pNode);
-            strDiv = "";
-        }
-
-        if (content[0] == '[') {
-            if (content[content.length()-1] == ']') {
-                // section
-                content = trim(content.substr(1, content.length()-2));
-                pNewNode = new IniNode;
-                pNewNode->type = IniNode::INI_NODE_TYPE_SECTION;
-                pNewNode->label = content;
-                root_->Add(pNewNode);
-                pScopeNode = pNewNode;
-            } else {
-                // hlogw("format error, line:%d", line);
-                continue;   // ignore
-            }
-        } else {
-            pos = content.find_first_of(_delim);
-            if (pos != string::npos) {
-                // key-value
-                pNewNode = new IniNode;
-                pNewNode->type = IniNode::INI_NODE_TYPE_KEY_VALUE;
-                pNewNode->label = trim(content.substr(0, pos));
-                pNewNode->value = trim(content.substr(pos+_delim.length()));
-                pScopeNode->Add(pNewNode);
-            } else {
-                // hlogw("format error, line:%d", line);
-                continue;   // ignore
-            }
-        }
-
-        if (comment.length() != 0) {
-            // tail_comment
-            IniNode* pNode = new IniNode;
-            pNode->type = IniNode::INI_NODE_TYPE_SPAN;
-            pNode->label = comment;
-            pNewNode->Add(pNode);
-            comment = "";
-        }
-    }
-
-    // file end comment
-    if (strDiv.length() != 0) {
-        IniNode* pNode = new IniNode;
-        pNode->type = IniNode::INI_NODE_TYPE_DIV;
-        pNode->label = strDiv;
-        root_->Add(pNode);
-    }
-
-    return 0;
-}
-
-void IniParser::DumpString(IniNode* pNode, string& str) {
-    if (pNode == NULL)  return;
-
-    if (pNode->type != IniNode::INI_NODE_TYPE_SPAN) {
-        if (str.length() > 0 && str[str.length()-1] != '\n') {
-            str += '\n';
-        }
-    }
-
-    switch (pNode->type) {
-    case IniNode::INI_NODE_TYPE_SECTION: {
-        str += '[';
-        str += pNode->label;
-        str += ']';
-    }
-    break;
-    case IniNode::INI_NODE_TYPE_KEY_VALUE: {
-        str += asprintf("%s %s %s", pNode->label.c_str(), _delim.c_str(), pNode->value.c_str());
-    }
-    break;
-    case IniNode::INI_NODE_TYPE_DIV: {
-        str += pNode->label;
-    }
-    break;
-    case IniNode::INI_NODE_TYPE_SPAN: {
-        str += '\t';
-        str += pNode->label;
-    }
-    break;
-    default:
-    break;
-    }
-
-    for (auto p : pNode->children) {
-        DumpString(p, str);
-    }
-}
-
-string IniParser::DumpString() {
-    string str;
-    DumpString(root_, str);
-    return str;
-}
-
-int IniParser::Save() {
-    return SaveAs(_filepath.c_str());
-}
-
-int IniParser::SaveAs(const char* filepath) {
-    string str = DumpString();
-    if (str.length() == 0) {
-        return 0;
-    }
-
-    HFile file;
-    if (file.open(filepath, "w") != 0) {
-        return ERR_SAVE_FILE;
-    }
-    file.write(str.c_str(), str.length());
-
-    return 0;
-}
-
-string IniParser::GetValue(const string& key, const string& section) {
-    IniNode* pSection = root_;
-    if (section.length() != 0) {
-        pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION);
-        if (pSection == NULL)   return "";
-    }
-
-    IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE);
-    if (pKV == NULL)    return "";
-
-    return pKV->value;
-}
-
-void IniParser::SetValue(const string& key, const string& value, const string& section) {
-    IniNode* pSection = root_;
-    if (section.length() != 0) {
-        pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION);
-        if (pSection == NULL) {
-            pSection = new IniNode;
-            pSection->type = IniNode::INI_NODE_TYPE_SECTION;
-            pSection->label = section;
-            root_->Add(pSection);
-        }
-    }
-
-    IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE);
-    if (pKV == NULL) {
-        pKV = new IniNode;
-        pKV->type = IniNode::INI_NODE_TYPE_KEY_VALUE;
-        pKV->label = key;
-        pSection->Add(pKV);
-    }
-    pKV->value = value;
-}
+#include "iniparser.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sstream>
+
+#include "herr.h"
+#include "hfile.h"
+
+IniParser::IniParser() {
+    _comment = DEFAULT_INI_COMMENT;
+    _delim = DEFAULT_INI_DELIM;
+    root_ = NULL;
+}
+
+IniParser::~IniParser() {
+    Unload();
+}
+
+int IniParser::Unload() {
+    SAFE_DELETE(root_);
+    return 0;
+}
+
+int IniParser::LoadFromFile(const char* filepath) {
+    _filepath = filepath;
+
+    HFile file;
+    if (file.open(filepath, "r") != 0) {
+        return ERR_OPEN_FILE;
+    }
+
+    hbuf_t buf;
+    file.readall(buf);
+
+    return LoadFromMem((const char*)buf.base);
+}
+
+int IniParser::LoadFromMem(const char* data) {
+    Unload();
+
+    root_ = new IniNode;
+    root_->type = IniNode::INI_NODE_TYPE_ROOT;
+
+    std::stringstream ss;
+    ss << data;
+    std::string strLine;
+    int line = 0;
+    string::size_type pos;
+
+    string      content;
+    string      comment;
+    string      strDiv;
+    IniNode* pScopeNode = root_;
+    IniNode* pNewNode = NULL;
+    while (std::getline(ss, strLine)) {
+        ++line;
+
+        content = trimL(strLine);
+        if (content.length() == 0)  {
+            // blank line
+            strDiv += '\n';
+            continue;
+        }
+
+        // trim_comment
+        comment = "";
+        pos = content.find_first_of(_comment);
+        if (pos != string::npos) {
+            comment = content.substr(pos);
+            content = content.substr(0, pos);
+        }
+
+        content = trimR(content);
+        if (content.length() == 0) {
+            strDiv += strLine;
+            strDiv += '\n';
+            continue;
+        } else if (strDiv.length() != 0) {
+            IniNode* pNode = new IniNode;
+            pNode->type = IniNode::INI_NODE_TYPE_DIV;
+            pNode->label = strDiv;
+            pScopeNode->Add(pNode);
+            strDiv = "";
+        }
+
+        if (content[0] == '[') {
+            if (content[content.length()-1] == ']') {
+                // section
+                content = trim(content.substr(1, content.length()-2));
+                pNewNode = new IniNode;
+                pNewNode->type = IniNode::INI_NODE_TYPE_SECTION;
+                pNewNode->label = content;
+                root_->Add(pNewNode);
+                pScopeNode = pNewNode;
+            } else {
+                // hlogw("format error, line:%d", line);
+                continue;   // ignore
+            }
+        } else {
+            pos = content.find_first_of(_delim);
+            if (pos != string::npos) {
+                // key-value
+                pNewNode = new IniNode;
+                pNewNode->type = IniNode::INI_NODE_TYPE_KEY_VALUE;
+                pNewNode->label = trim(content.substr(0, pos));
+                pNewNode->value = trim(content.substr(pos+_delim.length()));
+                pScopeNode->Add(pNewNode);
+            } else {
+                // hlogw("format error, line:%d", line);
+                continue;   // ignore
+            }
+        }
+
+        if (comment.length() != 0) {
+            // tail_comment
+            IniNode* pNode = new IniNode;
+            pNode->type = IniNode::INI_NODE_TYPE_SPAN;
+            pNode->label = comment;
+            pNewNode->Add(pNode);
+            comment = "";
+        }
+    }
+
+    // file end comment
+    if (strDiv.length() != 0) {
+        IniNode* pNode = new IniNode;
+        pNode->type = IniNode::INI_NODE_TYPE_DIV;
+        pNode->label = strDiv;
+        root_->Add(pNode);
+    }
+
+    return 0;
+}
+
+void IniParser::DumpString(IniNode* pNode, string& str) {
+    if (pNode == NULL)  return;
+
+    if (pNode->type != IniNode::INI_NODE_TYPE_SPAN) {
+        if (str.length() > 0 && str[str.length()-1] != '\n') {
+            str += '\n';
+        }
+    }
+
+    switch (pNode->type) {
+    case IniNode::INI_NODE_TYPE_SECTION: {
+        str += '[';
+        str += pNode->label;
+        str += ']';
+    }
+    break;
+    case IniNode::INI_NODE_TYPE_KEY_VALUE: {
+        str += asprintf("%s %s %s", pNode->label.c_str(), _delim.c_str(), pNode->value.c_str());
+    }
+    break;
+    case IniNode::INI_NODE_TYPE_DIV: {
+        str += pNode->label;
+    }
+    break;
+    case IniNode::INI_NODE_TYPE_SPAN: {
+        str += '\t';
+        str += pNode->label;
+    }
+    break;
+    default:
+    break;
+    }
+
+    for (auto p : pNode->children) {
+        DumpString(p, str);
+    }
+}
+
+string IniParser::DumpString() {
+    string str;
+    DumpString(root_, str);
+    return str;
+}
+
+int IniParser::Save() {
+    return SaveAs(_filepath.c_str());
+}
+
+int IniParser::SaveAs(const char* filepath) {
+    string str = DumpString();
+    if (str.length() == 0) {
+        return 0;
+    }
+
+    HFile file;
+    if (file.open(filepath, "w") != 0) {
+        return ERR_SAVE_FILE;
+    }
+    file.write(str.c_str(), str.length());
+
+    return 0;
+}
+
+string IniParser::GetValue(const string& key, const string& section) {
+    IniNode* pSection = root_;
+    if (section.length() != 0) {
+        pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION);
+        if (pSection == NULL)   return "";
+    }
+
+    IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE);
+    if (pKV == NULL)    return "";
+
+    return pKV->value;
+}
+
+void IniParser::SetValue(const string& key, const string& value, const string& section) {
+    IniNode* pSection = root_;
+    if (section.length() != 0) {
+        pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION);
+        if (pSection == NULL) {
+            pSection = new IniNode;
+            pSection->type = IniNode::INI_NODE_TYPE_SECTION;
+            pSection->label = section;
+            root_->Add(pSection);
+        }
+    }
+
+    IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE);
+    if (pKV == NULL) {
+        pKV = new IniNode;
+        pKV->type = IniNode::INI_NODE_TYPE_KEY_VALUE;
+        pKV->label = key;
+        pSection->Add(pKV);
+    }
+    pKV->value = value;
+}

+ 116 - 116
iniparser.h

@@ -1,116 +1,116 @@
-#ifndef HW_INI_PARSER_H_
-#define HW_INI_PARSER_H_
-
-#include <list>
-#include <string>
-
-#include "hdef.h"
-#include "hstring.h"
-
-#define DEFAULT_INI_COMMENT "#"
-#define DEFAULT_INI_DELIM   "="
-
-/**********************************
-# div
-
-[section]
-
-key = value # span
-
-# div
-***********************************/
-
-// class IniComment;
-// class IniSection;
-// class IniKeyValue;
-// for simplicity, we add a member value.
-class IniNode {
- public:
-    enum Type {
-        INI_NODE_TYPE_UNKNOWN,
-        INI_NODE_TYPE_ROOT,
-        INI_NODE_TYPE_SECTION,
-        INI_NODE_TYPE_KEY_VALUE,
-        INI_NODE_TYPE_DIV,
-        INI_NODE_TYPE_SPAN,
-    } type;
-    string  label;
-    string  value;
-    std::list<IniNode*>    children;
-
-    virtual ~IniNode() {
-        for (auto& item : children) {
-            SAFE_DELETE(item);
-        }
-        children.clear();
-    }
-
-    void Add(IniNode* pNode) {
-        children.push_back(pNode);
-    }
-
-    void Del(IniNode* pNode) {
-        for (auto iter = children.begin(); iter != children.end(); ++iter) {
-            if ((*iter) == pNode) {
-                delete (*iter);
-                children.erase(iter);
-                return;
-            }
-        }
-    }
-
-    IniNode* Get(const string& label, Type type = INI_NODE_TYPE_KEY_VALUE) {
-        for (auto& pNode : children) {
-            if (pNode->type == type && pNode->label == label) {
-                return pNode;
-            }
-        }
-        return NULL;
-    }
-};
-
-// class IniComment : public IniNode {
-// public:
-//     string comment;
-// };
-
-// class IniSection : public IniNode {
-// public:
-//     string section;
-// };
-
-// class IniKeyValue : public IniNode {
-// public:
-//     string key;
-//     string value;
-// };
-
-class IniParser {
- public:
-    IniParser();
-    ~IniParser();
-
-    void SetIniComment(const string& comment) {_comment = comment;}
-    void SetIniDilim(const string& delim) {_delim = delim;}
-
-    int LoadFromFile(const char* filepath);
-    int LoadFromMem(const char* data);
-    int Unload();
-
-    void DumpString(IniNode* pNode, string& str);
-    string DumpString();
-    int Save();
-    int SaveAs(const char* filepath);
-
-    string GetValue(const string& key, const string& section = "");
-    void   SetValue(const string& key, const string& value, const string& section = "");
-
- private:
-    string  _comment;
-    string  _delim;
-    string  _filepath;
-
-    IniNode* root_;
-};
-
-#endif  // HW_INI_PARSER_H_
+#ifndef HW_INI_PARSER_H_
+#define HW_INI_PARSER_H_
+
+#include <list>
+#include <string>
+
+#include "hdef.h"
+#include "hstring.h"
+
+#define DEFAULT_INI_COMMENT "#"
+#define DEFAULT_INI_DELIM   "="
+
+/**********************************
+# div
+
+[section]
+
+key = value # span
+
+# div
+***********************************/
+
+// class IniComment;
+// class IniSection;
+// class IniKeyValue;
+// for simplicity, we add a member value.
+class IniNode {
+ public:
+    enum Type {
+        INI_NODE_TYPE_UNKNOWN,
+        INI_NODE_TYPE_ROOT,
+        INI_NODE_TYPE_SECTION,
+        INI_NODE_TYPE_KEY_VALUE,
+        INI_NODE_TYPE_DIV,
+        INI_NODE_TYPE_SPAN,
+    } type;
+    string  label;
+    string  value;
+    std::list<IniNode*>    children;
+
+    virtual ~IniNode() {
+        for (auto& item : children) {
+            SAFE_DELETE(item);
+        }
+        children.clear();
+    }
+
+    void Add(IniNode* pNode) {
+        children.push_back(pNode);
+    }
+
+    void Del(IniNode* pNode) {
+        for (auto iter = children.begin(); iter != children.end(); ++iter) {
+            if ((*iter) == pNode) {
+                delete (*iter);
+                children.erase(iter);
+                return;
+            }
+        }
+    }
+
+    IniNode* Get(const string& label, Type type = INI_NODE_TYPE_KEY_VALUE) {
+        for (auto& pNode : children) {
+            if (pNode->type == type && pNode->label == label) {
+                return pNode;
+            }
+        }
+        return NULL;
+    }
+};
+
+// class IniComment : public IniNode {
+// public:
+//     string comment;
+// };
+
+// class IniSection : public IniNode {
+// public:
+//     string section;
+// };
+
+// class IniKeyValue : public IniNode {
+// public:
+//     string key;
+//     string value;
+// };
+
+class IniParser {
+ public:
+    IniParser();
+    ~IniParser();
+
+    void SetIniComment(const string& comment) {_comment = comment;}
+    void SetIniDilim(const string& delim) {_delim = delim;}
+
+    int LoadFromFile(const char* filepath);
+    int LoadFromMem(const char* data);
+    int Unload();
+
+    void DumpString(IniNode* pNode, string& str);
+    string DumpString();
+    int Save();
+    int SaveAs(const char* filepath);
+
+    string GetValue(const string& key, const string& section = "");
+    void   SetValue(const string& key, const string& value, const string& section = "");
+
+ private:
+    string  _comment;
+    string  _delim;
+    string  _filepath;
+
+    IniNode* root_;
+};
+
+#endif  // HW_INI_PARSER_H_

+ 4 - 3
main.cpp.tmpl

@@ -56,7 +56,8 @@ bool parse_command_line(int argc, char** argv) {
             }
             break;
             default: {
-                return false;
+                printf("Unrecognized options!\n");
+                pexit(-10);
             }
             break;
         }
@@ -78,8 +79,8 @@ int main(int argc, char** argv) {
         printf("Command line parse error, please use -h to get help.\n");
         pexit(-10);
     }
-    
+
     // ...
 
     pexit(0);
-}
+}

+ 652 - 652
msvc_getopt.h

@@ -1,653 +1,653 @@
-#ifndef __GETOPT_H__
-/**
- * DISCLAIMER
- * This file is part of the mingw-w64 runtime package.
- *
- * The mingw-w64 runtime package and its code is distributed in the hope that it 
- * will be useful but WITHOUT ANY WARRANTY.  ALL WARRANTIES, EXPRESSED OR 
- * IMPLIED ARE HEREBY DISCLAIMED.  This includes but is not limited to 
- * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- */
- /*
- * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- *
- * Sponsored in part by the Defense Advanced Research Projects
- * Agency (DARPA) and Air Force Research Laboratory, Air Force
- * Materiel Command, USAF, under agreement number F39502-99-1-0512.
- */
-/*-
- * Copyright (c) 2000 The NetBSD Foundation, Inc.
- * All rights reserved.
- *
- * This code is derived from software contributed to The NetBSD Foundation
- * by Dieter Baron and Thomas Klausner.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
- * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#pragma warning(disable:4996);
-
-#define __GETOPT_H__
-
-/* All the headers include this file. */
-#include <crtdefs.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <windows.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define	REPLACE_GETOPT		/* use this getopt as the system getopt(3) */
-
-#ifdef REPLACE_GETOPT
-int	opterr = 1;		/* if error message should be printed */
-int	optind = 1;		/* index into parent argv vector */
-int	optopt = '?';		/* character checked for validity */
-#undef	optreset		/* see getopt.h */
-#define	optreset		__mingw_optreset
-int	optreset;		/* reset getopt */
-char    *optarg;		/* argument associated with option */
-#endif
-
-//extern int optind;		/* index of first non-option in argv      */
-//extern int optopt;		/* single option character, as parsed     */
-//extern int opterr;		/* flag to enable built-in diagnostics... */
-//				/* (user may set to zero, to suppress)    */
-//
-//extern char *optarg;		/* pointer to argument of current option  */
-
-#define PRINT_ERROR	((opterr) && (*options != ':'))
-
-#define FLAG_PERMUTE	0x01	/* permute non-options to the end of argv */
-#define FLAG_ALLARGS	0x02	/* treat non-options as args to option "-1" */
-#define FLAG_LONGONLY	0x04	/* operate as getopt_long_only */
-
-/* return values */
-#define	BADCH		(int)'?'
-#define	BADARG		((*options == ':') ? (int)':' : (int)'?')
-#define	INORDER 	(int)1
-
-#ifndef __CYGWIN__
-#define __progname __argv[0]
-#else
-extern char __declspec(dllimport) *__progname;
-#endif
-
-#ifdef __CYGWIN__
-static char EMSG[] = "";
-#else
-#define	EMSG		(char*)""
-#endif
-
-static int getopt_internal(int, char * const *, const char *,
-			   const struct option *, int *, int);
-static int parse_long_options(char * const *, const char *,
-			      const struct option *, int *, int);
-static int gcd(int, int);
-static void permute_args(int, int, int, char * const *);
-
-static char *place = EMSG; /* option letter processing */
-
-/* XXX: set optreset to 1 rather than these two */
-static int nonopt_start = -1; /* first non option argument (for permute) */
-static int nonopt_end = -1;   /* first option after non options (for permute) */
-
-/* Error messages */
-static const char recargchar[] = "option requires an argument -- %c";
-static const char recargstring[] = "option requires an argument -- %s";
-static const char ambig[] = "ambiguous option -- %.*s";
-static const char noarg[] = "option doesn't take an argument -- %.*s";
-static const char illoptchar[] = "unknown option -- %c";
-static const char illoptstring[] = "unknown option -- %s";
-
-static void
-_vwarnx(const char *fmt,va_list ap)
-{
-  (void)fprintf(stderr,"%s: ",__progname);
-  if (fmt != NULL)
-    (void)vfprintf(stderr,fmt,ap);
-  (void)fprintf(stderr,"\n");
-}
-
-static void
-warnx(const char *fmt,...)
-{
-  va_list ap;
-  va_start(ap,fmt);
-  _vwarnx(fmt,ap);
-  va_end(ap);
-}
-
-/*
- * Compute the greatest common divisor of a and b.
- */
-static int
-gcd(int a, int b)
-{
-	int c;
-
-	c = a % b;
-	while (c != 0) {
-		a = b;
-		b = c;
-		c = a % b;
-	}
-
-	return (b);
-}
-
-/*
- * Exchange the block from nonopt_start to nonopt_end with the block
- * from nonopt_end to opt_end (keeping the same order of arguments
- * in each block).
- */
-static void
-permute_args(int panonopt_start, int panonopt_end, int opt_end,
-	char * const *nargv)
-{
-	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
-	char *swap;
-
-	/*
-	 * compute lengths of blocks and number and size of cycles
-	 */
-	nnonopts = panonopt_end - panonopt_start;
-	nopts = opt_end - panonopt_end;
-	ncycle = gcd(nnonopts, nopts);
-	cyclelen = (opt_end - panonopt_start) / ncycle;
-
-	for (i = 0; i < ncycle; i++) {
-		cstart = panonopt_end+i;
-		pos = cstart;
-		for (j = 0; j < cyclelen; j++) {
-			if (pos >= panonopt_end)
-				pos -= nnonopts;
-			else
-				pos += nopts;
-			swap = nargv[pos];
-			/* LINTED const cast */
-			((char **) nargv)[pos] = nargv[cstart];
-			/* LINTED const cast */
-			((char **)nargv)[cstart] = swap;
-		}
-	}
-}
-
-#ifdef REPLACE_GETOPT
-/*
- * getopt --
- *	Parse argc/argv argument vector.
- *
- * [eventually this will replace the BSD getopt]
- */
-int
-getopt(int nargc, char * const *nargv, const char *options)
-{
-
-	/*
-	 * We don't pass FLAG_PERMUTE to getopt_internal() since
-	 * the BSD getopt(3) (unlike GNU) has never done this.
-	 *
-	 * Furthermore, since many privileged programs call getopt()
-	 * before dropping privileges it makes sense to keep things
-	 * as simple (and bug-free) as possible.
-	 */
-	return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
-}
-#endif /* REPLACE_GETOPT */
-
-//extern int getopt(int nargc, char * const *nargv, const char *options);
-
-#ifdef _BSD_SOURCE
-/*
- * BSD adds the non-standard `optreset' feature, for reinitialisation
- * of `getopt' parsing.  We support this feature, for applications which
- * proclaim their BSD heritage, before including this header; however,
- * to maintain portability, developers are advised to avoid it.
- */
-# define optreset  __mingw_optreset
-extern int optreset;
-#endif
-#ifdef __cplusplus
-}
-#endif
-/*
- * POSIX requires the `getopt' API to be specified in `unistd.h';
- * thus, `unistd.h' includes this header.  However, we do not want
- * to expose the `getopt_long' or `getopt_long_only' APIs, when
- * included in this manner.  Thus, close the standard __GETOPT_H__
- * declarations block, and open an additional __GETOPT_LONG_H__
- * specific block, only when *not* __UNISTD_H_SOURCED__, in which
- * to declare the extended API.
- */
-#endif /* !defined(__GETOPT_H__) */
-
-#if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
-#define __GETOPT_LONG_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct option		/* specification for a long form option...	*/
-{
-  const char *name;		/* option name, without leading hyphens */
-  int         has_arg;		/* does it take an argument?		*/
-  int        *flag;		/* where to save its status, or NULL	*/
-  int         val;		/* its associated status value		*/
-};
-
-enum    		/* permitted values for its `has_arg' field...	*/
-{
-  no_argument = 0,      	/* option never takes an argument	*/
-  required_argument,		/* option always requires an argument	*/
-  optional_argument		/* option may take an argument		*/
-};
-
-/*
- * parse_long_options --
- *	Parse long options in argc/argv argument vector.
- * Returns -1 if short_too is set and the option does not match long_options.
- */
-static int
-parse_long_options(char * const *nargv, const char *options,
-	const struct option *long_options, int *idx, int short_too)
-{
-	char *current_argv, *has_equal;
-	size_t current_argv_len;
-	int i, ambiguous, match;
-
-#define IDENTICAL_INTERPRETATION(_x, _y)                                \
-	(long_options[(_x)].has_arg == long_options[(_y)].has_arg &&    \
-	 long_options[(_x)].flag == long_options[(_y)].flag &&          \
-	 long_options[(_x)].val == long_options[(_y)].val)
-
-	current_argv = place;
-	match = -1;
-	ambiguous = 0;
-
-	optind++;
-
-	if ((has_equal = strchr(current_argv, '=')) != NULL) {
-		/* argument found (--option=arg) */
-		current_argv_len = has_equal - current_argv;
-		has_equal++;
-	} else
-		current_argv_len = strlen(current_argv);
-
-	for (i = 0; long_options[i].name; i++) {
-		/* find matching long option */
-		if (strncmp(current_argv, long_options[i].name,
-		    current_argv_len))
-			continue;
-
-		if (strlen(long_options[i].name) == current_argv_len) {
-			/* exact match */
-			match = i;
-			ambiguous = 0;
-			break;
-		}
-		/*
-		 * If this is a known short option, don't allow
-		 * a partial match of a single character.
-		 */
-		if (short_too && current_argv_len == 1)
-			continue;
-
-		if (match == -1)	/* partial match */
-			match = i;
-		else if (!IDENTICAL_INTERPRETATION(i, match))
-			ambiguous = 1;
-	}
-	if (ambiguous) {
-		/* ambiguous abbreviation */
-		if (PRINT_ERROR)
-			warnx(ambig, (int)current_argv_len,
-			     current_argv);
-		optopt = 0;
-		return (BADCH);
-	}
-	if (match != -1) {		/* option found */
-		if (long_options[match].has_arg == no_argument
-		    && has_equal) {
-			if (PRINT_ERROR)
-				warnx(noarg, (int)current_argv_len,
-				     current_argv);
-			/*
-			 * XXX: GNU sets optopt to val regardless of flag
-			 */
-			if (long_options[match].flag == NULL)
-				optopt = long_options[match].val;
-			else
-				optopt = 0;
-			return (BADARG);
-		}
-		if (long_options[match].has_arg == required_argument ||
-		    long_options[match].has_arg == optional_argument) {
-			if (has_equal)
-				optarg = has_equal;
-			else if (long_options[match].has_arg ==
-			    required_argument) {
-				/*
-				 * optional argument doesn't use next nargv
-				 */
-				optarg = nargv[optind++];
-			}
-		}
-		if ((long_options[match].has_arg == required_argument)
-		    && (optarg == NULL)) {
-			/*
-			 * Missing argument; leading ':' indicates no error
-			 * should be generated.
-			 */
-			if (PRINT_ERROR)
-				warnx(recargstring,
-				    current_argv);
-			/*
-			 * XXX: GNU sets optopt to val regardless of flag
-			 */
-			if (long_options[match].flag == NULL)
-				optopt = long_options[match].val;
-			else
-				optopt = 0;
-			--optind;
-			return (BADARG);
-		}
-	} else {			/* unknown option */
-		if (short_too) {
-			--optind;
-			return (-1);
-		}
-		if (PRINT_ERROR)
-			warnx(illoptstring, current_argv);
-		optopt = 0;
-		return (BADCH);
-	}
-	if (idx)
-		*idx = match;
-	if (long_options[match].flag) {
-		*long_options[match].flag = long_options[match].val;
-		return (0);
-	} else
-		return (long_options[match].val);
-#undef IDENTICAL_INTERPRETATION
-}
-
-/*
- * getopt_internal --
- *	Parse argc/argv argument vector.  Called by user level routines.
- */
-static int
-getopt_internal(int nargc, char * const *nargv, const char *options,
-	const struct option *long_options, int *idx, int flags)
-{
-	char *oli;				/* option letter list index */
-	int optchar, short_too;
-	static int posixly_correct = -1;
-
-	if (options == NULL)
-		return (-1);
-
-	/*
-	 * XXX Some GNU programs (like cvs) set optind to 0 instead of
-	 * XXX using optreset.  Work around this braindamage.
-	 */
-	if (optind == 0)
-		optind = optreset = 1;
-
-	/*
-	 * Disable GNU extensions if POSIXLY_CORRECT is set or options
-	 * string begins with a '+'.
-	 *
-	 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
-	 *                 optreset != 0 for GNU compatibility.
-	 */
-	if (posixly_correct == -1 || optreset != 0)
-		posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
-	if (*options == '-')
-		flags |= FLAG_ALLARGS;
-	else if (posixly_correct || *options == '+')
-		flags &= ~FLAG_PERMUTE;
-	if (*options == '+' || *options == '-')
-		options++;
-
-	optarg = NULL;
-	if (optreset)
-		nonopt_start = nonopt_end = -1;
-start:
-	if (optreset || !*place) {		/* update scanning pointer */
-		optreset = 0;
-		if (optind >= nargc) {          /* end of argument vector */
-			place = EMSG;
-			if (nonopt_end != -1) {
-				/* do permutation, if we have to */
-				permute_args(nonopt_start, nonopt_end,
-				    optind, nargv);
-				optind -= nonopt_end - nonopt_start;
-			}
-			else if (nonopt_start != -1) {
-				/*
-				 * If we skipped non-options, set optind
-				 * to the first of them.
-				 */
-				optind = nonopt_start;
-			}
-			nonopt_start = nonopt_end = -1;
-			return (-1);
-		}
-		if (*(place = nargv[optind]) != '-' ||
-		    (place[1] == '\0' && strchr(options, '-') == NULL)) {
-			place = EMSG;		/* found non-option */
-			if (flags & FLAG_ALLARGS) {
-				/*
-				 * GNU extension:
-				 * return non-option as argument to option 1
-				 */
-				optarg = nargv[optind++];
-				return (INORDER);
-			}
-			if (!(flags & FLAG_PERMUTE)) {
-				/*
-				 * If no permutation wanted, stop parsing
-				 * at first non-option.
-				 */
-				return (-1);
-			}
-			/* do permutation */
-			if (nonopt_start == -1)
-				nonopt_start = optind;
-			else if (nonopt_end != -1) {
-				permute_args(nonopt_start, nonopt_end,
-				    optind, nargv);
-				nonopt_start = optind -
-				    (nonopt_end - nonopt_start);
-				nonopt_end = -1;
-			}
-			optind++;
-			/* process next argument */
-			goto start;
-		}
-		if (nonopt_start != -1 && nonopt_end == -1)
-			nonopt_end = optind;
-
-		/*
-		 * If we have "-" do nothing, if "--" we are done.
-		 */
-		if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
-			optind++;
-			place = EMSG;
-			/*
-			 * We found an option (--), so if we skipped
-			 * non-options, we have to permute.
-			 */
-			if (nonopt_end != -1) {
-				permute_args(nonopt_start, nonopt_end,
-				    optind, nargv);
-				optind -= nonopt_end - nonopt_start;
-			}
-			nonopt_start = nonopt_end = -1;
-			return (-1);
-		}
-	}
-
-	/*
-	 * Check long options if:
-	 *  1) we were passed some
-	 *  2) the arg is not just "-"
-	 *  3) either the arg starts with -- we are getopt_long_only()
-	 */
-	if (long_options != NULL && place != nargv[optind] &&
-	    (*place == '-' || (flags & FLAG_LONGONLY))) {
-		short_too = 0;
-		if (*place == '-')
-			place++;		/* --foo long option */
-		else if (*place != ':' && strchr(options, *place) != NULL)
-			short_too = 1;		/* could be short option too */
-
-		optchar = parse_long_options(nargv, options, long_options,
-		    idx, short_too);
-		if (optchar != -1) {
-			place = EMSG;
-			return (optchar);
-		}
-	}
-
-	if ((optchar = (int)*place++) == (int)':' ||
-	    (optchar == (int)'-' && *place != '\0') ||
-	    (oli = (char*)strchr(options, optchar)) == NULL) {
-		/*
-		 * If the user specified "-" and  '-' isn't listed in
-		 * options, return -1 (non-option) as per POSIX.
-		 * Otherwise, it is an unknown option character (or ':').
-		 */
-		if (optchar == (int)'-' && *place == '\0')
-			return (-1);
-		if (!*place)
-			++optind;
-		if (PRINT_ERROR)
-			warnx(illoptchar, optchar);
-		optopt = optchar;
-		return (BADCH);
-	}
-	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
-		/* -W long-option */
-		if (*place)			/* no space */
-			/* NOTHING */;
-		else if (++optind >= nargc) {	/* no arg */
-			place = EMSG;
-			if (PRINT_ERROR)
-				warnx(recargchar, optchar);
-			optopt = optchar;
-			return (BADARG);
-		} else				/* white space */
-			place = nargv[optind];
-		optchar = parse_long_options(nargv, options, long_options,
-		    idx, 0);
-		place = EMSG;
-		return (optchar);
-	}
-	if (*++oli != ':') {			/* doesn't take argument */
-		if (!*place)
-			++optind;
-	} else {				/* takes (optional) argument */
-		optarg = NULL;
-		if (*place)			/* no white space */
-			optarg = place;
-		else if (oli[1] != ':') {	/* arg not optional */
-			if (++optind >= nargc) {	/* no arg */
-				place = EMSG;
-				if (PRINT_ERROR)
-					warnx(recargchar, optchar);
-				optopt = optchar;
-				return (BADARG);
-			} else
-				optarg = nargv[optind];
-		}
-		place = EMSG;
-		++optind;
-	}
-	/* dump back option letter */
-	return (optchar);
-}
-
-/*
- * getopt_long --
- *	Parse argc/argv argument vector.
- */
-int
-getopt_long(int nargc, char * const *nargv, const char *options,
-    const struct option *long_options, int *idx)
-{
-
-	return (getopt_internal(nargc, nargv, options, long_options, idx,
-	    FLAG_PERMUTE));
-}
-
-/*
- * getopt_long_only --
- *	Parse argc/argv argument vector.
- */
-int
-getopt_long_only(int nargc, char * const *nargv, const char *options,
-    const struct option *long_options, int *idx)
-{
-
-	return (getopt_internal(nargc, nargv, options, long_options, idx,
-	    FLAG_PERMUTE|FLAG_LONGONLY));
-}
-
-//extern int getopt_long(int nargc, char * const *nargv, const char *options,
-//    const struct option *long_options, int *idx);
-//extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
-//    const struct option *long_options, int *idx);
-/*
- * Previous MinGW implementation had...
- */
-#ifndef HAVE_DECL_GETOPT
-/*
- * ...for the long form API only; keep this for compatibility.
- */
-# define HAVE_DECL_GETOPT	1
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
+#ifndef __GETOPT_H__
+/**
+ * DISCLAIMER
+ * This file is part of the mingw-w64 runtime package.
+ *
+ * The mingw-w64 runtime package and its code is distributed in the hope that it 
+ * will be useful but WITHOUT ANY WARRANTY.  ALL WARRANTIES, EXPRESSED OR 
+ * IMPLIED ARE HEREBY DISCLAIMED.  This includes but is not limited to 
+ * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+ /*
+ * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma warning(disable:4996);
+
+#define __GETOPT_H__
+
+/* All the headers include this file. */
+#include <crtdefs.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <windows.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define	REPLACE_GETOPT		/* use this getopt as the system getopt(3) */
+
+#ifdef REPLACE_GETOPT
+int	opterr = 1;		/* if error message should be printed */
+int	optind = 1;		/* index into parent argv vector */
+int	optopt = '?';		/* character checked for validity */
+#undef	optreset		/* see getopt.h */
+#define	optreset		__mingw_optreset
+int	optreset;		/* reset getopt */
+char    *optarg;		/* argument associated with option */
+#endif
+
+//extern int optind;		/* index of first non-option in argv      */
+//extern int optopt;		/* single option character, as parsed     */
+//extern int opterr;		/* flag to enable built-in diagnostics... */
+//				/* (user may set to zero, to suppress)    */
+//
+//extern char *optarg;		/* pointer to argument of current option  */
+
+#define PRINT_ERROR	((opterr) && (*options != ':'))
+
+#define FLAG_PERMUTE	0x01	/* permute non-options to the end of argv */
+#define FLAG_ALLARGS	0x02	/* treat non-options as args to option "-1" */
+#define FLAG_LONGONLY	0x04	/* operate as getopt_long_only */
+
+/* return values */
+#define	BADCH		(int)'?'
+#define	BADARG		((*options == ':') ? (int)':' : (int)'?')
+#define	INORDER 	(int)1
+
+#ifndef __CYGWIN__
+#define __progname __argv[0]
+#else
+extern char __declspec(dllimport) *__progname;
+#endif
+
+#ifdef __CYGWIN__
+static char EMSG[] = "";
+#else
+#define	EMSG		(char*)""
+#endif
+
+static int getopt_internal(int, char * const *, const char *,
+			   const struct option *, int *, int);
+static int parse_long_options(char * const *, const char *,
+			      const struct option *, int *, int);
+static int gcd(int, int);
+static void permute_args(int, int, int, char * const *);
+
+static char *place = EMSG; /* option letter processing */
+
+/* XXX: set optreset to 1 rather than these two */
+static int nonopt_start = -1; /* first non option argument (for permute) */
+static int nonopt_end = -1;   /* first option after non options (for permute) */
+
+/* Error messages */
+static const char recargchar[] = "option requires an argument -- %c";
+static const char recargstring[] = "option requires an argument -- %s";
+static const char ambig[] = "ambiguous option -- %.*s";
+static const char noarg[] = "option doesn't take an argument -- %.*s";
+static const char illoptchar[] = "unknown option -- %c";
+static const char illoptstring[] = "unknown option -- %s";
+
+static void
+_vwarnx(const char *fmt,va_list ap)
+{
+  (void)fprintf(stderr,"%s: ",__progname);
+  if (fmt != NULL)
+    (void)vfprintf(stderr,fmt,ap);
+  (void)fprintf(stderr,"\n");
+}
+
+static void
+warnx(const char *fmt,...)
+{
+  va_list ap;
+  va_start(ap,fmt);
+  _vwarnx(fmt,ap);
+  va_end(ap);
+}
+
+/*
+ * Compute the greatest common divisor of a and b.
+ */
+static int
+gcd(int a, int b)
+{
+	int c;
+
+	c = a % b;
+	while (c != 0) {
+		a = b;
+		b = c;
+		c = a % b;
+	}
+
+	return (b);
+}
+
+/*
+ * Exchange the block from nonopt_start to nonopt_end with the block
+ * from nonopt_end to opt_end (keeping the same order of arguments
+ * in each block).
+ */
+static void
+permute_args(int panonopt_start, int panonopt_end, int opt_end,
+	char * const *nargv)
+{
+	int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
+	char *swap;
+
+	/*
+	 * compute lengths of blocks and number and size of cycles
+	 */
+	nnonopts = panonopt_end - panonopt_start;
+	nopts = opt_end - panonopt_end;
+	ncycle = gcd(nnonopts, nopts);
+	cyclelen = (opt_end - panonopt_start) / ncycle;
+
+	for (i = 0; i < ncycle; i++) {
+		cstart = panonopt_end+i;
+		pos = cstart;
+		for (j = 0; j < cyclelen; j++) {
+			if (pos >= panonopt_end)
+				pos -= nnonopts;
+			else
+				pos += nopts;
+			swap = nargv[pos];
+			/* LINTED const cast */
+			((char **) nargv)[pos] = nargv[cstart];
+			/* LINTED const cast */
+			((char **)nargv)[cstart] = swap;
+		}
+	}
+}
+
+#ifdef REPLACE_GETOPT
+/*
+ * getopt --
+ *	Parse argc/argv argument vector.
+ *
+ * [eventually this will replace the BSD getopt]
+ */
+int
+getopt(int nargc, char * const *nargv, const char *options)
+{
+
+	/*
+	 * We don't pass FLAG_PERMUTE to getopt_internal() since
+	 * the BSD getopt(3) (unlike GNU) has never done this.
+	 *
+	 * Furthermore, since many privileged programs call getopt()
+	 * before dropping privileges it makes sense to keep things
+	 * as simple (and bug-free) as possible.
+	 */
+	return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
+}
+#endif /* REPLACE_GETOPT */
+
+//extern int getopt(int nargc, char * const *nargv, const char *options);
+
+#ifdef _BSD_SOURCE
+/*
+ * BSD adds the non-standard `optreset' feature, for reinitialisation
+ * of `getopt' parsing.  We support this feature, for applications which
+ * proclaim their BSD heritage, before including this header; however,
+ * to maintain portability, developers are advised to avoid it.
+ */
+# define optreset  __mingw_optreset
+extern int optreset;
+#endif
+#ifdef __cplusplus
+}
+#endif
+/*
+ * POSIX requires the `getopt' API to be specified in `unistd.h';
+ * thus, `unistd.h' includes this header.  However, we do not want
+ * to expose the `getopt_long' or `getopt_long_only' APIs, when
+ * included in this manner.  Thus, close the standard __GETOPT_H__
+ * declarations block, and open an additional __GETOPT_LONG_H__
+ * specific block, only when *not* __UNISTD_H_SOURCED__, in which
+ * to declare the extended API.
+ */
+#endif /* !defined(__GETOPT_H__) */
+
+#if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__)
+#define __GETOPT_LONG_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct option		/* specification for a long form option...	*/
+{
+  const char *name;		/* option name, without leading hyphens */
+  int         has_arg;		/* does it take an argument?		*/
+  int        *flag;		/* where to save its status, or NULL	*/
+  int         val;		/* its associated status value		*/
+};
+
+enum    		/* permitted values for its `has_arg' field...	*/
+{
+  no_argument = 0,      	/* option never takes an argument	*/
+  required_argument,		/* option always requires an argument	*/
+  optional_argument		/* option may take an argument		*/
+};
+
+/*
+ * parse_long_options --
+ *	Parse long options in argc/argv argument vector.
+ * Returns -1 if short_too is set and the option does not match long_options.
+ */
+static int
+parse_long_options(char * const *nargv, const char *options,
+	const struct option *long_options, int *idx, int short_too)
+{
+	char *current_argv, *has_equal;
+	size_t current_argv_len;
+	int i, ambiguous, match;
+
+#define IDENTICAL_INTERPRETATION(_x, _y)                                \
+	(long_options[(_x)].has_arg == long_options[(_y)].has_arg &&    \
+	 long_options[(_x)].flag == long_options[(_y)].flag &&          \
+	 long_options[(_x)].val == long_options[(_y)].val)
+
+	current_argv = place;
+	match = -1;
+	ambiguous = 0;
+
+	optind++;
+
+	if ((has_equal = strchr(current_argv, '=')) != NULL) {
+		/* argument found (--option=arg) */
+		current_argv_len = has_equal - current_argv;
+		has_equal++;
+	} else
+		current_argv_len = strlen(current_argv);
+
+	for (i = 0; long_options[i].name; i++) {
+		/* find matching long option */
+		if (strncmp(current_argv, long_options[i].name,
+		    current_argv_len))
+			continue;
+
+		if (strlen(long_options[i].name) == current_argv_len) {
+			/* exact match */
+			match = i;
+			ambiguous = 0;
+			break;
+		}
+		/*
+		 * If this is a known short option, don't allow
+		 * a partial match of a single character.
+		 */
+		if (short_too && current_argv_len == 1)
+			continue;
+
+		if (match == -1)	/* partial match */
+			match = i;
+		else if (!IDENTICAL_INTERPRETATION(i, match))
+			ambiguous = 1;
+	}
+	if (ambiguous) {
+		/* ambiguous abbreviation */
+		if (PRINT_ERROR)
+			warnx(ambig, (int)current_argv_len,
+			     current_argv);
+		optopt = 0;
+		return (BADCH);
+	}
+	if (match != -1) {		/* option found */
+		if (long_options[match].has_arg == no_argument
+		    && has_equal) {
+			if (PRINT_ERROR)
+				warnx(noarg, (int)current_argv_len,
+				     current_argv);
+			/*
+			 * XXX: GNU sets optopt to val regardless of flag
+			 */
+			if (long_options[match].flag == NULL)
+				optopt = long_options[match].val;
+			else
+				optopt = 0;
+			return (BADARG);
+		}
+		if (long_options[match].has_arg == required_argument ||
+		    long_options[match].has_arg == optional_argument) {
+			if (has_equal)
+				optarg = has_equal;
+			else if (long_options[match].has_arg ==
+			    required_argument) {
+				/*
+				 * optional argument doesn't use next nargv
+				 */
+				optarg = nargv[optind++];
+			}
+		}
+		if ((long_options[match].has_arg == required_argument)
+		    && (optarg == NULL)) {
+			/*
+			 * Missing argument; leading ':' indicates no error
+			 * should be generated.
+			 */
+			if (PRINT_ERROR)
+				warnx(recargstring,
+				    current_argv);
+			/*
+			 * XXX: GNU sets optopt to val regardless of flag
+			 */
+			if (long_options[match].flag == NULL)
+				optopt = long_options[match].val;
+			else
+				optopt = 0;
+			--optind;
+			return (BADARG);
+		}
+	} else {			/* unknown option */
+		if (short_too) {
+			--optind;
+			return (-1);
+		}
+		if (PRINT_ERROR)
+			warnx(illoptstring, current_argv);
+		optopt = 0;
+		return (BADCH);
+	}
+	if (idx)
+		*idx = match;
+	if (long_options[match].flag) {
+		*long_options[match].flag = long_options[match].val;
+		return (0);
+	} else
+		return (long_options[match].val);
+#undef IDENTICAL_INTERPRETATION
+}
+
+/*
+ * getopt_internal --
+ *	Parse argc/argv argument vector.  Called by user level routines.
+ */
+static int
+getopt_internal(int nargc, char * const *nargv, const char *options,
+	const struct option *long_options, int *idx, int flags)
+{
+	char *oli;				/* option letter list index */
+	int optchar, short_too;
+	static int posixly_correct = -1;
+
+	if (options == NULL)
+		return (-1);
+
+	/*
+	 * XXX Some GNU programs (like cvs) set optind to 0 instead of
+	 * XXX using optreset.  Work around this braindamage.
+	 */
+	if (optind == 0)
+		optind = optreset = 1;
+
+	/*
+	 * Disable GNU extensions if POSIXLY_CORRECT is set or options
+	 * string begins with a '+'.
+	 *
+	 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
+	 *                 optreset != 0 for GNU compatibility.
+	 */
+	if (posixly_correct == -1 || optreset != 0)
+		posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
+	if (*options == '-')
+		flags |= FLAG_ALLARGS;
+	else if (posixly_correct || *options == '+')
+		flags &= ~FLAG_PERMUTE;
+	if (*options == '+' || *options == '-')
+		options++;
+
+	optarg = NULL;
+	if (optreset)
+		nonopt_start = nonopt_end = -1;
+start:
+	if (optreset || !*place) {		/* update scanning pointer */
+		optreset = 0;
+		if (optind >= nargc) {          /* end of argument vector */
+			place = EMSG;
+			if (nonopt_end != -1) {
+				/* do permutation, if we have to */
+				permute_args(nonopt_start, nonopt_end,
+				    optind, nargv);
+				optind -= nonopt_end - nonopt_start;
+			}
+			else if (nonopt_start != -1) {
+				/*
+				 * If we skipped non-options, set optind
+				 * to the first of them.
+				 */
+				optind = nonopt_start;
+			}
+			nonopt_start = nonopt_end = -1;
+			return (-1);
+		}
+		if (*(place = nargv[optind]) != '-' ||
+		    (place[1] == '\0' && strchr(options, '-') == NULL)) {
+			place = EMSG;		/* found non-option */
+			if (flags & FLAG_ALLARGS) {
+				/*
+				 * GNU extension:
+				 * return non-option as argument to option 1
+				 */
+				optarg = nargv[optind++];
+				return (INORDER);
+			}
+			if (!(flags & FLAG_PERMUTE)) {
+				/*
+				 * If no permutation wanted, stop parsing
+				 * at first non-option.
+				 */
+				return (-1);
+			}
+			/* do permutation */
+			if (nonopt_start == -1)
+				nonopt_start = optind;
+			else if (nonopt_end != -1) {
+				permute_args(nonopt_start, nonopt_end,
+				    optind, nargv);
+				nonopt_start = optind -
+				    (nonopt_end - nonopt_start);
+				nonopt_end = -1;
+			}
+			optind++;
+			/* process next argument */
+			goto start;
+		}
+		if (nonopt_start != -1 && nonopt_end == -1)
+			nonopt_end = optind;
+
+		/*
+		 * If we have "-" do nothing, if "--" we are done.
+		 */
+		if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
+			optind++;
+			place = EMSG;
+			/*
+			 * We found an option (--), so if we skipped
+			 * non-options, we have to permute.
+			 */
+			if (nonopt_end != -1) {
+				permute_args(nonopt_start, nonopt_end,
+				    optind, nargv);
+				optind -= nonopt_end - nonopt_start;
+			}
+			nonopt_start = nonopt_end = -1;
+			return (-1);
+		}
+	}
+
+	/*
+	 * Check long options if:
+	 *  1) we were passed some
+	 *  2) the arg is not just "-"
+	 *  3) either the arg starts with -- we are getopt_long_only()
+	 */
+	if (long_options != NULL && place != nargv[optind] &&
+	    (*place == '-' || (flags & FLAG_LONGONLY))) {
+		short_too = 0;
+		if (*place == '-')
+			place++;		/* --foo long option */
+		else if (*place != ':' && strchr(options, *place) != NULL)
+			short_too = 1;		/* could be short option too */
+
+		optchar = parse_long_options(nargv, options, long_options,
+		    idx, short_too);
+		if (optchar != -1) {
+			place = EMSG;
+			return (optchar);
+		}
+	}
+
+	if ((optchar = (int)*place++) == (int)':' ||
+	    (optchar == (int)'-' && *place != '\0') ||
+	    (oli = (char*)strchr(options, optchar)) == NULL) {
+		/*
+		 * If the user specified "-" and  '-' isn't listed in
+		 * options, return -1 (non-option) as per POSIX.
+		 * Otherwise, it is an unknown option character (or ':').
+		 */
+		if (optchar == (int)'-' && *place == '\0')
+			return (-1);
+		if (!*place)
+			++optind;
+		if (PRINT_ERROR)
+			warnx(illoptchar, optchar);
+		optopt = optchar;
+		return (BADCH);
+	}
+	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
+		/* -W long-option */
+		if (*place)			/* no space */
+			/* NOTHING */;
+		else if (++optind >= nargc) {	/* no arg */
+			place = EMSG;
+			if (PRINT_ERROR)
+				warnx(recargchar, optchar);
+			optopt = optchar;
+			return (BADARG);
+		} else				/* white space */
+			place = nargv[optind];
+		optchar = parse_long_options(nargv, options, long_options,
+		    idx, 0);
+		place = EMSG;
+		return (optchar);
+	}
+	if (*++oli != ':') {			/* doesn't take argument */
+		if (!*place)
+			++optind;
+	} else {				/* takes (optional) argument */
+		optarg = NULL;
+		if (*place)			/* no white space */
+			optarg = place;
+		else if (oli[1] != ':') {	/* arg not optional */
+			if (++optind >= nargc) {	/* no arg */
+				place = EMSG;
+				if (PRINT_ERROR)
+					warnx(recargchar, optchar);
+				optopt = optchar;
+				return (BADARG);
+			} else
+				optarg = nargv[optind];
+		}
+		place = EMSG;
+		++optind;
+	}
+	/* dump back option letter */
+	return (optchar);
+}
+
+/*
+ * getopt_long --
+ *	Parse argc/argv argument vector.
+ */
+int
+getopt_long(int nargc, char * const *nargv, const char *options,
+    const struct option *long_options, int *idx)
+{
+
+	return (getopt_internal(nargc, nargv, options, long_options, idx,
+	    FLAG_PERMUTE));
+}
+
+/*
+ * getopt_long_only --
+ *	Parse argc/argv argument vector.
+ */
+int
+getopt_long_only(int nargc, char * const *nargv, const char *options,
+    const struct option *long_options, int *idx)
+{
+
+	return (getopt_internal(nargc, nargv, options, long_options, idx,
+	    FLAG_PERMUTE|FLAG_LONGONLY));
+}
+
+//extern int getopt_long(int nargc, char * const *nargv, const char *options,
+//    const struct option *long_options, int *idx);
+//extern int getopt_long_only(int nargc, char * const *nargv, const char *options,
+//    const struct option *long_options, int *idx);
+/*
+ * Previous MinGW implementation had...
+ */
+#ifndef HAVE_DECL_GETOPT
+/*
+ * ...for the long form API only; keep this for compatibility.
+ */
+# define HAVE_DECL_GETOPT	1
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
 #endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */