Преглед на файлове

refactor & style: 函数定义使用namespace

SongZihuan преди 3 години
родител
ревизия
d4416d14b8
променени са 22 файла, в които са добавени 2845 реда и са изтрити 2844 реда
  1. 3 0
      include/tool/byte.h
  2. 58 0
      include/tool/byte.template.h
  3. 215 210
      src/core/activation.cpp
  4. 368 367
      src/core/code.cpp
  5. 112 112
      src/core/env-var.cpp
  6. 13 14
      src/core/gc.cpp
  7. 33 35
      src/core/init.cpp
  8. 164 164
      src/core/inter.cpp
  9. 112 113
      src/core/msg.cpp
  10. 9 10
      src/core/value.cpp
  11. 243 244
      src/core/var.cpp
  12. 62 131
      src/tool/byte.cpp
  13. 57 55
      src/tool/dlc.cpp
  14. 71 71
      src/tool/exit_.cpp
  15. 240 240
      src/tool/file.cpp
  16. 13 13
      src/tool/hash.cpp
  17. 261 254
      src/tool/log.cpp
  18. 198 200
      src/tool/md5.cpp
  19. 67 64
      src/tool/regex.cpp
  20. 413 412
      src/tool/stdio_.cpp
  21. 67 71
      src/tool/string.cpp
  22. 66 64
      src/tool/time.cpp

+ 3 - 0
include/tool/byte.h

@@ -11,6 +11,7 @@ namespace aFuntool {
     };
 
     extern enum EndianType endian;
+    extern enum EndianType save_as;
 
     AFUN_TOOL_EXPORT void getEndian();
 
@@ -28,4 +29,6 @@ namespace aFuntool {
 
 }
 
+#include "byte.template.h"
+
 #endif //AFUN_BYTE_H

+ 58 - 0
include/tool/byte.template.h

@@ -0,0 +1,58 @@
+#ifndef AFUN_BYTE_TEMPLATE_H
+#define AFUN_BYTE_TEMPLATE_H
+
+#include "byte.h"
+
+namespace aFuntool {
+    /**
+     * 写入一个整数
+     * @tparam T 整数类型
+     * @param file FILE 结构体
+     * @param num 整数
+     * @return
+     */
+    template<typename T>
+    bool byteWriteInt(FILE *file, T num){
+        if (endian != save_as) {
+            const size_t len = sizeof(T) / sizeof(uint8_t);  // NOLINT 允许 size(T) / size(T)
+            union {
+                T a;//元素a,占2个字节
+                uint8_t b[len];//元素b,占1个字节,b在内存中的地址为a最低字节的地址
+            } in{.a = num}, out{};
+
+            for (int i = 0; i < len; i++)
+                out.b[len - i] = in.b[i];  // 大小端序转换
+            num = out.a;
+        }
+
+        return fwrite(&num, sizeof(T), 1, file) == 1;
+    }
+
+    /**
+     * 读取一个整数
+     * @tparam T 整数类型
+     * @param file FILE 结构体
+     * @param num 整数
+     * @return
+     */
+    template<typename T>
+    bool byteReadInt(FILE *file, T *num){
+        size_t re = fread(num, sizeof(T), 1, file);
+
+        if (endian != save_as) {
+            const size_t len = sizeof(T) / sizeof(uint8_t);  // NOLINT 允许 size(T) / size(T)
+            union {
+                T a;//元素a,占2个字节
+                uint8_t b[len];//元素b,占1个字节,b在内存中的地址为a最低字节的地址
+            } in{.a = *num}, out{};
+
+            for (int i = 0; i < len; i++)
+                out.b[len - i] = in.b[i];  // 大小端序转换
+            *num = out.a;
+        }
+
+        return re == 1;
+    }
+}
+
+#endif //AFUN_BYTE_TEMPLATE_H

+ 215 - 210
src/core/activation.cpp

@@ -4,253 +4,258 @@
 #include "msg.h"
 #include "code.h"
 
-using namespace aFuncore;
-using namespace aFuntool;
-
-/**
- * 创建基本Activation
- * 自动继承上层VarList和UpMessage
- * 自动压入inter
- * @param inter_
- */
-Activation::Activation(Inter &inter_)
-    : inter{inter_}, prev {inter_.getActivation()}, line{0},
-      up{prev == nullptr ? nullptr : &prev->up}, down {} {
-    if (prev != nullptr) {
-        varlist = new VarList(prev->varlist);
-        line = prev->line;
-        path = prev->path;
-    } else {
-        varlist = new VarList();
-        path = "";
+namespace aFuncore {
+    /**
+     * 创建基本Activation
+     * 自动继承上层VarList和UpMessage
+     * 自动压入inter
+     * @param inter_
+     */
+    Activation::Activation(Inter &inter_)
+            : inter{inter_}, prev{inter_.getActivation()}, line{0},
+              up{prev == nullptr ? nullptr : &prev->up}, down{}{
+        if (prev != nullptr) {
+            varlist = new VarList(prev->varlist);
+            line = prev->line;
+            path = prev->path;
+        } else {
+            varlist = new VarList();
+            path = "";
+        }
+        inter.pushActivation(this);
     }
-    inter.pushActivation(this);
-}
 
-/**
- * 析构Activation
- * 注意: 不会自动从inter中弹出
- * 释放Varlist并且将DownMessage压入上层
- */
-Activation::~Activation(){
-    if (prev != nullptr)
-        down.joinMsg(prev->down);
-    delete varlist;
-}
+    /**
+     * 析构Activation
+     * 注意: 不会自动从inter中弹出
+     * 释放Varlist并且将DownMessage压入上层
+     */
+    Activation::~Activation(){
+        if (prev != nullptr)
+            down.joinMsg(prev->down);
+        delete varlist;
+    }
 
-/**
- * 运行代码
- * @param code
- */
-void Activation::runCode(Code *code) {
-    auto code_type = code->getType();
-    if (code_type == Code::code_start) {  // start 不处理 msg
-        auto *none = new Object("None", inter);
-        down.pushMessage(new NormalMessage(none));
-    } else {
-        if (code_type == Code::code_element) {
-            runCodeElement(code);
-        } else switch (code->getBlockType()) {
-            case Code::block_p:  // 顺序执行
-                runCodeBlockP(code);
-                break;
-            case Code::block_b:
-                runCodeBlockB(code);
-                break;
-            case Code::block_c:
-                runCodeBlockC(code);
-                break;
-            default:
-                errorLog(aFunCoreLogger, "Error block type.");
-                break;
+    /**
+     * 运行代码
+     * @param code
+     */
+    void Activation::runCode(Code *code){
+        auto code_type = code->getType();
+        if (code_type == Code::code_start) {  // start 不处理 msg
+            auto *none = new Object("None", inter);
+            down.pushMessage(new NormalMessage(none));
+        } else {
+            if (code_type == Code::code_element) {
+                runCodeElement(code);
+            } else
+                switch (code->getBlockType()) {
+                    case Code::block_p:  // 顺序执行
+                        runCodeBlockP(code);
+                        break;
+                    case Code::block_b:
+                        runCodeBlockB(code);
+                        break;
+                    case Code::block_c:
+                        runCodeBlockC(code);
+                        break;
+                    default:
+                        errorLog(aFunCoreLogger, "Error block type.");
+                        break;
+                }
         }
     }
-}
 
-void Activation::runCodeElement(Code *code) {
-    std::string literaler_name;
-    bool in_protect = false;
-    Object *obj = nullptr;
-    if (inter.checkLiteral(code->getElement(), literaler_name, in_protect)) {
-        if (in_protect)
-            obj = inter.getProtectVarSpace()->findObject(literaler_name);
-        else
-            obj = varlist->findObject(literaler_name);
-        auto literaler = dynamic_cast<Literaler *>(obj);
-        if (literaler != nullptr)
-            literaler->getObject(code->getElement(), code->getPrefix(), inter);
-        else
-            down.pushMessage(new ErrorMessage("TypeError", "Error type of literal.", this));
-    } else {
-        if (varlist != nullptr)
-            obj = varlist->findObject(code->getElement());
-        if (obj != nullptr) {
-            auto cbv = dynamic_cast<CallBackVar *>(obj);
-            if (cbv != nullptr && cbv->isCallBack())
-                cbv->callBack(inter);
+    void Activation::runCodeElement(Code *code){
+        std::string literaler_name;
+        bool in_protect = false;
+        Object *obj = nullptr;
+        if (inter.checkLiteral(code->getElement(), literaler_name, in_protect)) {
+            if (in_protect)
+                obj = inter.getProtectVarSpace()->findObject(literaler_name);
             else
-                down.pushMessage(new NormalMessage(obj));
-        } else
-            down.pushMessage(new ErrorMessage("NameError", std::string("Variable ") + code->getElement() + " not fount.", this));
+                obj = varlist->findObject(literaler_name);
+            auto literaler = dynamic_cast<Literaler *>(obj);
+            if (literaler != nullptr)
+                literaler->getObject(code->getElement(), code->getPrefix(), inter);
+            else
+                down.pushMessage(new ErrorMessage("TypeError", "Error type of literal.", this));
+        } else {
+            if (varlist != nullptr)
+                obj = varlist->findObject(code->getElement());
+            if (obj != nullptr) {
+                auto cbv = dynamic_cast<CallBackVar *>(obj);
+                if (cbv != nullptr && cbv->isCallBack())
+                    cbv->callBack(inter);
+                else
+                    down.pushMessage(new NormalMessage(obj));
+            } else
+                down.pushMessage(
+                        new ErrorMessage("NameError", std::string("Variable ") + code->getElement() + " not fount.",
+                                         this));
+        }
     }
-}
 
-void Activation::runCodeBlockP(Code *code) {
-    new ExeActivation(code->getSon(), inter);
-}
-
-void Activation::runCodeBlockC(Code *code) {
-    new FuncActivation(code, inter);
-}
+    void Activation::runCodeBlockP(Code *code){
+        new ExeActivation(code->getSon(), inter);
+    }
 
-void Activation::runCodeBlockB(Code *code) {
-    new FuncActivation(code, inter);
-}
+    void Activation::runCodeBlockC(Code *code){
+        new FuncActivation(code, inter);
+    }
 
-Activation::ActivationStatus ExeActivation::getCode(Code *&code){
-    code = next;
-    if (code == nullptr)
-        return as_end;
+    void Activation::runCodeBlockB(Code *code){
+        new FuncActivation(code, inter);
+    }
 
-    if (!first) {
-        auto msg = down.getMessage<NormalMessage>("NORMAL");
-        if (msg == nullptr)
+    Activation::ActivationStatus ExeActivation::getCode(Code *&code){
+        code = next;
+        if (code == nullptr)
             return as_end;
-        else
-            down.popMessage("NORMAL");
-        delete msg;
-    }
 
-    first = false;
-    line = code->getFileLine();
-    if (code->getFilePath() != nullptr)
-        path = code->getFilePath();
-    next = code->toNext();
-    return as_run;
-}
+        if (!first) {
+            auto msg = down.getMessage<NormalMessage>("NORMAL");
+            if (msg == nullptr)
+                return as_end;
+            else
+                down.popMessage("NORMAL");
+            delete msg;
+        }
+
+        first = false;
+        line = code->getFileLine();
+        if (code->getFilePath() != nullptr)
+            path = code->getFilePath();
+        next = code->toNext();
+        return as_run;
+    }
 
-TopActivation::TopActivation(Code *code, Inter &inter_) : ExeActivation(code, inter_) {
-    varlist->connect(inter_.getGlobalVarlist());
-}
+    TopActivation::TopActivation(Code *code, Inter &inter_) : ExeActivation(code, inter_){
+        varlist->connect(inter_.getGlobalVarlist());
+    }
 
-static void ActivationTopProgress(Message *msg, void *) {
-    auto *t = dynamic_cast<TopMessage *>(msg);
-    if (t)
-        t->topProgress();
-};
+    static void ActivationTopProgress(Message *msg, void *){
+        auto *t = dynamic_cast<TopMessage *>(msg);
+        if (t)
+            t->topProgress();
+    };
 
-TopActivation::~TopActivation() {
-    down.forEach(ActivationTopProgress, nullptr);
-}
+    TopActivation::~TopActivation(){
+        down.forEach(ActivationTopProgress, nullptr);
+    }
 
-FuncActivation::~FuncActivation(){
-    delete call_func;
-}
+    FuncActivation::~FuncActivation(){
+        delete call_func;
+    }
 
-Activation::ActivationStatus FuncActivation::getCode(Code *&code){
-    if (on_tail)
-        return as_end;
+    Activation::ActivationStatus FuncActivation::getCode(Code *&code){
+        if (on_tail)
+            return as_end;
 
-    if (status == func_first) {
-        switch (call->getBlockType()) {
-            case Code::block_c:
-                status = func_get_func;
-                code = call->getSon();
-                if (code == nullptr) {
+        if (status == func_first) {
+            switch (call->getBlockType()) {
+                case Code::block_c:
+                    status = func_get_func;
+                    code = call->getSon();
+                    if (code == nullptr) {
+                        line = 0;
+                        down.pushMessage(new ErrorMessage("SyntaxError", "Callback without code.", this));
+                        return as_end;
+                    }
+                    line = code->getFileLine();
+                    if (code->getFilePath() != nullptr)
+                        path = code->getFilePath();
+                    return as_run;
+                case Code::block_b: {
+                    std::string prefix;
+                    if (!inter.getEnvVarSpace().findString("sys:prefix", prefix) ||
+                        prefix.size() != Inter::PREFIX_COUNT)
+                        prefix = "''";
+                    char quote = prefix[Inter::prefix_quote];
+                    for (Code *var = call->getSon(); var != nullptr; var = var->toNext()) {
+                        if (var->getType() != Code::code_element || var->getPrefix() == quote ||
+                            inter.checkLiteral(var->getElement()))
+                            continue;
+                        Object *obj = varlist->findObject(var->getElement());
+                        if (obj == nullptr || !dynamic_cast<Function *>(obj) ||
+                            !dynamic_cast<Function *>(obj)->isInfix())
+                            continue;
+                        func = dynamic_cast<Function *>(obj);
+                        if (func == nullptr || !func->isInfix())
+                            continue;
+                        status = func_get_func;
+                        break;  /* 跳转到: 执行变量获取前的准备 */
+                    }
+                    if (status != func_get_func) {
+                        line = 0;
+                        down.pushMessage(new ErrorMessage("SyntaxError", "Callback without code.", this));
+                        return as_end;
+                    }
+                    break;
+                }
+                default:
+                    errorLog(aFunCoreLogger, "Error FuncActivation block type");
                     line = 0;
-                    down.pushMessage(new ErrorMessage("SyntaxError", "Callback without code.", this));
+                    down.pushMessage(new ErrorMessage("RuntimeError", "Error FuncActivation block type.", this));
+                    return as_end;
+            }
+        }
+
+        if (status == func_get_func) {
+            if (func == nullptr) {
+                auto *msg = down.getMessage<NormalMessage>("NORMAL");
+                if (msg == nullptr)
+                    return as_end;
+                else
+                    down.popMessage("NORMAL");
+                func = dynamic_cast<Function *>(msg->getObject());
+                delete msg;
+                if (func == nullptr) {
+                    down.pushMessage(new ErrorMessage("TypeError", "Callback without function.", this));
                     return as_end;
                 }
+            }
+
+            /* Label: 执行变量获取前的准备 */
+            status = func_get_arg;
+            call_func = func->getCallFunction(call, inter);
+            acl = call_func->getArgCodeList();
+            acl_begin = acl->begin();
+            acl_end = acl->end();
+            if (acl_begin != acl_end) {  // 如果有参数需要计算
+                code = acl_begin->code;
                 line = code->getFileLine();
                 if (code->getFilePath() != nullptr)
                     path = code->getFilePath();
                 return as_run;
-            case Code::block_b: {
-                std::string prefix;
-                if (!inter.getEnvVarSpace().findString("sys:prefix", prefix) || prefix.size() != Inter::PREFIX_COUNT)
-                    prefix = "''";
-                char quote = prefix[Inter::prefix_quote];
-                for (Code *var = call->getSon(); var != nullptr; var = var->toNext()) {
-                    if (var->getType() != Code::code_element || var->getPrefix() == quote || inter.checkLiteral(var->getElement()))
-                        continue;
-                    Object *obj = varlist->findObject(var->getElement());
-                    if (obj == nullptr || !dynamic_cast<Function *>(obj) || !dynamic_cast<Function *>(obj)->isInfix())
-                        continue;
-                    func = dynamic_cast<Function *>(obj);
-                    if (func == nullptr || !func->isInfix())
-                        continue;
-                    status = func_get_func;
-                    break;  /* 跳转到: 执行变量获取前的准备 */
-                }
-                if (status != func_get_func) {
-                    line = 0;
-                    down.pushMessage(new ErrorMessage("SyntaxError", "Callback without code.", this));
-                    return as_end;
-                }
-                break;
             }
-            default:
-                errorLog(aFunCoreLogger, "Error FuncActivation block type");
-                line = 0;
-                down.pushMessage(new ErrorMessage("RuntimeError", "Error FuncActivation block type.", this));
-                return as_end;
         }
-    }
 
-    if (status == func_get_func) {
-        if (func == nullptr) {
+        if (acl_begin != acl_end) {  // 获取参数计算结果
             auto *msg = down.getMessage<NormalMessage>("NORMAL");
             if (msg == nullptr)
                 return as_end;
-            else
-                down.popMessage("NORMAL");
-            func = dynamic_cast<Function *>(msg->getObject());
+            down.popMessage("NORMAL");
+
+            acl_begin->ret = msg->getObject();
             delete msg;
-            if (func == nullptr) {
-                down.pushMessage(new ErrorMessage("TypeError", "Callback without function.", this));
-                return as_end;
+
+            acl_begin++;
+            if (acl_begin != acl_end) {
+                code = acl_begin->code;
+                line = code->getFileLine();
+                if (code->getFilePath() != nullptr)
+                    path = code->getFilePath();
+                return as_run;
             }
         }
 
-        /* Label: 执行变量获取前的准备 */
-        status = func_get_arg;
-        call_func = func->getCallFunction(call, inter);
-        acl = call_func->getArgCodeList();
-        acl_begin = acl->begin();
-        acl_end = acl->end();
-        if (acl_begin != acl_end) {  // 如果有参数需要计算
-            code = acl_begin->code;
-            line = code->getFileLine();
-            if (code->getFilePath() != nullptr)
-                path = code->getFilePath();
-            return as_run;
-        }
+        on_tail = true;
+        line = 0;
+        return as_end_run;
     }
 
-    if (acl_begin != acl_end) {  // 获取参数计算结果
-        auto *msg = down.getMessage<NormalMessage>("NORMAL");
-        if (msg == nullptr)
-            return as_end;
-        down.popMessage("NORMAL");
-
-        acl_begin->ret = msg->getObject();
-        delete msg;
-
-        acl_begin++;
-        if (acl_begin != acl_end) {
-            code = acl_begin->code;
-            line = code->getFileLine();
-            if (code->getFilePath() != nullptr)
-                path = code->getFilePath();
-            return as_run;
-        }
+    void FuncActivation::endRun(){
+        call_func->runFunction();
     }
-
-    on_tail = true;
-    line = 0;
-    return as_end_run;
-}
-
-void FuncActivation::endRun(){
-    call_func->runFunction();
-}
+}

+ 368 - 367
src/core/code.cpp

@@ -1,22 +1,21 @@
 #include "code.h"
 #include "init.h"
-using namespace aFuncore;
-using namespace aFuntool;
+namespace aFuncore {
 
 /**
  * 创建 `start` 代码块
  * @param line
  * @param file
  */
-Code::Code(FileLine line, ConstFilePath file){  // NOLINT 不初始化 element, block_type, son
-    this->type = code_start;
-    if (file.empty()) {
-        errorLog(aFunCoreLogger, "Make `start` code without FilePath");
-        this->file = nullptr;
-    } else
-        this->file = strCopy(file.c_str());
-    this->line = line;
-}
+    Code::Code(aFuntool::FileLine line, aFuntool::ConstFilePath file){  // NOLINT 不初始化 element, block_type, son
+        this->type = code_start;
+        if (file.empty()) {
+            errorLog(aFunCoreLogger, "Make `start` code without FilePath");
+            this->file = nullptr;
+        } else
+            this->file = aFuntool::strCopy(file.c_str());
+        this->line = line;
+    }
 
 /**
  * 创建 `element` 代码块
@@ -25,21 +24,22 @@ Code::Code(FileLine line, ConstFilePath file){  // NOLINT 不初始化 element,
  * @param file
  * @param prefix
  */
-aFuncore::Code::Code(const std::string &element, FileLine line, ConstFilePath file, char prefix){  // NOLINT 不初始化 block_type, son
-    this->type=code_element;
-    this->prefix = prefix;
-    if (file.empty())
-        this->file = nullptr;
-    else
-        this->file = strCopy(file.c_str());
-    this->line = line;
-
-    if (!isCharUTF8(element)) {
-        errorLog(aFunCoreLogger, "Element not utf-8");
-        this->element = nullptr;
-    } else
-        this->element = strCopy(element.c_str());
-}
+    Code::Code(const std::string &element, aFuntool::FileLine line, aFuntool::ConstFilePath file,
+                         char prefix){  // NOLINT 不初始化 block_type, son
+        this->type = code_element;
+        this->prefix = prefix;
+        if (file.empty())
+            this->file = nullptr;
+        else
+            this->file = aFuntool::strCopy(file.c_str());
+        this->line = line;
+
+        if (!aFuntool::isCharUTF8(element)) {
+            errorLog(aFunCoreLogger, "Element not utf-8");
+            this->element = nullptr;
+        } else
+            this->element = aFuntool::strCopy(element.c_str());
+    }
 
 /**
  * 创建 `block` 代码块
@@ -49,123 +49,123 @@ aFuncore::Code::Code(const std::string &element, FileLine line, ConstFilePath fi
  * @param file
  * @param prefix
  */
-Code::Code(BlockType block_type, Code *son, FileLine line, ConstFilePath file, char prefix){  // NOLINT 不出时候 element
-    this->type=code_block;
-    this->prefix = prefix;
-    if (file.empty())
-        this->file = nullptr;
-    else
-        this->file = strCopy(file.c_str());
-    this->line = line;
-
-    this->block_type = block_type;
-    this->son = son;
-
-    for (Code *tmp = son; tmp != nullptr; tmp = tmp->next)
-        tmp->father = this;
-}
-
-Code::~Code(){
-    if (type == code_element)
-        free(element);
-    free(file);
-}
+    Code::Code(BlockType block_type, Code *son, aFuntool::FileLine line, aFuntool::ConstFilePath file, char prefix){  // NOLINT 不出时候 element
+        this->type = code_block;
+        this->prefix = prefix;
+        if (file.empty())
+            this->file = nullptr;
+        else
+            this->file = aFuntool::strCopy(file.c_str());
+        this->line = line;
+
+        this->block_type = block_type;
+        this->son = son;
+
+        for (Code *tmp = son; tmp != nullptr; tmp = tmp->next)
+            tmp->father = this;
+    }
+
+    Code::~Code(){
+        if (type == code_element)
+            free(element);
+        free(file);
+    }
 
 /**
  * 连结代码块
  * @param code
  * @return
  */
-Code *Code::connect(Code *code){
-    Code *tmp = this;
-    while (tmp->next != nullptr)
-        tmp = tmp->next;
-
-    if (code->type == code_start) {
-        errorLog(aFunCoreLogger, "Code connect with `start`");
-        return tmp;
-    }
+    Code *Code::connect(Code *code){
+        Code *tmp = this;
+        while (tmp->next != nullptr)
+            tmp = tmp->next;
+
+        if (code->type == code_start) {
+            errorLog(aFunCoreLogger, "Code connect with `start`");
+            return tmp;
+        }
 
-    Code *father_ = tmp->father;
-    tmp->next = code;
-    code->prev = tmp;
-    while (code->next != nullptr) {
-        code = code->next;
-        code->father = father_;
+        Code *father_ = tmp->father;
+        tmp->next = code;
+        code->prev = tmp;
+        while (code->next != nullptr) {
+            code = code->next;
+            code->father = father_;
+        }
+        return code;
     }
-    return code;
-}
 
 /**
  * 删除自己以及其子、兄代码块
  */
-void Code::destruct(Code *code){
-    if (code->type != code_start) {
-        errorLog(aFunCoreLogger, "Code delete did not with `start`");
-        return;
-    }
+    void Code::destruct(Code *code){
+        if (code->type != code_start) {
+            errorLog(aFunCoreLogger, "Code delete did not with `start`");
+            return;
+        }
 
-    Code *next_tmp;
-    while (code != nullptr) {
-        if (code->type != code_block || code->son == nullptr) {
-            if (code->next == nullptr) {
-                if (code->father == nullptr)
-                    next_tmp = nullptr;
-                else {
-                    next_tmp = code->father;
-                    next_tmp->son = nullptr;
-                }
+        Code *next_tmp;
+        while (code != nullptr) {
+            if (code->type != code_block || code->son == nullptr) {
+                if (code->next == nullptr) {
+                    if (code->father == nullptr)
+                        next_tmp = nullptr;
+                    else {
+                        next_tmp = code->father;
+                        next_tmp->son = nullptr;
+                    }
+                } else
+                    next_tmp = code->next;
+                delete code;
+                code = next_tmp;
             } else
-                next_tmp = code->next;
-            delete code;
-            code = next_tmp;
-        } else
-            code = code->son;
+                code = code->son;
+        }
+        delete code;
     }
-    delete code;
-}
 
 /**
  * 显式代码块内容
  */
-void Code::display() const {
-    printf_stdout(0, "%c[father: %p] type=%d %p", prefix == NUL ? '-' : prefix, father, type, this);
-    if (type == code_element)
-        printf_stdout(0, " element: %s\n", element);
-    else if (type == code_block)
-        printf_stdout(0, " block: '%c' son: %p\n", block_type, son);
-    else
-        printf_stdout(0, "\n");
-}
+    void Code::display() const{
+        aFuntool::printf_stdout(0, "%c[father: %p] type=%d %p", prefix == aFuntool::NUL ? '-' : prefix, father, type, this);
+        if (type == code_element)
+            aFuntool::printf_stdout(0, " element: %s\n", element);
+        else if (type == code_block)
+            aFuntool::printf_stdout(0, " block: '%c' son: %p\n", block_type, son);
+        else
+            aFuntool::printf_stdout(0, "\n");
+    }
 
 /**
  * 显式自己以及其子、兄代码块
  */
-void Code::displayAll() const {
-    if (this->type != code_start) {
-        errorLog(aFunCoreLogger, "Code dsplay all did not with `start`");
-        return;
-    }
-
-    const Code *tmp = this;
-    while (tmp != nullptr) {
-        tmp->display();
-        if (tmp->type == code_block && tmp->son != nullptr){
-            tmp = tmp->son;
-            continue;
+    void Code::displayAll() const{
+        if (this->type != code_start) {
+            errorLog(aFunCoreLogger, "Code dsplay all did not with `start`");
+            return;
         }
 
-        if (tmp->next == nullptr) {
-            do {
-                tmp = tmp->father;
-            } while(tmp != nullptr && tmp->next == nullptr);
-            if (tmp == nullptr)
-                break;
-            tmp = tmp->next;
-        } else
-            tmp = tmp->next;
+        const Code *tmp = this;
+        while (tmp != nullptr) {
+            tmp->display();
+            if (tmp->type == code_block && tmp->son != nullptr) {
+                tmp = tmp->son;
+                continue;
+            }
+
+            if (tmp->next == nullptr) {
+                do {
+                    tmp = tmp->father;
+                } while (tmp != nullptr && tmp->next == nullptr);
+                if (tmp == nullptr)
+                    break;
+                tmp = tmp->next;
+            } else
+                tmp = tmp->next;
+        }
     }
-}
 
 #define Done(write) do{if(!(write)){return false;}}while(0)
 
@@ -175,31 +175,31 @@ void Code::displayAll() const {
  * @param debug 是否记录 debug 信息
  * @return
  */
-bool Code::write_v1(FILE *f, bool debug) const{
-    switch (type) {
-        case code_element:
-            Done(byteWriteInt(f, (int8_t)code_element));
-            Done(byteWriteInt(f, (int8_t)prefix));
-            Done(byteWriteStr(f, element));
-            break;
-        case code_block:
-            if (son == nullptr)
-                Done(byteWriteInt(f, (int8_t)4));  // 空 block 标注为 4
-            else
-                Done(byteWriteInt(f, (int8_t) code_block));
-            Done(byteWriteInt(f, (int8_t)prefix));
-            Done(byteWriteInt(f, (int8_t)block_type));
-            break;
-        default:
-            break;
+    bool Code::write_v1(FILE *f, bool debug) const{
+        switch (type) {
+            case code_element:
+                Done(aFuntool::byteWriteInt(f, (int8_t) code_element));
+                Done(aFuntool::byteWriteInt(f, (int8_t) prefix));
+                Done(aFuntool::byteWriteStr(f, element));
+                break;
+            case code_block:
+                if (son == nullptr)
+                    Done(aFuntool::byteWriteInt(f, (int8_t) 4));  // 空 block 标注为 4
+                else
+                    Done(aFuntool::byteWriteInt(f, (int8_t) code_block));
+                Done(aFuntool::byteWriteInt(f, (int8_t) prefix));
+                Done(aFuntool::byteWriteInt(f, (int8_t) block_type));
+                break;
+            default:
+                break;
 
+        }
+        if (debug) {
+            Done(aFuntool::byteWriteInt(f, (int16_t) line));
+            Done(aFuntool::byteWriteStr(f, file));
+        }
+        return true;
     }
-    if (debug) {
-        Done(byteWriteInt(f, (int16_t)line));
-        Done(byteWriteStr(f, file));
-    }
-    return true;
-}
 
 /**
  * 将的子、兄code写入到文件中 (版本: 1)
@@ -208,34 +208,34 @@ bool Code::write_v1(FILE *f, bool debug) const{
  * @param debug
  * @return
  */
-bool Code::writeAll_v1(FILE *f, bool debug) const{
-    if (this->type != code_start) {
-        errorLog(aFunCoreLogger, "Code write all did not with `start`");
-        return false;
-    }
-
-    const Code *tmp = this;
-    while (tmp != nullptr) {
-        Done(tmp->write_v1(f, debug));
-        if (tmp->type == code_block && tmp->son != nullptr){
-            tmp = tmp->son;
-            continue;
+    bool Code::writeAll_v1(FILE *f, bool debug) const{
+        if (this->type != code_start) {
+            errorLog(aFunCoreLogger, "Code write all did not with `start`");
+            return false;
         }
 
-        if (tmp->next == nullptr) {
-            do {
-                tmp = tmp->father;
-                Done(byteWriteInt(f, (int8_t)3));
-            } while(tmp != nullptr && tmp->next == nullptr);
-            if (tmp == nullptr)
-                break;
-            tmp = tmp->next;
-        } else
-            tmp = tmp->next;
+        const Code *tmp = this;
+        while (tmp != nullptr) {
+            Done(tmp->write_v1(f, debug));
+            if (tmp->type == code_block && tmp->son != nullptr) {
+                tmp = tmp->son;
+                continue;
+            }
+
+            if (tmp->next == nullptr) {
+                do {
+                    tmp = tmp->father;
+                    Done(aFuntool::byteWriteInt(f, (int8_t) 3));
+                } while (tmp != nullptr && tmp->next == nullptr);
+                if (tmp == nullptr)
+                    break;
+                tmp = tmp->next;
+            } else
+                tmp = tmp->next;
+        }
+        Done(aFuntool::byteWriteInt(f, (int8_t) 0));
+        return true;
     }
-    Done(byteWriteInt(f, (int8_t)0));
-    return true;
-}
 
 /**
  * 读取文件中的code (版本: 1)
@@ -243,56 +243,56 @@ bool Code::writeAll_v1(FILE *f, bool debug) const{
  * @param debug 文件是否包含 debug 信息
  * @return
  */
-bool Code::readAll_v1(FILE *f, bool debug) {
-    if (this->type != code_start) {
-        errorLog(aFunCoreLogger, "Code read all did not with `start`");
-        return false;
-    }
-
-    Code *father_ = nullptr;
-    Code *next_ = this;
-    const Code *tmp = this;
-    while (tmp != nullptr) {
-        int8_t type_ = NUL;
-        Done(byteReadInt(f, &type_));
-        switch (type_) {
-            case 0:
-                goto RETURN;
-            case 3:
-                if (next_ == nullptr) {
-                    errorLog(aFunCoreLogger, "Code read all error");
-                    return false;
-                }
-                next_ = next_->father;
-                break;
-            default: {
-                Code *ret;
-                if (next_ == nullptr && father_ != nullptr)
-                    ret = father_->read_v1(f, debug, type_, true);
-                else if (next_ != nullptr)
-                    ret = next_->read_v1(f, debug, type_, false);
-                else {
-                    errorLog(aFunCoreLogger, "Code read all error");
-                    return false;
-                }
+    bool Code::readAll_v1(FILE *f, bool debug){
+        if (this->type != code_start) {
+            errorLog(aFunCoreLogger, "Code read all did not with `start`");
+            return false;
+        }
 
-                if (ret == nullptr) {
-                    errorLog(aFunCoreLogger, "Code read error");
-                    return false;
-                } else if (type_ == code_block) {
-                    next_ = nullptr;
-                    father_ = ret;
-                } else {
-                    next_ = ret;
-                    father_ = nullptr;
+        Code *father_ = nullptr;
+        Code *next_ = this;
+        const Code *tmp = this;
+        while (tmp != nullptr) {
+            int8_t type_ = aFuntool::NUL;
+            Done(aFuntool::byteReadInt(f, &type_));
+            switch (type_) {
+                case 0:
+                    goto RETURN;
+                case 3:
+                    if (next_ == nullptr) {
+                        errorLog(aFunCoreLogger, "Code read all error");
+                        return false;
+                    }
+                    next_ = next_->father;
+                    break;
+                default: {
+                    Code *ret;
+                    if (next_ == nullptr && father_ != nullptr)
+                        ret = father_->read_v1(f, debug, type_, true);
+                    else if (next_ != nullptr)
+                        ret = next_->read_v1(f, debug, type_, false);
+                    else {
+                        errorLog(aFunCoreLogger, "Code read all error");
+                        return false;
+                    }
+
+                    if (ret == nullptr) {
+                        errorLog(aFunCoreLogger, "Code read error");
+                        return false;
+                    } else if (type_ == code_block) {
+                        next_ = nullptr;
+                        father_ = ret;
+                    } else {
+                        next_ = ret;
+                        father_ = nullptr;
+                    }
+                    break;
                 }
-                break;
             }
         }
-    }
 RETURN:
-    return true;
-}
+        return true;
+    }
 
 #undef Done
 #define Done(write) do{if(!(write)){return nullptr;}}while(0)
@@ -305,130 +305,130 @@ RETURN:
  * @param to_son 若位true则拼接到son, 否则拼接到next
  * @return
  */
-Code *Code::read_v1(FILE *f, bool debug, int8_t read_type, bool to_son) {
-    Code *ret;
-    switch (read_type) {
-        case code_element: {
-            int8_t prefix_ = NUL;
-            std::string element_;
-            Done(byteReadInt(f, &prefix_));
-            Done(byteReadStr(f, element_));
-            ret = Code::create(element_, 0, "", char(prefix_));
-            break;
+    Code *Code::read_v1(FILE *f, bool debug, int8_t read_type, bool to_son){
+        Code *ret;
+        switch (read_type) {
+            case code_element: {
+                int8_t prefix_ = aFuntool::NUL;
+                std::string element_;
+                Done(aFuntool::byteReadInt(f, &prefix_));
+                Done(aFuntool::byteReadStr(f, element_));
+                ret = Code::create(element_, 0, "", char(prefix_));
+                break;
+            }
+            case 4:
+            case code_block: {
+                int8_t prefix_ = aFuntool::NUL;
+                int8_t block_type = aFuntool::NUL;
+                Done(aFuntool::byteReadInt(f, &prefix_));
+                Done(aFuntool::byteReadInt(f, &block_type));
+                ret = Code::create(BlockType(block_type), nullptr, 0, "", char(prefix_));
+                break;
+            }
+            default:
+                errorLog(aFunCoreLogger, "Read code with error type.");
+                return nullptr;
         }
-        case 4:
-        case code_block: {
-            int8_t prefix_ = NUL;
-            int8_t block_type = NUL;
-            Done(byteReadInt(f, &prefix_));
-            Done(byteReadInt(f, &block_type));
-            ret = Code::create(BlockType(block_type), nullptr, 0, "", char(prefix_));
-            break;
+
+        if (debug) {
+            int16_t line_ = aFuntool::NUL;
+            char *file_ = nullptr;
+            Done(aFuntool::byteReadInt(f, &line_));
+            Done(aFuntool::byteReadStr(f, file_));
+            ret->line = line;
+            if (strlen(file) != 0)
+                ret->file = aFuntool::strCopy(file);
         }
-        default:
-            errorLog(aFunCoreLogger, "Read code with error type.");
-            return nullptr;
-    }
 
-    if (debug) {
-        int16_t line_ = NUL;
-        char *file_ = nullptr;
-        Done(byteReadInt(f, &line_));
-        Done(byteReadStr(f, file_));
-        ret->line = line;
-        if (strlen(file) != 0)
-            ret->file = strCopy(file);
+        if (to_son) {
+            if (type != code_block || son != nullptr) {
+                errorLog(aFunCoreLogger, "Read son with error type.");
+                delete ret;
+                return nullptr;
+            }
+            ret->father = this;
+            son = ret;
+        } else
+            connect(ret);
+        return ret;
     }
 
-    if (to_son) {
-        if (type != code_block || son != nullptr) {
-            errorLog(aFunCoreLogger, "Read son with error type.");
-            delete ret;
-            return nullptr;
-        }
-        ret->father = this;
-        son = ret;
-    } else
-        connect(ret);
-    return ret;
-}
-
 #undef Done
 
 /**
  * 计算代码的MD5值(版本:1)
  * @return md5
  */
-std::string Code::getMD5_v1() const {
-    char md5str[MD5_STR_LEN + 1] {};
-    char md5_value[MD5_SIZE];
-    MD5_CTX *md5 = MD5Init();
-
-    char head[] = {(char)type, prefix, 'x', 'x', NUL};
-    if (prefix == NUL)
-        head[1] = '-';
-    if (type == code_block) {
-        head[2] = son == nullptr ? 'n' : 's';
-        head[3] = block_type;
-    }
-
-    MD5Update(md5, (unsigned char *)head, strlen((char *)head));
-    if (type == code_element)
-        MD5Update(md5, (unsigned char *)element, strlen((char *)element));
-    else if (type == code_block)
-        MD5Update(md5, (unsigned char *)"block", 5);
-    else
-        MD5Update(md5, (unsigned char *)"start", 5);
+    std::string Code::getMD5_v1() const{
+        char md5str[aFuntool::MD5_STR_LEN + 1]{};
+        char md5_value[aFuntool::MD5_SIZE];
+        aFuntool::MD5_CTX *md5 = aFuntool::MD5Init();
+
+        char head[] = {(char) type, prefix, 'x', 'x', aFuntool::NUL};
+        if (prefix == aFuntool::NUL)
+            head[1] = '-';
+        if (type == code_block) {
+            head[2] = son == nullptr ? 'n' : 's';
+            head[3] = block_type;
+        }
 
-    MD5Final(md5, (unsigned char *)md5_value);
-    for(int i = 0; i < MD5_SIZE; i++)
-        snprintf((char *)md5str + i * 2, 2 + 1, "%02x", md5_value[i]);
-    return md5str;
-}
+        MD5Update(md5, (unsigned char *) head, strlen((char *) head));
+        if (type == code_element)
+            MD5Update(md5, (unsigned char *) element, strlen((char *) element));
+        else if (type == code_block)
+            MD5Update(md5, (unsigned char *) "block", 5);
+        else
+            MD5Update(md5, (unsigned char *) "start", 5);
+
+        MD5Final(md5, (unsigned char *) md5_value);
+        for (int i = 0; i < aFuntool::MD5_SIZE; i++)
+            snprintf((char *) md5str + i * 2, 2 + 1, "%02x", md5_value[i]);
+        return md5str;
+    }
 
 /**
  * 计算代码(子、兄)的MD5值(版本:1)
  * @return md5
  */
-std::string Code::getMD5All_v1() const {
-    if (this->type != code_start) {
-        errorLog(aFunCoreLogger, "Code get md5 all did not with `start`");
-        return "";
-    }
+    std::string Code::getMD5All_v1() const{
+        if (this->type != code_start) {
+            errorLog(aFunCoreLogger, "Code get md5 all did not with `start`");
+            return "";
+        }
+
+        char md5str[aFuntool::MD5_STR_LEN + 1]{};
+        char md5_value[aFuntool::MD5_SIZE];
+        aFuntool::MD5_CTX *md5 = aFuntool::MD5Init();
 
-    char md5str[MD5_STR_LEN + 1] {};
-    char md5_value[MD5_SIZE];
-    MD5_CTX *md5 = MD5Init();
+        const Code *tmp = this;
+        while (tmp != nullptr) {
+            std::string code_md5 = tmp->getMD5_v1();
+            MD5Update(md5, (unsigned char *) code_md5.c_str(), code_md5.size());
 
-    const Code *tmp = this;
-    while (tmp != nullptr) {
-        std::string code_md5 = tmp->getMD5_v1();
-        MD5Update(md5, (unsigned char *)code_md5.c_str(), code_md5.size());
+            if (tmp->type == code_block && tmp->son != nullptr) {
+                tmp = tmp->son;
+                continue;
+            }
 
-        if (tmp->type == code_block && tmp->son != nullptr){
-            tmp = tmp->son;
-            continue;
+            if (tmp->next == nullptr) {
+                do {
+                    tmp = tmp->father;
+                } while (tmp != nullptr && tmp->next == nullptr);
+                if (tmp == nullptr)
+                    break;
+                tmp = tmp->next;
+            } else
+                tmp = tmp->next;
         }
 
-        if (tmp->next == nullptr) {
-            do {
-                tmp = tmp->father;
-            } while(tmp != nullptr && tmp->next == nullptr);
-            if (tmp == nullptr)
-                break;
-            tmp = tmp->next;
-        } else
-            tmp = tmp->next;
+        MD5Final(md5, (unsigned char *) md5_value);
+        for (int i = 0; i < aFuntool::MD5_SIZE; i++)
+            snprintf((char *) md5str + i * 2, 2 + 1, "%02x", md5_value[i]);
+        return md5str;
     }
 
-    MD5Final(md5, (unsigned char *)md5_value);
-    for(int i = 0; i < MD5_SIZE; i++)
-        snprintf((char *)md5str + i * 2, 2 + 1, "%02x", md5_value[i]);
-    return md5str;
-}
-
-static const std::string ByteCodeHead = "aFunByteCode";  // NOLINT
-static const int MaxByteCodeVersion = 1;  // 字节码版本号, 有别于 aFun 版本号
+    static const std::string ByteCodeHead = "aFunByteCode";  // NOLINT
+    static const int MaxByteCodeVersion = 1;  // 字节码版本号, 有别于 aFun 版本号
 
 #define Done(write) do{if(!(write)){goto RETURN_FALSE;}}while(0)
 
@@ -438,77 +438,78 @@ static const int MaxByteCodeVersion = 1;  // 字节码版本号, 有别于 aFun
  * @param debug
  * @return
  */
-bool Code::writeByteCode(ConstFilePath file_path, bool debug) const {
-    if (this->type != code_start) {
-        errorLog(aFunCoreLogger, "ByteCode write all did not with `start`");
-        return false;
-    }
+    bool Code::writeByteCode(aFuntool::ConstFilePath file_path, bool debug) const{
+        if (this->type != code_start) {
+            errorLog(aFunCoreLogger, "ByteCode write all did not with `start`");
+            return false;
+        }
 
-    FILE *f = fileOpen(file_path, "wb");
-    if (f == nullptr) {
-        warningLog(aFunCoreLogger, "Write ByteCode create file error.");
-        return false;
-    }
+        FILE *f = aFuntool::fileOpen(file_path, "wb");
+        if (f == nullptr) {
+            warningLog(aFunCoreLogger, "Write ByteCode create file error.");
+            return false;
+        }
 
-    Done(byteWriteStr(f, ByteCodeHead));
-    Done(byteWriteInt(f, int16_t(MaxByteCodeVersion)));
-    Done(byteWriteStr(f, getMD5All_v1()));
-    Done(byteWriteInt(f, int8_t(debug)));
-    Done(writeAll_v1(f, debug));
-    fileClose(f);
-    return true;
+        Done(aFuntool::byteWriteStr(f, ByteCodeHead));
+        Done(aFuntool::byteWriteInt(f, int16_t(MaxByteCodeVersion)));
+        Done(aFuntool::byteWriteStr(f, getMD5All_v1()));
+        Done(aFuntool::byteWriteInt(f, int8_t(debug)));
+        Done(writeAll_v1(f, debug));
+        aFuntool::fileClose(f);
+        return true;
 
 RETURN_FALSE:
-    fileClose(f);
-    return false;
-}
+        aFuntool::fileClose(f);
+        return false;
+    }
 
 /**
  * 读取字节码文件(版本: 自动识别)
  * @param file_path
  * @return
  */
-bool Code::readByteCode(ConstFilePath file_path){
-    if (this->type != code_start) {
-        errorLog(aFunCoreLogger, "ByteCode read all did not with `start`");
-        return false;
-    }
-
-    FILE *f = fileOpen(file_path, "rb");
-    if (f == nullptr) {
-        warningLog(aFunCoreLogger, "Read ByteCode read file error.");
-        return false;
-    }
+    bool Code::readByteCode(aFuntool::ConstFilePath file_path){
+        if (this->type != code_start) {
+            errorLog(aFunCoreLogger, "ByteCode read all did not with `start`");
+            return false;
+        }
 
-    std::string head;
-    Done(byteReadStr(f, head));
-    if (head != ByteCodeHead)
-        return false;
+        FILE *f = aFuntool::fileOpen(file_path, "rb");
+        if (f == nullptr) {
+            warningLog(aFunCoreLogger, "Read ByteCode read file error.");
+            return false;
+        }
 
-    int16_t version;
-    Done(byteReadInt(f, &version));
-    switch (version) {  // NOLINT 为拓展方便, 使用switch-case而不是if-else
-        case 1: {
-            std::string md5;
-            int8_t debug;
-            Done(byteReadStr(f, md5));
-            Done(byteReadInt(f, &debug));
-
-            Done(readAll_v1(f, debug));
-            std::string md5_ = getMD5All_v1();
-            if (md5_ != md5)
+        std::string head;
+        Done(aFuntool::byteReadStr(f, head));
+        if (head != ByteCodeHead)
+            return false;
+
+        int16_t version;
+        Done(aFuntool::byteReadInt(f, &version));
+        switch (version) {  // NOLINT 为拓展方便, 使用switch-case而不是if-else
+            case 1: {
+                std::string md5;
+                int8_t debug;
+                Done(aFuntool::byteReadStr(f, md5));
+                Done(aFuntool::byteReadInt(f, &debug));
+
+                Done(readAll_v1(f, debug));
+                std::string md5_ = getMD5All_v1();
+                if (md5_ != md5)
+                    goto RETURN_FALSE;
+                return true;
+            }
+            default:
                 goto RETURN_FALSE;
-            return true;
         }
-        default:
-            goto RETURN_FALSE;
-    }
-    fileClose(f);
-    return true;
+        aFuntool::fileClose(f);
+        return true;
 
 RETURN_FALSE:
-    fileClose(f);
-    return false;
-}
+        aFuntool::fileClose(f);
+        return false;
+    }
 
-#undef Done
+#undef Done
+}

+ 112 - 112
src/core/env-var.cpp

@@ -1,136 +1,136 @@
 #include "env-var.h"
-using namespace aFuncore;
-using namespace aFuntool;
+namespace aFuncore {
 
-/**
- * 创建环境变量
- */
-aFuncore::EnvVarSpace::EnvVarSpace() : count {0} {
+    /**
+     * 创建环境变量
+     */
+    EnvVarSpace::EnvVarSpace() : count{0}{
 
-}
+    }
 
-/**
- * 释放全部环境变量
- */
-aFuncore::EnvVarSpace::~EnvVarSpace() {
-    for (auto &i : var) {
-        for (EnvVar *tmp = i, *next; tmp != nullptr; tmp = next) {
-            next = tmp->next;
-            delete tmp;
+    /**
+     * 释放全部环境变量
+     */
+    EnvVarSpace::~EnvVarSpace(){
+        for (auto &i: var) {
+            for (EnvVar *tmp = i, *next; tmp != nullptr; tmp = next) {
+                next = tmp->next;
+                delete tmp;
+            }
         }
     }
-}
 
-/**
- * 获取环境变量文本
- * @param name 变量名
- * @param str 文本
- * @return 是否成功
- */
-bool EnvVarSpace::findString(const std::string &name, std::string &str) const{
-    size_t index = time33(name) % ENV_VAR_HASH_SIZE;
-    for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
-        if (name == tmp->name) {
-            str = tmp->str;
-            return true;
+    /**
+     * 获取环境变量文本
+     * @param name 变量名
+     * @param str 文本
+     * @return 是否成功
+     */
+    bool EnvVarSpace::findString(const std::string &name, std::string &str) const{
+        size_t index = aFuntool::time33(name) % ENV_VAR_HASH_SIZE;
+        for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
+            if (name == tmp->name) {
+                str = tmp->str;
+                return true;
+            }
         }
+        return false;
     }
-    return false;
-}
 
-/**
- * 获取环境变量数值
- * @param name 变量名
- * @param num 文本
- * @return 是否成功
- */
-bool EnvVarSpace::findNumber(const std::string &name, int32_t &num) const{
-    size_t index = time33(name) % ENV_VAR_HASH_SIZE;
-    for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
-        if (name == tmp->name) {
-            num = tmp->num;
-            return true;
+    /**
+     * 获取环境变量数值
+     * @param name 变量名
+     * @param num 文本
+     * @return 是否成功
+     */
+    bool EnvVarSpace::findNumber(const std::string &name, int32_t &num) const{
+        size_t index = aFuntool::time33(name) % ENV_VAR_HASH_SIZE;
+        for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
+            if (name == tmp->name) {
+                num = tmp->num;
+                return true;
+            }
         }
+        return false;
     }
-    return false;
-}
 
-/**
- * 设置环境变量文本
- * @param name 变量名
- * @param str 文本
- */
-void EnvVarSpace::setString(const std::string &name, const std::string &str){
-    size_t index = time33(name) % ENV_VAR_HASH_SIZE;
-    auto tmp = &var[index];
-    for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
-        if (name == (*tmp)->name) {
-            (*tmp)->str = str;
-            return;
+    /**
+     * 设置环境变量文本
+     * @param name 变量名
+     * @param str 文本
+     */
+    void EnvVarSpace::setString(const std::string &name, const std::string &str){
+        size_t index = aFuntool::time33(name) % ENV_VAR_HASH_SIZE;
+        auto tmp = &var[index];
+        for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
+            if (name == (*tmp)->name) {
+                (*tmp)->str = str;
+                return;
+            }
         }
-    }
 
-    (*tmp) = new EnvVar;
-    (*tmp)->name = name;
-    (*tmp)->str = str;
-}
+        (*tmp) = new EnvVar;
+        (*tmp)->name = name;
+        (*tmp)->str = str;
+    }
 
-/**
- * 设置环境变量数值
- * @param name 变量名
- * @param num 数值
- */
-void EnvVarSpace::setNumber(const std::string &name, int32_t num){
-    size_t index = time33(name) % ENV_VAR_HASH_SIZE;
-    auto tmp = &var[index];
-    for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
-        if (name == (*tmp)->name) {
-            (*tmp)->num = num;
-            return;
+    /**
+     * 设置环境变量数值
+     * @param name 变量名
+     * @param num 数值
+     */
+    void EnvVarSpace::setNumber(const std::string &name, int32_t num){
+        size_t index = aFuntool::time33(name) % ENV_VAR_HASH_SIZE;
+        auto tmp = &var[index];
+        for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
+            if (name == (*tmp)->name) {
+                (*tmp)->num = num;
+                return;
+            }
         }
-    }
 
-    (*tmp) = new EnvVar;
-    (*tmp)->name = name;
-    (*tmp)->num = num;
-}
+        (*tmp) = new EnvVar;
+        (*tmp)->name = name;
+        (*tmp)->num = num;
+    }
 
-/**
- * 设置环境变量文本
- * @param name 变量名
- * @param str 文本
- */
-void EnvVarSpace::addString(const std::string &name, const std::string &str){
-    size_t index = time33(name) % ENV_VAR_HASH_SIZE;
-    auto tmp = &var[index];
-    for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
-        if (name == (*tmp)->name) {
-            (*tmp)->str += str;
-            return;
+    /**
+     * 设置环境变量文本
+     * @param name 变量名
+     * @param str 文本
+     */
+    void EnvVarSpace::addString(const std::string &name, const std::string &str){
+        size_t index = aFuntool::time33(name) % ENV_VAR_HASH_SIZE;
+        auto tmp = &var[index];
+        for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
+            if (name == (*tmp)->name) {
+                (*tmp)->str += str;
+                return;
+            }
         }
-    }
 
-    (*tmp) = new EnvVar;
-    (*tmp)->name = name;
-    (*tmp)->str = str;
-}
+        (*tmp) = new EnvVar;
+        (*tmp)->name = name;
+        (*tmp)->str = str;
+    }
 
-/**
- * 设置环境变量数值
- * @param name 变量名
- * @param num 数值
- */
-void EnvVarSpace::addNumber(const std::string &name, int32_t num){
-    size_t index = time33(name) % ENV_VAR_HASH_SIZE;
-    auto tmp = &var[index];
-    for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
-        if (name == (*tmp)->name) {
-            (*tmp)->num += num;
-            return;
+    /**
+     * 设置环境变量数值
+     * @param name 变量名
+     * @param num 数值
+     */
+    void EnvVarSpace::addNumber(const std::string &name, int32_t num){
+        size_t index = aFuntool::time33(name) % ENV_VAR_HASH_SIZE;
+        auto tmp = &var[index];
+        for (NULL; *tmp != nullptr; tmp = &((*tmp)->next)) {
+            if (name == (*tmp)->name) {
+                (*tmp)->num += num;
+                return;
+            }
         }
-    }
 
-    (*tmp) = new EnvVar;
-    (*tmp)->name = name;
-    (*tmp)->num = num;
-}
+        (*tmp) = new EnvVar;
+        (*tmp)->name = name;
+        (*tmp)->num = num;
+    }
+}

+ 13 - 14
src/core/gc.cpp

@@ -1,18 +1,17 @@
 #include "gc.h"
-using namespace aFuncore;
-using namespace aFuntool;
 
-size_t GcList::add(GcObjectBase *obj){
-    queue.push(obj);
-    return queue.size();
-}
+namespace aFuncore {
+    size_t GcList::add(GcObjectBase *obj){
+        queue.push(obj);
+        return queue.size();
+    }
 
+    GcObjectBase *GcList::pop(){
+        if (queue.empty())
+            return nullptr;
 
-GcObjectBase *GcList::pop(){
-    if (queue.empty())
-        return nullptr;
-
-    GcObjectBase *ret = queue.front();
-    queue.pop();
-    return ret;
-}
+        GcObjectBase *ret = queue.front();
+        queue.pop();
+        return ret;
+    }
+}

+ 33 - 35
src/core/init.cpp

@@ -1,43 +1,41 @@
 #include <clocale>
 #include "init.h"
-using namespace aFuncore;
-using namespace aFuntool;
 
 namespace aFuncore {
     std::string log_path;
     std::string varlib_path;
     aFuntool::Logger *aFunCoreLogger;
-};
-
-/**
- * 初始化程序
- * @param info 初始化信息
- * @return 是否初始化成功
- */
-bool aFuncore::aFunCoreInit(aFuncore::InitInfo *info) {
-    if (info == nullptr)
-        return false;
-
-    getEndian();
-    if (setlocale(LC_ALL, "") == nullptr)
-        return false;
-    if (info->base_dir.empty())
-        return false;
-
-    log_path = info->base_dir + SEP + aFunLogDir + SEP;
-    varlib_path = info->base_dir + SEP + aFunVarLibDir + SEP;
-
-    std::string log = log_path + "aFunlang";
-    bool re = info->factor.initLogSystem(log, info->log_asyn);
-    if (re == 0)
-        return false;
-
-    static aFuntool::Logger logger {info->factor, "aFunlang-core", info->level};
-    aFuncore::aFunCoreLogger = &logger;
-
-    debugLog(aFunCoreLogger, "aFunCore log path: %s", log_path.c_str());
-    debugLog(aFunCoreLogger, "aFunCore var.lib path: %s", varlib_path.c_str());
-
-    debugLog(aFunCoreLogger, "aFunCore init success");
-    return true;
+
+    /**
+     * 初始化程序
+     * @param info 初始化信息
+     * @return 是否初始化成功
+     */
+    bool aFunCoreInit(InitInfo *info){
+        if (info == nullptr)
+            return false;
+
+        aFuntool::getEndian();
+        if (setlocale(LC_ALL, "") == nullptr)
+            return false;
+        if (info->base_dir.empty())
+            return false;
+
+        log_path = info->base_dir + aFuntool::SEP + aFunLogDir + aFuntool::SEP;
+        varlib_path = info->base_dir + aFuntool::SEP + aFunVarLibDir + aFuntool::SEP;
+
+        std::string log = log_path + "aFunlang";
+        bool re = info->factor.initLogSystem(log, info->log_asyn);
+        if (re == 0)
+            return false;
+
+        static aFuntool::Logger logger{info->factor, "aFunlang-core", info->level};
+        aFunCoreLogger = &logger;
+
+        debugLog(aFunCoreLogger, "aFunCore log path: %s", log_path.c_str());
+        debugLog(aFunCoreLogger, "aFunCore var.lib path: %s", varlib_path.c_str());
+
+        debugLog(aFunCoreLogger, "aFunCore init success");
+        return true;
+    }
 }

+ 164 - 164
src/core/inter.cpp

@@ -4,207 +4,207 @@
 #include "msg.h"
 #include "core-exception.h"
 
-using namespace aFuncore;
-using namespace aFuntool;
-
-Inter::Inter(Environment &env_, int argc, char **argv, ExitMode em)
-    : out{}, in{}, env{env_} {
-    status = inter_creat;
+namespace aFuncore {
+    Inter::Inter(Environment &env_, int argc, char **argv, ExitMode em)
+            : out{}, in{}, env{env_}{
+        status = inter_creat;
+
+        activation = nullptr;
+
+        env.envvar.setNumber("sys:gc-runtime", 2);
+        env.envvar.setString("sys:prefix", "''");  // 引用,顺序执行
+        env.envvar.setNumber("sys:exit-code", 0);
+        env.envvar.setNumber("sys:argc", argc);
+        env.envvar.setNumber("sys:error_std", 0);
+
+        for (int i = 0; i < argc; i++) {
+            char buf[20];
+            snprintf(buf, 10, "sys:arg%d", i);
+            env.envvar.setString(buf, argv[i]);
+        }
 
-    activation = nullptr;
+        result = nullptr;
 
-    env.envvar.setNumber("sys:gc-runtime", 2);
-    env.envvar.setString("sys:prefix", "''");  // 引用,顺序执行
-    env.envvar.setNumber("sys:exit-code", 0);
-    env.envvar.setNumber("sys:argc", argc);
-    env.envvar.setNumber("sys:error_std", 0);
+        exit_flat = ef_none;
+        exit_mode = em;
 
-    for (int i = 0; i < argc; i++) {
-        char buf[20];
-        snprintf(buf, 10, "sys:arg%d", i);
-        env.envvar.setString(buf, argv[i]);
+        status = inter_init;
+        env++;
     }
 
-    result = nullptr;
-
-    exit_flat = ef_none;
-    exit_mode = em;
+    Inter::Inter(const Inter &base_inter, ExitMode em)
+            : out{}, in{}, env{base_inter.env}{
+        status = inter_creat;
 
-    status = inter_init;
-    env++;
-}
+        activation = nullptr;
 
-Inter::Inter(const Inter &base_inter, ExitMode em)
-        : out{}, in{}, env{base_inter.env} {
-    status = inter_creat;
+        for (auto &i: base_inter.literal)
+            literal.push_back(i);
 
-    activation = nullptr;
+        result = nullptr;
+        exit_flat = ef_none;
+        exit_mode = em;
 
-    for(auto &i : base_inter.literal)
-        literal.push_back(i);
+        status = inter_normal;
+        env++;
+    }
 
-    result = nullptr;
-    exit_flat = ef_none;
-    exit_mode = em;
+    Inter::~Inter(){
+        env--;
+    }
 
-    status = inter_normal;
-    env++;
-}
+    /**
+     * 使能 (激活解释器)
+     */
+    void Inter::enable(){
+        if (status == inter_init) {
+            env.protect->setProtect(true);
+            status = inter_normal;
+        }
+    }
 
-Inter::~Inter(){
-    env--;
-}
+    /**
+     * 运行代码(直接运行activation)
+     * @return
+     */
+    bool Inter::runCode(){
+        while (activation != nullptr) {
+            Code *code = nullptr;
+            Activation::ActivationStatus as = activation->getCode(code);
+            switch (as) {
+                case Activation::as_end: {
+                    Activation *prev = activation->toPrev();
+                    delete activation;
+                    activation = prev;
+                    break;
+                }
+                case Activation::as_run:
+                    activation->runCode(code);
+                    break;
+                case Activation::as_end_run:
+                    activation->endRun();
+                    break;
+                default:
+                    errorLog(aFunCoreLogger, "Error activation status.");
+                    activation->getDownStream().pushMessage(
+                            new ErrorMessage("RuntimeError", "Error activation status.", activation));
+                    break;
+            }
 
-/**
- * 使能 (激活解释器)
- */
-void Inter::enable(){
-    if (status == inter_init) {
-        env.protect->setProtect(true);
-        status = inter_normal;
-    }
-}
-
-/**
- * 运行代码(直接运行activation)
- * @return
- */
-bool Inter::runCode(){
-    while (activation != nullptr) {
-        Code *code = nullptr;
-        Activation::ActivationStatus as = activation->getCode(code);
-        switch (as) {
-            case Activation::as_end: {
-                Activation *prev = activation->toPrev();
-                delete activation;
-                activation = prev;
-                break;
+            if (isExit()) {
+                while (activation != nullptr) {
+                    Activation *prev = activation->toPrev();
+                    delete activation;
+                    activation = prev;
+                }
+                return false;
             }
-            case Activation::as_run:
-                activation->runCode(code);
-                break;
-            case Activation::as_end_run:
-                activation->endRun();
-                break;
-            default:
-                errorLog(aFunCoreLogger, "Error activation status.");
-                activation->getDownStream().pushMessage(new ErrorMessage("RuntimeError", "Error activation status.", activation));
-                break;
         }
+        return true;
+    }
 
-        if (isExit()) {
-            while (activation != nullptr) {
-                Activation *prev = activation->toPrev();
-                delete activation;
-                activation = prev;
-            }
+    /**
+     * 运行代码
+     * @param code 代码
+     * @return
+     */
+    bool Inter::runCode(Code *code){
+        if (activation != nullptr) {
+            errorLog(aFunCoreLogger, "Run code with activation");
             return false;
         }
-    }
-    return true;
-}
-
-/**
- * 运行代码
- * @param code 代码
- * @return
- */
-bool Inter::runCode(Code *code){
-    if (activation != nullptr) {
-        errorLog(aFunCoreLogger, "Run code with activation");
-        return false;
+
+        new TopActivation(code, *this);
+        return runCode();
     }
 
-    new TopActivation(code, *this);
-    return runCode();
-}
-
-/**
- * 检查字面量是否匹配
- * @param element 字面量
- * @return
- */
-bool Inter::checkLiteral(const std::string &element) const {
-    if (literal.empty())
-        return false;
+    /**
+     * 检查字面量是否匹配
+     * @param element 字面量
+     * @return
+     */
+    bool Inter::checkLiteral(const std::string &element) const{
+        if (literal.empty())
+            return false;
 
-    for(auto &i : literal){
-        try {
-            if (i.rg.match(element) != 1)
+        for (auto &i: literal) {
+            try {
+                if (i.rg.match(element) != 1)
+                    continue;
+                return true;
+            } catch (aFuntool::RegexException &e) {
                 continue;
-            return true;
-        } catch (RegexException &e) {
-            continue;
+            }
         }
-    }
-    return false;
-}
-
-/**
- * 检查字面量正则匹配
- * @param element 字面量
- * @param literaler 函数
- * @param in_protect 是否保护空间
- * @return
- */
-bool Inter::checkLiteral(const std::string &element, std::string &literaler, bool &in_protect) const {
-    if (literal.empty())
         return false;
+    }
 
-    for(auto &i : literal){
-        try {
-            if (i.rg.match(element) != 1)
+    /**
+     * 检查字面量正则匹配
+     * @param element 字面量
+     * @param literaler 函数
+     * @param in_protect 是否保护空间
+     * @return
+     */
+    bool Inter::checkLiteral(const std::string &element, std::string &literaler, bool &in_protect) const{
+        if (literal.empty())
+            return false;
+
+        for (auto &i: literal) {
+            try {
+                if (i.rg.match(element) != 1)
+                    continue;
+                literaler = i.literaler;
+                in_protect = i.in_protect;
+                return true;
+            } catch (aFuntool::RegexException &e) {
                 continue;
-            literaler = i.literaler;
-            in_protect = i.in_protect;
-            return true;
-        } catch (RegexException &e) {
-            continue;
+            }
         }
+        return false;
     }
-    return false;
-}
 
-bool Inter::pushLiteral(const std::string &pattern, const std::string &literaler, bool in_protect){
-    try {
-        literal.push_front({Regex(pattern), pattern, literaler, in_protect});
-    } catch (RegexException &e) {
-        return false;
+    bool Inter::pushLiteral(const std::string &pattern, const std::string &literaler, bool in_protect){
+        try {
+            literal.push_front({aFuntool::Regex(pattern), pattern, literaler, in_protect});
+        } catch (aFuntool::RegexException &e) {
+            return false;
+        }
+        return true;
     }
-    return true;
-}
 
-Environment::Environment() : envvar{} {
-    obj = nullptr;
-    var = nullptr;
-    varspace = nullptr;
+    Environment::Environment() : envvar{}{
+        obj = nullptr;
+        var = nullptr;
+        varspace = nullptr;
 
-    protect = new ProtectVarSpace(*this);  // 放到最后
-    global = new VarSpace(*this);  // 放到最后
-    global_varlist = new VarList(protect);
-    global_varlist->push(global);
+        protect = new ProtectVarSpace(*this);  // 放到最后
+        global = new VarSpace(*this);  // 放到最后
+        global_varlist = new VarList(protect);
+        global_varlist->push(global);
 
-    reference = 0;
-}
+        reference = 0;
+    }
 
-Environment::~Environment() noexcept(false) {
-    if (reference != 0)
-        throw EnvironmentDestructException();
+    Environment::~Environment() noexcept(false){
+        if (reference != 0)
+            throw EnvironmentDestructException();
 
-    if (global_varlist == nullptr)
-        return;
+        if (global_varlist == nullptr)
+            return;
 
-    delete global_varlist;
+        delete global_varlist;
 
-    Object::destruct(obj);
-    Var::destruct(var);
-    VarSpace::destruct(varspace);
+        Object::destruct(obj);
+        Var::destruct(var);
+        VarSpace::destruct(varspace);
 
-    obj = nullptr;
-    var = nullptr;
-    varspace = nullptr;
+        obj = nullptr;
+        var = nullptr;
+        varspace = nullptr;
 
-    protect = nullptr;  // 放到最后
-    global = nullptr;  // 放到最后
-    global_varlist = nullptr;
+        protect = nullptr;  // 放到最后
+        global = nullptr;  // 放到最后
+        global_varlist = nullptr;
+    }
 }

+ 112 - 113
src/core/msg.cpp

@@ -3,139 +3,138 @@
 #include "inter.h"
 #include "env-var.h"
 
-using namespace aFuncore;
-using namespace aFuntool;
-
-NormalMessage::~NormalMessage(){
-    this->obj = nullptr;
-}
+namespace aFuncore {
+    NormalMessage::~NormalMessage(){
+        this->obj = nullptr;
+    }
 
-void NormalMessage::topProgress(){
-    printf_stdout(0, "NORMAL: %p\n", obj);
-}
+    void NormalMessage::topProgress(){
+        aFuntool::printf_stdout(0, "NORMAL: %p\n", obj);
+    }
 
-ErrorMessage::ErrorMessage(const std::string &error_type_, const std::string &error_info_, Activation *activation)
-        : TopMessage("ERROR"), error_type{error_type_}, error_info{error_info_}, inter{activation->inter} {
-    for (NULL; activation != nullptr; activation = activation->toPrev()) {
-        if (activation->getFileLine() != 0)
-            trackback.push_front({activation->getFilePath(), activation->getFileLine()});
+    ErrorMessage::ErrorMessage(const std::string &error_type_, const std::string &error_info_, Activation *activation)
+            : TopMessage("ERROR"), error_type{error_type_}, error_info{error_info_}, inter{activation->inter}{
+        for (NULL; activation != nullptr; activation = activation->toPrev()) {
+            if (activation->getFileLine() != 0)
+                trackback.push_front({activation->getFilePath(), activation->getFileLine()});
+        }
     }
-}
 
-void ErrorMessage::topProgress(){
-    int32_t error_std = 0;
-    inter.getEnvVarSpace().findNumber("sys:error_std", error_std);
-    if (error_std == 0) {
-        printf_stderr(0, "Error TrackBack\n");
-        for (auto & begin : trackback)
-            printf_stderr(0, "  File \"%s\", line %d\n", begin.path.c_str(), begin.line);
-        printf_stderr(0, "%s: %s\n", error_type.c_str(), error_info.c_str());
-    } else {
-        printf_stdout(0, "Error TrackBack\n");
-        for (auto & begin : trackback)
-            printf_stdout(0, "  File \"%s\", line %d\n", begin.path.c_str(), begin.line);
-        printf_stdout(0, "%s: %s\n", error_type.c_str(), error_info.c_str());
+    void ErrorMessage::topProgress(){
+        int32_t error_std = 0;
+        inter.getEnvVarSpace().findNumber("sys:error_std", error_std);
+        if (error_std == 0) {
+            aFuntool::printf_stderr(0, "Error TrackBack\n");
+            for (auto &begin: trackback)
+                aFuntool::printf_stderr(0, "  File \"%s\", line %d\n", begin.path.c_str(), begin.line);
+            aFuntool::printf_stderr(0, "%s: %s\n", error_type.c_str(), error_info.c_str());
+        } else {
+            aFuntool::printf_stdout(0, "Error TrackBack\n");
+            for (auto &begin: trackback)
+                aFuntool::printf_stdout(0, "  File \"%s\", line %d\n", begin.path.c_str(), begin.line);
+            aFuntool::printf_stdout(0, "%s: %s\n", error_type.c_str(), error_info.c_str());
+        }
     }
-}
 
-MessageStream::MessageStream(){
-    stream = nullptr;
-}
+    MessageStream::MessageStream(){
+        stream = nullptr;
+    }
 
-MessageStream::~MessageStream(){
-    for (Message *msg = stream, *tmp; msg != nullptr; msg = tmp) {
-        tmp = msg->next;
-        delete msg;
+    MessageStream::~MessageStream(){
+        for (Message *msg = stream, *tmp; msg != nullptr; msg = tmp) {
+            tmp = msg->next;
+            delete msg;
+        }
     }
-}
 
-/**
- * 压入 Message
- * @param msg Message
- */
-void MessageStream::pushMessage(Message *msg){
-    msg->next = stream;
-    stream = msg;
-}
+    /**
+     * 压入 Message
+     * @param msg Message
+     */
+    void MessageStream::pushMessage(Message *msg){
+        msg->next = stream;
+        stream = msg;
+    }
 
-/**
- * 获取 Message
- * @param type 类型
- * @return Message
- */
-Message *MessageStream::_getMessage(const std::string &type) const{
-    for (Message *msg = stream; msg != nullptr; msg = msg->next) {
-        if (msg->type == type)
-            return msg;
+    /**
+     * 获取 Message
+     * @param type 类型
+     * @return Message
+     */
+    Message *MessageStream::_getMessage(const std::string &type) const{
+        for (Message *msg = stream; msg != nullptr; msg = msg->next) {
+            if (msg->type == type)
+                return msg;
+        }
+        return nullptr;
     }
-    return nullptr;
-}
 
-/**
- * 弹出Message (使Message脱离数据流)
- * @param type 类型
- * @return Message
- */
-Message *MessageStream::popMessage(const std::string &type) {
-    for (Message **msg = &stream; *msg != nullptr; msg = &((*msg)->next)) {
-        if ((*msg)->type == type) {
-            Message *ret = *msg;
-            *msg = ret->next;
-            return ret;
+    /**
+     * 弹出Message (使Message脱离数据流)
+     * @param type 类型
+     * @return Message
+     */
+    Message *MessageStream::popMessage(const std::string &type){
+        for (Message **msg = &stream; *msg != nullptr; msg = &((*msg)->next)) {
+            if ((*msg)->type == type) {
+                Message *ret = *msg;
+                *msg = ret->next;
+                return ret;
+            }
         }
+        return nullptr;
     }
-    return nullptr;
-}
 
-UpMessage::UpMessage(const UpMessage *old) : MessageStream() {
-    if (old != nullptr)
-        this->old = old->stream;
-    else
-        this->old = nullptr;
-    this->stream = this->old;
-}
+    UpMessage::UpMessage(const UpMessage *old) : MessageStream(){
+        if (old != nullptr)
+            this->old = old->stream;
+        else
+            this->old = nullptr;
+        this->stream = this->old;
+    }
 
-UpMessage::~UpMessage(){
-    if (old != nullptr) {
-        for (Message **msg = &stream; *msg != nullptr; msg = &((*msg)->next)) {
-            if (*msg == old) {
-                *msg = nullptr;
-                break;
+    UpMessage::~UpMessage(){
+        if (old != nullptr) {
+            for (Message **msg = &stream; *msg != nullptr; msg = &((*msg)->next)) {
+                if (*msg == old) {
+                    *msg = nullptr;
+                    break;
+                }
             }
         }
     }
-}
 
-/**
- * 弹出Message (使Message脱离数据流)
- * 注意: 不会弹出继承的Message
- * @param type 类型
- * @return Message
- */
-Message *UpMessage::popMessage(const std::string &type){
-    for (Message **msg = &stream; *msg != nullptr; msg = &((*msg)->next)) {
-        if ((*msg) == old)
-            break;
-        if ((*msg)->type == type) {
-            Message *ret = *msg;
-            *msg = ret->next;
-            return ret;
+    /**
+     * 弹出Message (使Message脱离数据流)
+     * 注意: 不会弹出继承的Message
+     * @param type 类型
+     * @return Message
+     */
+    Message *UpMessage::popMessage(const std::string &type){
+        for (Message **msg = &stream; *msg != nullptr; msg = &((*msg)->next)) {
+            if ((*msg) == old)
+                break;
+            if ((*msg)->type == type) {
+                Message *ret = *msg;
+                *msg = ret->next;
+                return ret;
+            }
         }
+        return nullptr;
     }
-    return nullptr;
-}
 
-/**
- * 拼接数据流
- * @param msg
- */
-void DownMessage::joinMsg(DownMessage &msg){
-    Message *m = stream;
-    if (m == nullptr)
-        return;
-    while (m->next != nullptr)
-        m = m->next;
-    m->next = msg.stream;
-    msg.stream = m;
-    stream = nullptr;
-}
+    /**
+     * 拼接数据流
+     * @param msg
+     */
+    void DownMessage::joinMsg(DownMessage &msg){
+        Message *m = stream;
+        if (m == nullptr)
+            return;
+        while (m->next != nullptr)
+            m = m->next;
+        m->next = msg.stream;
+        msg.stream = m;
+        stream = nullptr;
+    }
+}

+ 9 - 10
src/core/value.cpp

@@ -1,15 +1,14 @@
 #include "value.h"
 #include "inter.h"
 
-using namespace aFuncore;
-using namespace aFuntool;
+namespace aFuncore {
+    Object::Object(std::string type_, Inter &inter)
+            : type{std::move(type_)}, env{inter.getEnvironment()}{
+        this->addObject(env.obj);
+    }
 
-aFuncore::Object::Object(std::string type_, Inter &inter)
-        : type{std::move(type_)}, env{inter.getEnvironment()} {
-    this->addObject(env.obj);
-}
-
-aFuncore::Object::Object(std::string type_, Environment &env_)
-        : type{std::move(type_)}, env{env_} {
-    this->addObject(env.obj);
+    Object::Object(std::string type_, Environment &env_)
+            : type{std::move(type_)}, env{env_}{
+        this->addObject(env.obj);
+    }
 }

+ 243 - 244
src/core/var.cpp

@@ -1,254 +1,253 @@
 #include "var.h"
 #include "inter.h"
 
-using namespace aFuncore;
-using namespace aFuntool;
-
-
-aFuncore::Var::Var(Object *data_, Inter &inter) : data{data_}, env{inter.getEnvironment()} {
-    addObject(env.var);
-}
-
-aFuncore::Var::Var(Object *data_, Environment &env_) : data{data_}, env{env_} {
-    addObject(env.var);
-}
-
-aFuncore::VarSpace::VarSpace(Inter &inter) : count{0}, var{}, env{inter.getEnvironment()} {
-    addObject(env.varspace);
-}
-
-aFuncore::VarSpace::VarSpace(Environment &env_) : count{0}, var{}, env{env_} {
-    addObject(env.varspace);
-}
-
-/**
- * 访问指定变量
- * @param name 变量名
- * @return
- */
-Var *aFuncore::VarSpace::findVar(const std::string &name){
-    size_t index = time33(name) % VAR_HASH_SIZE;
-    for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
-        if (tmp->name == name)
-            return tmp->var;
-    }
-    return nullptr;
-}
-
-/**
- * 定义变量
- * @param name 变量名
- * @param data 变量(Object)
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::VarSpace::defineVar(const std::string &name, Object *data){
-    size_t index = time33(name) % VAR_HASH_SIZE;
-    auto tmp = &var[index];
-    for (NULL; *tmp != nullptr; tmp = &(*tmp)->next) {
-        if ((*tmp)->name == name)
-            return vof_redefine_var;
-    }
-    (*tmp) = new VarCup;
-    (*tmp)->name = name;
-    (*tmp)->var = new Var(data, env);
-    count++;
-    return vof_success;
-}
-
-/**
- * 定义变量
- * @param name 变量名
- * @param data 变量(Var)
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::VarSpace::defineVar(const std::string &name, Var *data){
-    size_t index = time33(name) % VAR_HASH_SIZE;
-    auto tmp = &var[index];
-    for (NULL; *tmp != nullptr; tmp = &(*tmp)->next) {
-        if ((*tmp)->name == name)
-            return vof_redefine_var;
-    }
-    (*tmp) = new VarCup;
-    (*tmp)->name = name;
-    (*tmp)->var = data;
-    count++;
-    return vof_success;
-}
-
-/**
- * 设定变量的值
- * @param name 变量名
- * @param data 变量
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::VarSpace::setVar(const std::string &name, Object *data){
-    size_t index = time33(name) % VAR_HASH_SIZE;
-    for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
-        if (tmp->name == name) {
-            tmp->var->setData(data);
-            return vof_success;
+namespace aFuncore {
+    Var::Var(Object *data_, Inter &inter) : data{data_}, env{inter.getEnvironment()}{
+        addObject(env.var);
+    }
+    
+    Var::Var(Object *data_, Environment &env_) : data{data_}, env{env_}{
+        addObject(env.var);
+    }
+    
+    VarSpace::VarSpace(Inter &inter) : count{0}, var{}, env{inter.getEnvironment()}{
+        addObject(env.varspace);
+    }
+    
+    VarSpace::VarSpace(Environment &env_) : count{0}, var{}, env{env_}{
+        addObject(env.varspace);
+    }
+    
+    /**
+     * 访问指定变量
+     * @param name 变量名
+     * @return
+     */
+    Var *VarSpace::findVar(const std::string &name){
+        size_t index = aFuntool::time33(name) % VAR_HASH_SIZE;
+        for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
+            if (tmp->name == name)
+                return tmp->var;
         }
+        return nullptr;
     }
-    return vof_not_var;
-}
-
-/**
- * 删除变量
- * @param name 变量名
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::VarSpace::delVar(const std::string &name){
-    size_t index = time33(name) % VAR_HASH_SIZE;
-    for (auto tmp = var[index]; tmp != nullptr && tmp->next != nullptr; tmp = tmp->next) {
-        if (tmp->next->name == name) {
-            auto del = tmp->next;
-            tmp->next = del->next;
-            delete del;  // 删除 VarCup
-            count--;
-            return vof_success;
+    
+    /**
+     * 定义变量
+     * @param name 变量名
+     * @param data 变量(Object)
+     * @return
+     */
+    VarSpace::VarOperationFlat VarSpace::defineVar(const std::string &name, Object *data){
+        size_t index = aFuntool::time33(name) % VAR_HASH_SIZE;
+        auto tmp = &var[index];
+        for (NULL; *tmp != nullptr; tmp = &(*tmp)->next) {
+            if ((*tmp)->name == name)
+                return vof_redefine_var;
         }
+        (*tmp) = new VarCup;
+        (*tmp)->name = name;
+        (*tmp)->var = new Var(data, env);
+        count++;
+        return vof_success;
     }
-    return vof_not_var;
-}
-
-aFuncore::VarSpace::~VarSpace(){
-    for (auto &cup : var) {
-        for (VarCup *next; cup != nullptr; cup = next) {
-            next = cup->next;
-            delete cup;
+    
+    /**
+     * 定义变量
+     * @param name 变量名
+     * @param data 变量(Var)
+     * @return
+     */
+    VarSpace::VarOperationFlat VarSpace::defineVar(const std::string &name, Var *data){
+        size_t index = aFuntool::time33(name) % VAR_HASH_SIZE;
+        auto tmp = &var[index];
+        for (NULL; *tmp != nullptr; tmp = &(*tmp)->next) {
+            if ((*tmp)->name == name)
+                return vof_redefine_var;
         }
+        (*tmp) = new VarCup;
+        (*tmp)->name = name;
+        (*tmp)->var = data;
+        count++;
+        return vof_success;
+    }
+    
+    /**
+     * 设定变量的值
+     * @param name 变量名
+     * @param data 变量
+     * @return
+     */
+    VarSpace::VarOperationFlat VarSpace::setVar(const std::string &name, Object *data){
+        size_t index = aFuntool::time33(name) % VAR_HASH_SIZE;
+        for (auto tmp = var[index]; tmp != nullptr; tmp = tmp->next) {
+            if (tmp->name == name) {
+                tmp->var->setData(data);
+                return vof_success;
+            }
+        }
+        return vof_not_var;
+    }
+    
+    /**
+     * 删除变量
+     * @param name 变量名
+     * @return
+     */
+    VarSpace::VarOperationFlat VarSpace::delVar(const std::string &name){
+        size_t index = aFuntool::time33(name) % VAR_HASH_SIZE;
+        for (auto tmp = var[index]; tmp != nullptr && tmp->next != nullptr; tmp = tmp->next) {
+            if (tmp->next->name == name) {
+                auto del = tmp->next;
+                tmp->next = del->next;
+                delete del;  // 删除 VarCup
+                count--;
+                return vof_success;
+            }
+        }
+        return vof_not_var;
+    }
+    
+    VarSpace::~VarSpace(){
+        for (auto &cup: var) {
+            for (VarCup *next; cup != nullptr; cup = next) {
+                next = cup->next;
+                delete cup;
+            }
+        }
+    }
+    
+    VarList::VarList(VarList *varlist){
+        for (auto &t: varlist->varspace)
+            this->varspace.push_back(t);
+    }
+    
+    /**
+     * 定义变量
+     * 若启用保护且变量名存在,则返回错误redefine
+     * 若启用保护则返回错误fail
+     * @param name 变量名
+     * @param data 变量(Object)
+     * @return
+     */
+    VarSpace::VarOperationFlat ProtectVarSpace::defineVar(const std::string &name, Object *data){
+        return VarSpace::defineVar(name, data);
+    }
+    
+    /**
+     * 定义变量
+     * 若启用保护且变量名存在,则返回错误redefine
+     * 若启用保护则返回错误fail
+     * @param name 变量名
+     * @param data 变量(Var)
+     * @return
+     */
+    VarSpace::VarOperationFlat ProtectVarSpace::defineVar(const std::string &name, Var *data){
+        return VarSpace::defineVar(name, data);
+    }
+    
+    /**
+     * 设定变量的值
+     * 若启用保护且变量名存在,则返回错误fail
+     * 若启用保护则返回错误 not_var
+     * @param name 变量名
+     * @param data 变量(Var)
+     * @return
+     */
+    VarSpace::VarOperationFlat ProtectVarSpace::setVar(const std::string &name, Object *data){
+        if (is_protect)
+            return findVar(name) ? vof_fail : vof_not_var;
+        return VarSpace::setVar(name, data);
+    }
+    
+    /**
+     * 删除变量
+     * 若启用保护且变量名存在,则返回错误fail
+     * 若启用保护则返回错误 not_var
+     * @param name 变量名
+     * @param data 变量(Var)
+     * @return
+     */
+    VarSpace::VarOperationFlat ProtectVarSpace::delVar(const std::string &name){
+        if (is_protect)
+            return findVar(name) ? vof_fail : vof_not_var;
+        return VarSpace::delVar(name);
+    }
+    
+    /**
+     * 访问变量
+     * @param name 变量名
+     * @return
+     */
+    Var *VarList::findVar(const std::string &name){
+        Var *ret = nullptr;
+        for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == nullptr; tmp++)
+            ret = (*tmp)->findVar(name);
+        return ret;
+    }
+    
+    /**
+     * 定义变量
+     * 若定义出现redefine则退出报错
+     * 若出现fail则跳到下一个变量空间尝试定义
+     * @param name 变量名
+     * @param data 变量(Object)
+     * @return
+     */
+    bool VarList::defineVar(const std::string &name, Object *data){
+        VarSpace::VarOperationFlat ret = VarSpace::vof_fail;
+        for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_fail; tmp++)
+            ret = (*tmp)->defineVar(name, data);
+        return ret == VarSpace::vof_success;
+    }
+    
+    /**
+     * 定义变量
+     * 若定义出现redefine则退出报错
+     * 若出现fail则跳到下一个变量空间尝试定义
+     * @param name 变量名
+     * @param data 变量(Var)
+     * @return
+     */
+    bool VarList::defineVar(const std::string &name, Var *data){
+        VarSpace::VarOperationFlat ret = VarSpace::vof_fail;
+        for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_fail; tmp++)
+            ret = (*tmp)->defineVar(name, data);
+        return ret == VarSpace::vof_success;
+    }
+    
+    /**
+     * 设置变量的值
+     * 若not_var则跳到下一个变量空间
+     * 若fail则结束
+     * @param name 变量名
+     * @param data 数据
+     * @return
+     */
+    bool VarList::setVar(const std::string &name, Object *data){
+        VarSpace::VarOperationFlat ret = VarSpace::vof_not_var;
+        for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_not_var; tmp++)
+            ret = (*tmp)->setVar(name, data);
+        return ret == VarSpace::vof_success;
+    }
+    
+    /**
+     * 删除变量
+     * 若not_var则跳到下一个变量空间
+     * 若fail则结束
+     * @param name
+     * @return
+     */
+    bool VarList::delVar(const std::string &name){
+        VarSpace::VarOperationFlat ret = VarSpace::vof_not_var;
+        for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_not_var; tmp++)
+            ret = (*tmp)->delVar(name);
+        return ret == VarSpace::vof_success;
+    }
+    
+    void VarList::connect(VarList *varlist){
+        for (auto &t: varlist->varspace)
+            this->varspace.push_back(t);
     }
-}
-
-aFuncore::VarList::VarList(VarList *varlist) {
-    for (auto &t : varlist->varspace)
-        this->varspace.push_back(t);
-}
-
-/**
- * 定义变量
- * 若启用保护且变量名存在,则返回错误redefine
- * 若启用保护则返回错误fail
- * @param name 变量名
- * @param data 变量(Object)
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::ProtectVarSpace::defineVar(const std::string &name, Object *data){
-    return VarSpace::defineVar(name, data);
-}
-
-/**
- * 定义变量
- * 若启用保护且变量名存在,则返回错误redefine
- * 若启用保护则返回错误fail
- * @param name 变量名
- * @param data 变量(Var)
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::ProtectVarSpace::defineVar(const std::string &name, Var *data){
-    return VarSpace::defineVar(name, data);
-}
-
-/**
- * 设定变量的值
- * 若启用保护且变量名存在,则返回错误fail
- * 若启用保护则返回错误 not_var
- * @param name 变量名
- * @param data 变量(Var)
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::ProtectVarSpace::setVar(const std::string &name, Object *data){
-    if (is_protect)
-        return findVar(name) ? vof_fail : vof_not_var;
-    return VarSpace::setVar(name, data);
-}
-
-/**
- * 删除变量
- * 若启用保护且变量名存在,则返回错误fail
- * 若启用保护则返回错误 not_var
- * @param name 变量名
- * @param data 变量(Var)
- * @return
- */
-VarSpace::VarOperationFlat aFuncore::ProtectVarSpace::delVar(const std::string &name){
-    if (is_protect)
-        return findVar(name) ? vof_fail : vof_not_var;
-    return VarSpace::delVar(name);
-}
-
-/**
- * 访问变量
- * @param name 变量名
- * @return
- */
-Var *aFuncore::VarList::findVar(const std::string &name){
-    Var *ret = nullptr;
-    for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == nullptr; tmp++)
-        ret = (*tmp)->findVar(name);
-    return ret;
-}
-
-/**
- * 定义变量
- * 若定义出现redefine则退出报错
- * 若出现fail则跳到下一个变量空间尝试定义
- * @param name 变量名
- * @param data 变量(Object)
- * @return
- */
-bool aFuncore::VarList::defineVar(const std::string &name, Object *data){
-    VarSpace::VarOperationFlat ret = VarSpace::vof_fail;
-    for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_fail; tmp++)
-        ret = (*tmp)->defineVar(name, data);
-    return ret == VarSpace::vof_success;
-}
-
-/**
- * 定义变量
- * 若定义出现redefine则退出报错
- * 若出现fail则跳到下一个变量空间尝试定义
- * @param name 变量名
- * @param data 变量(Var)
- * @return
- */
-bool aFuncore::VarList::defineVar(const std::string &name, Var *data){
-    VarSpace::VarOperationFlat ret = VarSpace::vof_fail;
-    for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_fail; tmp++)
-        ret = (*tmp)->defineVar(name, data);
-    return ret == VarSpace::vof_success;
-}
-
-/**
- * 设置变量的值
- * 若not_var则跳到下一个变量空间
- * 若fail则结束
- * @param name 变量名
- * @param data 数据
- * @return
- */
-bool aFuncore::VarList::setVar(const std::string &name, Object *data){
-    VarSpace::VarOperationFlat ret = VarSpace::vof_not_var;
-    for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_not_var; tmp++)
-        ret = (*tmp)->setVar(name, data);
-    return ret == VarSpace::vof_success;
-}
-
-/**
- * 删除变量
- * 若not_var则跳到下一个变量空间
- * 若fail则结束
- * @param name
- * @return
- */
-bool aFuncore::VarList::delVar(const std::string &name){
-    VarSpace::VarOperationFlat ret = VarSpace::vof_not_var;
-    for (auto tmp = varspace.begin(), end = varspace.end(); tmp != end && ret == VarSpace::vof_not_var; tmp++)
-        ret = (*tmp)->delVar(name);
-    return ret == VarSpace::vof_success;
-}
 
-void VarList::connect(VarList *varlist){
-    for (auto &t : varlist->varspace)
-        this->varspace.push_back(t);
-}
+}

+ 62 - 131
src/tool/byte.cpp

@@ -5,152 +5,83 @@
 #include "tool.h"
 #include "byte.h"
 
-using namespace aFuntool;
-
 namespace aFuntool {
     enum EndianType endian = little_endian;
     enum EndianType save_as = little_endian;  // 默认以小端序存储
-}
-
-/**
- * 获取机器字节序
- */
-void aFuntool::getEndian() {
-    union {
-        int16_t a;//元素a,占2个字节
-        int8_t b;//元素b,占1个字节,b在内存中的地址为a最低字节的地址
-    } test = {.a = 0x1234};
 
-    if (test.b == 0x34)
-        endian = little_endian;
-    else if (test.b == 0x12)
-        endian = big_endian;
-    else
-        abort();
-}
-
-/**
- * 写入一个整数
- * @tparam T 整数类型
- * @param file FILE 结构体
- * @param num 整数
- * @return
- */
-template <typename T>
-bool aFuntool::byteWriteInt(FILE *file, T num) {
-    if (endian != save_as) {
-        const size_t len = sizeof(T) / sizeof(uint8_t);  // NOLINT 允许 size(T) / size(T)
+    /**
+     * 获取机器字节序
+     */
+    void getEndian(){
         union {
-            T a;//元素a,占2个字节
-            uint8_t b[len];//元素b,占1个字节,b在内存中的地址为a最低字节的地址
-        } in {.a = num}, out {};
-
-        for (int i = 0; i < len; i++)
-            out.b[len - i] = in.b[i];  // 大小端序转换
-        num = out.a;
+            int16_t a;//元素a,占2个字节
+            int8_t b;//元素b,占1个字节,b在内存中的地址为a最低字节的地址
+        } test = {.a = 0x1234};
+
+        if (test.b == 0x34)
+            endian = little_endian;
+        else if (test.b == 0x12)
+            endian = big_endian;
+        else
+            abort();
     }
 
-    return fwrite(&num, sizeof(T), 1, file) == 1;
-}
-
-/**
- * 读取一个整数
- * @tparam T 整数类型
- * @param file FILE 结构体
- * @param num 整数
- * @return
- */
-template <typename T>
-bool aFuntool::byteReadInt(FILE *file, T *num) {
-    size_t re = fread(num, sizeof(T), 1, file);
-
-    if (endian != save_as) {
-        const size_t len = sizeof(T) / sizeof(uint8_t);  // NOLINT 允许 size(T) / size(T)
-        union {
-            T a;//元素a,占2个字节
-            uint8_t b[len];//元素b,占1个字节,b在内存中的地址为a最低字节的地址
-        } in {.a = *num}, out {};
-
-        for (int i = 0; i < len; i++)
-            out.b[len - i] = in.b[i];  // 大小端序转换
-        *num = out.a;
+    /**
+     * 写入一个C风格字符串
+     */
+    bool byteWriteStr(FILE *file, const char *str){
+        if (!byteWriteInt<uint16_t>(file, (uint16_t) strlen(str)))
+            return false;
+        return fwrite(str, sizeof(char), strlen(str), file) == strlen(str);
     }
 
-    return re == 1;
-}
-
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, int8_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, int16_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, int32_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, int64_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, uint8_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, uint16_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, uint32_t num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteWriteInt(FILE *file, uint64_t num);
-
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt<int8_t>(FILE *file, int8_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, int16_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, int32_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, int64_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, uint8_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, uint16_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, uint32_t *num);
-template AFUN_TOOL_EXPORT bool aFuntool::byteReadInt(FILE *file, uint64_t *num);
-
-/**
- * 写入一个C风格字符串
- */
-bool aFuntool::byteWriteStr(FILE *file, const char *str) {
-    if (!byteWriteInt<uint16_t>(file, (uint16_t)strlen(str)))
-        return false;
-    return fwrite(str, sizeof(char), strlen(str), file) == strlen(str);
-}
 
+    /**
+     * 写入一个C++风格字符串
+     */
+    bool byteWriteStr(FILE *file, const std::string &str){
+        size_t size = str.size();
+        if (!byteWriteInt<uint16_t>(file, (uint16_t) size))
+            return false;
+        return fwrite(str.c_str(), sizeof(char), size, file) == size;
+    }
 
-/**
- * 写入一个C++风格字符串
- */
-bool aFuntool::byteWriteStr(FILE *file, const std::string &str) {
-    size_t size = str.size();
-    if (!byteWriteInt<uint16_t>(file, (uint16_t)size))
-        return false;
-    return fwrite(str.c_str(), sizeof(char), size, file) == size;
-}
 
+    /**
+     * 读取一个C风格字符串
+     */
+    bool byteReadStr(FILE *file, char *&str){
+        uint16_t len;
+        if (!byteReadInt<uint16_t>(file, &len))
+            return false;
 
-/**
- * 读取一个C风格字符串
- */
-bool aFuntool::byteReadStr(FILE *file, char *&str) {
-    uint16_t len;
-    if (!byteReadInt<uint16_t>(file, &len))
-        return false;
+        if (len == 0) {
+            str = nullptr;
+            return true;
+        }
 
-    if (len == 0) {
-        str = nullptr;
-        return true;
+        str = calloc(len + 1, char);
+        return fread(str, sizeof(char), len, file) == len;
     }
 
-    str = calloc(len + 1, char);
-    return fread(str, sizeof(char), len, file) == len;
-}
-
-/**
- * 读取一个C++风格字符串
- */
-bool aFuntool::byteReadStr(FILE *file, std::string &str) {
-    uint16_t len;
-    if (!byteReadInt<uint16_t>(file, &len))
-        return false;
-
-    if (len == 0) {
-        str = "";
-        return true;
+    /**
+     * 读取一个C++风格字符串
+     */
+    bool byteReadStr(FILE *file, std::string &str){
+        uint16_t len;
+        if (!byteReadInt<uint16_t>(file, &len))
+            return false;
+
+        if (len == 0) {
+            str = "";
+            return true;
+        }
+
+        char *tmp = calloc(len + 1, char);
+        size_t ret = fread(tmp, sizeof(char), len, file);
+        str = tmp;
+        free(tmp);
+        return ret == len;
     }
 
-    char *tmp = calloc(len + 1, char);
-    size_t ret = fread(tmp, sizeof(char), len, file);
-    str = tmp;
-    free(tmp);
-    return ret == len;
-}
+}

+ 57 - 55
src/tool/dlc.cpp

@@ -1,73 +1,75 @@
 #include "tool.h"
 #include "dlc.h"
-using namespace aFuntool;
 
-DlcHandle::Handle *DlcHandle::dlc = nullptr;
+namespace aFuntool {
+    DlcHandle::Handle *DlcHandle::dlc = nullptr;
 
-/**
- * 打开动态库
- * @param file 动态库路径
- * @param mode 模式
- * @return
- */
-aFuntool::DlcHandle::DlcHandle(const char *file, int mode) noexcept : handle_{nullptr} {
-    void *handle = dlopen(file, mode);
-    if (handle == nullptr)
-        return;
-
-    for (Handle *tmp = dlc; tmp != nullptr; tmp = tmp->next_) {
-        if (tmp->handle_ == handle) {
-            dlclose(handle);  // 减少dlopen时对handle的引用计数
-            (*tmp)++;
-            handle_ = tmp;
+    /**
+     * 打开动态库
+     * @param file 动态库路径
+     * @param mode 模式
+     * @return
+     */
+    DlcHandle::DlcHandle(const char *file, int mode) noexcept: handle_{nullptr}{
+        void *handle = dlopen(file, mode);
+        if (handle == nullptr)
             return;
+
+        for (Handle *tmp = dlc; tmp != nullptr; tmp = tmp->next_) {
+            if (tmp->handle_ == handle) {
+                dlclose(handle);  // 减少dlopen时对handle的引用计数
+                (*tmp)++;
+                handle_ = tmp;
+                return;
+            }
         }
-    }
 
-    handle_ = new Handle(handle);
-    (*handle_)++;
-}
+        handle_ = new Handle(handle);
+        (*handle_)++;
+    }
 
-aFuntool::DlcHandle::Handle::Handle(void *handle) : handle_{handle}, link_{0}, next_{DlcHandle::dlc}, prev_{nullptr} {
-    if (DlcHandle::dlc != nullptr)
-        DlcHandle::dlc->prev_ = dlc;
-    DlcHandle::dlc = this;
-}
+    DlcHandle::Handle::Handle(void *handle) : handle_{handle}, link_{0}, next_{DlcHandle::dlc},
+                                                        prev_{nullptr}{
+        if (DlcHandle::dlc != nullptr)
+            DlcHandle::dlc->prev_ = dlc;
+        DlcHandle::dlc = this;
+    }
 
 
-aFuntool::DlcHandle::Handle::~Handle() {
-    dlclose(handle_);
+    DlcHandle::Handle::~Handle(){
+        dlclose(handle_);
 
-    if (prev_ == nullptr)
-        dlc = next_;
-    else
-        prev_->next_ = next_;
+        if (prev_ == nullptr)
+            dlc = next_;
+        else
+            prev_->next_ = next_;
 
-    if (next_ != nullptr)
-        next_->prev_ = prev_;
-}
+        if (next_ != nullptr)
+            next_->prev_ = prev_;
+    }
 
 
-int aFuntool::DlcHandle::Handle::operator++(int){
-    return link_++;
-}
+    int DlcHandle::Handle::operator++(int){
+        return link_++;
+    }
 
 
-int aFuntool::DlcHandle::Handle::operator--(int){
-    int ret = link_--;
-    if (link_ == 0)
-        delete this;  // 删除自己
-    return ret;
-}
+    int DlcHandle::Handle::operator--(int){
+        int ret = link_--;
+        if (link_ == 0)
+            delete this;  // 删除自己
+        return ret;
+    }
 
-/**
- * 退出函数
- * 需要使用at_exit注册
- */
-void aFuntool::DlcHandle::dlcExit() {
-    while (dlc != nullptr) {
-        auto next = dlc->next_;
-        free(dlc);
-        dlc = next;
+    /**
+     * 退出函数
+     * 需要使用at_exit注册
+     */
+    void DlcHandle::dlcExit(){
+        while (dlc != nullptr) {
+            auto next = dlc->next_;
+            free(dlc);
+            dlc = next;
+        }
     }
-}
+}

+ 71 - 71
src/tool/exit_.cpp

@@ -2,71 +2,92 @@
 #include "exit_.h"
 #include "mutex"
 
-using namespace aFuntool;
+namespace aFuntool {
+    static const int exit_func_size = 1024;
+    static std::mutex exit_mutex;
+    struct ExitFuncData {
+        aFunExitFunc *func;
+        void *data;
+    } exit_func[exit_func_size];
 
-static const int exit_func_size = 1024;
-static std::mutex exit_mutex;
-struct ExitFuncData {
-    aFunExitFunc *func;
-    void *data;
-} exit_func[exit_func_size];
+    /**
+     * 退出程序
+     * @param exit_code 退出代码
+     */
+    [[noreturn]] void aFunExit(int exit_code){
+        std::unique_lock<std::mutex> ul{exit_mutex};
+        for (int i = exit_func_size - 1; i >= 0; i--) {
+            if (exit_func[i].func != nullptr)
+                exit_func[i].func(exit_func[i].data);
+        }
+        ul.unlock();
+        exit(exit_code);
+    }
 
-/**
- * 退出程序
- * @param exit_code 退出代码
- */
-[[ noreturn ]] void aFuntool::aFunExit(int exit_code) {
-    std::unique_lock<std::mutex> ul{exit_mutex};
-    for (int i = exit_func_size - 1; i >= 0; i--) {
-        if (exit_func[i].func != nullptr)
-            exit_func[i].func(exit_func[i].data);
+    /**
+     * 尝试执行退出函数
+     */
+    int aFunTryExitPseudo(){
+        if (exit_mutex.try_lock()) {
+            std::unique_lock<std::mutex> ul{exit_mutex, std::adopt_lock};
+            for (int i = exit_func_size - 1; i >= 0; i--) {
+                if (exit_func[i].func != nullptr)
+                    exit_func[i].func(exit_func[i].data);
+                exit_func[i].func = nullptr;
+                exit_func[i].data = nullptr;
+            }
+            return 1;
+        }
+        return 0;
     }
-    ul.unlock();
-    exit(exit_code);
-}
 
-/**
- * 尝试执行退出函数
- */
-int aFuntool::aFunTryExitPseudo() {
-    if (exit_mutex.try_lock()) {
-        std::unique_lock<std::mutex> ul{exit_mutex, std::adopt_lock};
+    /**
+     * 执行退出函数, 但不退出
+     */
+    int aFunExitPseudo(){
+        std::unique_lock<std::mutex> ul{exit_mutex};
         for (int i = exit_func_size - 1; i >= 0; i--) {
             if (exit_func[i].func != nullptr)
                 exit_func[i].func(exit_func[i].data);
             exit_func[i].func = nullptr;
             exit_func[i].data = nullptr;
         }
-        return 1;
+        return 0;
     }
-    return 0;
-}
 
-/**
- * 执行退出函数, 但不退出
- */
-int aFuntool::aFunExitPseudo() {
-    std::unique_lock<std::mutex> ul{exit_mutex};
-    for (int i = exit_func_size - 1; i >= 0; i--) {
-        if (exit_func[i].func != nullptr)
-            exit_func[i].func(exit_func[i].data);
-        exit_func[i].func = nullptr;
-        exit_func[i].data = nullptr;
+    /**
+     * 尝试注册退出函数, 若锁占用则返回-1
+     * @param func 退出函数
+     * @param data 参数
+     */
+    int aFunAtExitTry(aFunExitFunc *func, void *data){
+        if (exit_mutex.try_lock()) {
+            std::unique_lock<std::mutex> ul{exit_mutex, std::adopt_lock};
+            struct ExitFuncData *tmp = exit_func;
+            int count = 0;
+            for (NULL; tmp->func != nullptr; tmp++, count++) {
+                if (count >= exit_func_size) {
+                    return -1;
+                }
+            }
+            tmp->func = func;
+            tmp->data = data;
+            return count;
+        }
+        return -1;
     }
-    return 0;
-}
 
-/**
- * 尝试注册退出函数, 若锁占用则返回-1
- * @param func 退出函数
- * @param data 参数
- */
-int aFuntool::aFunAtExitTry(aFunExitFunc *func, void *data) {
-    if (exit_mutex.try_lock()) {
-        std::unique_lock<std::mutex> ul{exit_mutex, std::adopt_lock};
+    /**
+     * 注册退出函数, aFun退出函数会在atexit退出函数之前执行
+     * @param func 退出函数
+     * @param data 参数
+     * @return
+     */
+    int aFunAtExit(aFunExitFunc *func, void *data){
+        std::unique_lock<std::mutex> ul{exit_mutex};
         struct ExitFuncData *tmp = exit_func;
         int count = 0;
-        for(NULL; tmp->func != nullptr; tmp++, count++) {
+        for (NULL; tmp->func != nullptr; tmp++, count++) {
             if (count >= exit_func_size) {
                 return -1;
             }
@@ -75,25 +96,4 @@ int aFuntool::aFunAtExitTry(aFunExitFunc *func, void *data) {
         tmp->data = data;
         return count;
     }
-    return -1;
-}
-
-/**
- * 注册退出函数, aFun退出函数会在atexit退出函数之前执行
- * @param func 退出函数
- * @param data 参数
- * @return
- */
-int aFuntool::aFunAtExit(aFunExitFunc *func, void *data) {
-    std::unique_lock<std::mutex> ul{exit_mutex};
-    struct ExitFuncData *tmp = exit_func;
-    int count = 0;
-    for(NULL; tmp->func != nullptr; tmp++, count++) {
-        if (count >= exit_func_size) {
-            return -1;
-        }
-    }
-    tmp->func = func;
-    tmp->data = data;
-    return count;
-}
+}

+ 240 - 240
src/tool/file.cpp

@@ -15,8 +15,6 @@
 #include "log.h"
 #include "stdio_.h"
 
-using namespace aFuntool;
-
 #ifdef aFunWIN32_NO_CYGWIN
 #ifdef _MSC_VER
 #pragma warning(disable : 5105)  // 关闭 5105 的警告输出 (Windows.h中使用)
@@ -34,279 +32,281 @@ using namespace aFuntool;
 #define	S_ISDIR(m)	(((m) & S_IFMT) == S_IFDIR)
 #endif
 
+namespace aFuntool {
 #ifdef aFunWIN32_NO_CYGWIN
-typedef struct _stat64 aFun_stat;
-typedef wchar_t aFun_path;
+    typedef struct _stat64 aFun_stat;
+    typedef wchar_t aFun_path;
 #else
-typedef struct stat aFun_stat;
-typedef char aFun_path;
+    typedef struct stat aFun_stat;
+    typedef char aFun_path;
 #endif
 
-/**
- * 获取文件的stat结构体
- * @param stat stat 保存地址
- * @param path 路径 (utf-8)
- * @return
- */
-static int get_stat(aFun_stat &stat_, const std::string &path_){
-    int re;
+    /**
+     * 获取文件的stat结构体
+     * @param stat stat 保存地址
+     * @param path 路径 (utf-8)
+     * @return
+     */
+    static int get_stat(aFun_stat &stat_, const std::string &path_){
+        int re;
 #ifdef aFunWIN32_NO_CYGWIN
-    aFun_path *tmp = nullptr;
-    if (convertWideByte(&tmp, path_.c_str(), CP_UTF8) == 0)
-        return -1;
-    re = _wstat64(tmp, &stat_);
-    free(tmp);  // 如果 path 为nullptr, 则释放最新生成的 wchat_t
+        aFun_path *tmp = nullptr;
+        if (convertWideByte(&tmp, path_.c_str(), CP_UTF8) == 0)
+            return -1;
+        re = _wstat64(tmp, &stat_);
+        free(tmp);  // 如果 path 为nullptr, 则释放最新生成的 wchat_t
 #else
-    re = stat(path_.c_str(), &stat_);
+        re = stat(path_.c_str(), &stat_);
 #endif
-    return re;
-}
-
-/**
- * 目标判断文件类型, 若是普通文件返回1, 若是文件夹返回2, 其他遇到错误返回0
- */
-int aFuntool::checkFile(const std::string &path){
-    if (path.empty())
-        return 0;
-
-    int re = 0;
-    aFun_stat stat;
-    if (get_stat(stat, path) != 0)
-        re = 0;
-    else if (S_ISREG(stat.st_mode))  // 普通文件
-        re = 1;
-    else if (S_ISDIR(stat.st_mode))
-        re = 2;
-    return re;
-}
-
-/**
- * 获取文件最后修改时间
- */
-time_t aFuntool::getFileMTime(const std::string &path) {
-    aFun_stat stat;
-    if (path.empty() || get_stat(stat, path) != 0)
-        return 0;
-    return stat.st_mtime;
-}
+        return re;
+    }
 
-/**
- * 拼接路径
- * @param path 路径
- * @param name 文件名
- * @param suffix 后缀
- * @return
- */
-std::string aFuntool::joinPath(const std::string &path, const std::string &name, const std::string &suffix) {
-    std::string name_suffix = name + suffix;
-    if (!path.empty() && *(path.end()) == SEP_CH)
-        return path + name_suffix;
-    else if (!path.empty())
-        return path + SEP + name_suffix;
-    return name_suffix;
-}
+    /**
+     * 目标判断文件类型, 若是普通文件返回1, 若是文件夹返回2, 其他遇到错误返回0
+     */
+    int checkFile(const std::string &path){
+        if (path.empty())
+            return 0;
+
+        int re = 0;
+        aFun_stat stat;
+        if (get_stat(stat, path) != 0)
+            re = 0;
+        else if (S_ISREG(stat.st_mode))  // 普通文件
+            re = 1;
+        else if (S_ISDIR(stat.st_mode))
+            re = 2;
+        return re;
+    }
 
-/**
- * 给定路径获取该路径所指定的文件名
- */
-std::string aFuntool::getFileName(const std::string &path){
-    int sep = 0;
-    if (*(path.end()) == SEP_CH)  // 若路径的最后一个字符为SEP, 则忽略此SEP
-        sep = -1;
+    /**
+     * 获取文件最后修改时间
+     */
+    time_t getFileMTime(const std::string &path) {
+        aFun_stat stat;
+        if (path.empty() || get_stat(stat, path) != 0)
+            return 0;
+        return stat.st_mtime;
+    }
 
-    auto slash = path.find_last_of('/');
-    if (slash == std::string::npos)
-        slash = 0;
-    else
-        slash++;
+    /**
+     * 拼接路径
+     * @param path 路径
+     * @param name 文件名
+     * @param suffix 后缀
+     * @return
+     */
+    std::string joinPath(const std::string &path, const std::string &name, const std::string &suffix) {
+        std::string name_suffix = name + suffix;
+        if (!path.empty() && *(path.end()) == SEP_CH)
+            return path + name_suffix;
+        else if (!path.empty())
+            return path + SEP + name_suffix;
+        return name_suffix;
+    }
 
-    return path.substr(path.size() - slash + sep, slash);
-}
+    /**
+     * 给定路径获取该路径所指定的文件名
+     */
+    std::string getFileName(const std::string &path){
+        int sep = 0;
+        if (*(path.end()) == SEP_CH)  // 若路径的最后一个字符为SEP, 则忽略此SEP
+            sep = -1;
+
+        auto slash = path.find_last_of('/');
+        if (slash == std::string::npos)
+            slash = 0;
+        else
+            slash++;
 
-/**
- * 获取 文件路径+文件名(排除后缀)
- */
-std::string aFuntool::getFilePathName(const std::string &path){
-    auto point = path.find_last_of('.');
-    if (point == std::string::npos)
-        return path;
-    return path.substr(point);
-}
+        return path.substr(path.size() - slash + sep, slash);
+    }
 
-/**
- * 获取文件路径(不包含文件名)
- */
-std::string aFuntool::getFilePath(const std::string &path, int dep){
-    std::string::size_type point = path.size();
-    for (int i = 0; i < dep; i++) {
-        auto tmp = path.rfind(SEP_CH, point - 1);
-        if (tmp == std::string::npos)
-            break;
-        point = tmp;
+    /**
+     * 获取 文件路径+文件名(排除后缀)
+     */
+    std::string getFilePathName(const std::string &path){
+        auto point = path.find_last_of('.');
+        if (point == std::string::npos)
+            return path;
+        return path.substr(point);
     }
-    return path.substr(0, point);
-}
 
-/**
- * 获取文件后缀
- */
-std::string aFuntool::getFileSurfix(const std::string &path) {
-    auto point = path.find_last_of('.');
-    if (point == std::string::npos)
-        point = 0;
-    else
-        point++;
+    /**
+     * 获取文件路径(不包含文件名)
+     */
+    std::string getFilePath(const std::string &path, int dep){
+        std::string::size_type point = path.size();
+        for (int i = 0; i < dep; i++) {
+            auto tmp = path.rfind(SEP_CH, point - 1);
+            if (tmp == std::string::npos)
+                break;
+            point = tmp;
+        }
+        return path.substr(0, point);
+    }
 
-    std::string ret = path.substr(path.size() - point, point);
-    return ret;
-}
+    /**
+     * 获取文件后缀
+     */
+    std::string getFileSurfix(const std::string &path) {
+        auto point = path.find_last_of('.');
+        if (point == std::string::npos)
+            point = 0;
+        else
+            point++;
 
-/**
- * 把一个文件名转换为合法的变量名(替换不合法字符为_)
- * @param name 路径
- * @param need_free 是否需要释放
- */
-std::string aFuntool::fileNameToVar(const std::string &name){
-    char *var = strCopy(name.c_str());  // 复制新的数据再修改
+        std::string ret = path.substr(path.size() - point, point);
+        return ret;
+    }
 
-    if (!isalpha(*var) && *var != '_')
-        var = strJoin("_", var, false, true);
-    for (char *tmp = var; *tmp != 0; tmp++)
-        if (!isalnum(*tmp) &&'_' != *tmp)
-            *tmp = '_';
-    std::string ret = var;
-    free(var);
-    return ret;
-}
+    /**
+     * 把一个文件名转换为合法的变量名(替换不合法字符为_)
+     * @param name 路径
+     * @param need_free 是否需要释放
+     */
+    std::string fileNameToVar(const std::string &name){
+        char *var = strCopy(name.c_str());  // 复制新的数据再修改
+
+        if (!isalpha(*var) && *var != '_')
+            var = strJoin("_", var, false, true);
+        for (char *tmp = var; *tmp != 0; tmp++)
+            if (!isalnum(*tmp) &&'_' != *tmp)
+                *tmp = '_';
+        std::string ret = var;
+        free(var);
+        return ret;
+    }
 
-/**
- * 转换路径为合法路径(相对路径->绝对路径, 绝对路径保持不变)
- * @param path 文件路径
- * @param env 环境 必须以 / 结尾
- * @param need_free 是否需要释放 path
- */
-std::string aFuntool::findPath(const std::string &path, const std::string &env){
+    /**
+     * 转换路径为合法路径(相对路径->绝对路径, 绝对路径保持不变)
+     * @param path 文件路径
+     * @param env 环境 必须以 / 结尾
+     * @param need_free 是否需要释放 path
+     */
+    std::string findPath(const std::string &path, const std::string &env){
 #ifdef __linux
-    if (path[0] != SEP_CH) // 不以 / 开头
+        if (path[0] != SEP_CH) // 不以 / 开头
 #else
-    if (!(isupper(path[0]) && (path)[1] == ':'))  // 不以盘符开头
+        if (!(isupper(path[0]) && (path)[1] == ':'))  // 不以盘符开头
 #endif
-        return env + path;  // 调整为相对路径模式
-    return path;
-}
+            return env + path;  // 调整为相对路径模式
+        return path;
+    }
 
-/**
- * 获取可执行程序目录
- * @param dep 从可执行程序往回跳出的层数
- */
-std::string aFuntool::getExedir(int dep) {
-    aFun_path exepath[218] = {0};
+    /**
+     * 获取可执行程序目录
+     * @param dep 从可执行程序往回跳出的层数
+     */
+    std::string getExedir(int dep) {
+        aFun_path exepath[218] = {0};
 #ifdef aFunWIN32_NO_CYGWIN
-    DWORD ret = GetModuleFileNameW(nullptr, exepath, 217);  // 预留一位给NUL
-    if (ret == 0 || wcslen(exepath) == 0)
-        return "";
-    char *path = nullptr;
-    if (convertFromWideByte(&path, exepath, CP_UTF8) == 0)
-        return "";
-    std::string re = getFilePath(path, dep + 1);
-    free(path);
-    return re;
+        DWORD ret = GetModuleFileNameW(nullptr, exepath, 217);  // 预留一位给NUL
+        if (ret == 0 || wcslen(exepath) == 0)
+            return "";
+        char *path = nullptr;
+        if (convertFromWideByte(&path, exepath, CP_UTF8) == 0)
+            return "";
+        std::string re = getFilePath(path, dep + 1);
+        free(path);
+        return re;
 #else
-    ssize_t ret =  readlink("/proc/self/exe", exepath, 217);  // 预留一位给NUL
-    if (ret == -1 || strlen(exepath) == 0)
-        return "";
-    return getFilePath(exepath, dep + 1);
+        ssize_t ret =  readlink("/proc/self/exe", exepath, 217);  // 预留一位给NUL
+        if (ret == -1 || strlen(exepath) == 0)
+            return "";
+        return getFilePath(exepath, dep + 1);
 #endif
-}
-
-/**
- * @param path 文件路径 (utf-8)
- * @return 文件大小
- */
-uintmax_t aFuntool::getFileSize(const std::string &path) {
-    aFun_stat stat;
-    int ret;
-    ret = get_stat(stat, path);
-    if(ret != 0)
-        return 0;  // 获取失败。
-    return (uintmax_t)stat.st_size;  // 返回文件大小
-}
+    }
 
-/**
- * 检查给定字符串是否utf-8编码
- * @param str 字符串
- */
-bool aFuntool::isCharUTF8(const char *str) {
-    int code = 0;  // utf-8 多字节数
-    for (const char *ch = str; *ch != NUL; ch++) {
-        unsigned char c = *ch;
-        unsigned char c_ = ~c;
+    /**
+     * @param path 文件路径 (utf-8)
+     * @return 文件大小
+     */
+    uintmax_t getFileSize(const std::string &path) {
+        aFun_stat stat;
+        int ret;
+        ret = get_stat(stat, path);
+        if(ret != 0)
+            return 0;  // 获取失败。
+        return (uintmax_t)stat.st_size;  // 返回文件大小
+    }
 
-        if (SysLogger)
-            assertFatalErrorLog(code >= 0 && code <= 5, SysLogger, 2, "str = %s", str);
-        if (code == 0) {
-            if ((c_ & 0xFC) == 0 && (c & 0x02) == 0)  // 检查是否为1111110x, 先对其取反, 使用0xFC掩码检查前6位是否为0, 然后单独检查倒数第二位是否为0
-                code = 5;  // 剩余 5 个字节
-            else if ((c_ & 0xF8) == 0 && (c & 0x04) == 0)
-                code = 4;  // 剩余 4 个字节
-            else if ((c_ & 0xF0) == 0 && (c & 0x08) == 0)
-                code = 3;  // 剩余 3 个字节
-            else if ((c_ & 0xE0) == 0 && (c & 0x10) == 0)
-                code = 2;  // 剩余 2 个字节
-            else if ((c_ & 0xC0) == 0 && (c & 0x20) == 0)
-                code = 1;  // 剩余 1 个字节
-            else if ((c & 0x80) == 0)  // 检查最高位是否为0
-                code = 0;
+    /**
+     * 检查给定字符串是否utf-8编码
+     * @param str 字符串
+     */
+    bool isCharUTF8(const char *str) {
+        int code = 0;  // utf-8 多字节数
+        for (const char *ch = str; *ch != NUL; ch++) {
+            unsigned char c = *ch;
+            unsigned char c_ = ~c;
+
+            if (SysLogger)
+                assertFatalErrorLog(code >= 0 && code <= 5, SysLogger, 2, "str = %s", str);
+            if (code == 0) {
+                if ((c_ & 0xFC) == 0 && (c & 0x02) == 0)  // 检查是否为1111110x, 先对其取反, 使用0xFC掩码检查前6位是否为0, 然后单独检查倒数第二位是否为0
+                    code = 5;  // 剩余 5 个字节
+                else if ((c_ & 0xF8) == 0 && (c & 0x04) == 0)
+                    code = 4;  // 剩余 4 个字节
+                else if ((c_ & 0xF0) == 0 && (c & 0x08) == 0)
+                    code = 3;  // 剩余 3 个字节
+                else if ((c_ & 0xE0) == 0 && (c & 0x10) == 0)
+                    code = 2;  // 剩余 2 个字节
+                else if ((c_ & 0xC0) == 0 && (c & 0x20) == 0)
+                    code = 1;  // 剩余 1 个字节
+                else if ((c & 0x80) == 0)  // 检查最高位是否为0
+                    code = 0;
+                else
+                    return false;
+            } else if ((c_ & 0x80) == 0 && (c & 0x40) == 0)
+                code--;
             else
                 return false;
-        } else if ((c_ & 0x80) == 0 && (c & 0x40) == 0)
-            code--;
-        else
-            return false;
-    }
+        }
 
-    return true;
-}
+        return true;
+    }
 
-bool aFuntool::isCharUTF8(const std::string &str) {
-    return isCharUTF8(str.c_str());
-}
+    bool isCharUTF8(const std::string &str) {
+        return isCharUTF8(str.c_str());
+    }
 
-/**
- * 打开指定文件
- * @param path_ 路径 (utf-8)
- * @param mode_ 模式
- * @return
- */
-FILE *aFuntool::fileOpen(const char *path_, const char *mode_) {
-    if (strlen(mode_) >= 5)
-        return nullptr;
+    /**
+     * 打开指定文件
+     * @param path_ 路径 (utf-8)
+     * @param mode_ 模式
+     * @return
+     */
+    FILE *fileOpen(const char *path_, const char *mode_) {
+        if (strlen(mode_) >= 5)
+            return nullptr;
 #ifdef aFunWIN32_NO_CYGWIN
-    FILE *file = nullptr;
-    wchar_t *path = nullptr;
-    wchar_t mode[5];
-    if (convertWideByte(&path, path_, CP_UTF8) == 0)
-        return nullptr;
-    for (int i = 0; i < 5; i++)
-        mode[i] = (wchar_t)mode_[i];  // ascii字符转换
-
-    _wfopen_s(&file, path, mode);
-    free(path);
-    return file;
+        FILE *file = nullptr;
+        wchar_t *path = nullptr;
+        wchar_t mode[5];
+        if (convertWideByte(&path, path_, CP_UTF8) == 0)
+            return nullptr;
+        for (int i = 0; i < 5; i++)
+            mode[i] = (wchar_t)mode_[i];  // ascii字符转换
+
+        _wfopen_s(&file, path, mode);
+        free(path);
+        return file;
 #else
-    return fopen(path_, mode_);
+        return fopen(path_, mode_);
 #endif
-}
+    }
 
-FILE *aFuntool::fileOpen(const std::string &path_, const char *mode_) {
-    return fileOpen(path_.c_str(), mode_);
-}
+    FILE *fileOpen(const std::string &path_, const char *mode_) {
+        return fileOpen(path_.c_str(), mode_);
+    }
 
-/**
- * 关闭文件, 本质和fclose一样
- * @param file FILE
- * @return
- */
-int aFuntool::fileClose(FILE *file) {
-    return fclose(file);
-}
+    /**
+     * 关闭文件, 本质和fclose一样
+     * @param file FILE
+     * @return
+     */
+    int fileClose(FILE *file) {
+        return fclose(file);
+    }
+}

+ 13 - 13
src/tool/hash.cpp

@@ -6,18 +6,18 @@
 #include "tool.h"
 #include "hash.h"
 
-using namespace aFuntool;
+namespace aFuntool {
+    time33_t time33(const char *str){
+        unsigned int hash = 5381;
+        while (*str)
+            hash += (hash << 5) + (*str++);
+        return (hash & 0x7FFFFFFF);  // NOLINT
+    }
 
-time33_t aFuntool::time33(const char *str) {
-    unsigned int hash = 5381;
-    while(*str)
-        hash += (hash << 5 ) + (*str++);
-    return (hash & 0x7FFFFFFF);  // NOLINT
-}
-
-time33_t aFuntool::time33(const std::string &str) {
-    unsigned int hash = 5381;
-    for (auto ch : str)
-        hash += (hash << 5 ) + ch;
-    return (hash & 0x7FFFFFFF);  // NOLINT
+    time33_t time33(const std::string &str){
+        unsigned int hash = 5381;
+        for (auto ch: str)
+            hash += (hash << 5) + ch;
+        return (hash & 0x7FFFFFFF);  // NOLINT
+    }
 }

+ 261 - 254
src/tool/log.cpp

@@ -25,10 +25,10 @@
 #include "str.h"
 #include "exit_.h"
 
-using namespace aFuntool;
-
 #ifdef aFunWIN32
+
 #include <windows.h>
+
 #define getpid() (long)GetCurrentProcessId()
 #define gettid() (long)GetCurrentThreadId()
 // cygwin没有syscall.h, 因此需要依赖 windows 的 api
@@ -56,20 +56,19 @@ namespace aFuntool {
 
         LogNode *next = nullptr;
     };
-}
 
-void staticAnsyWritrLog(LogFactory::ansyData *data);
+    void staticAnsyWritrLog(LogFactory::ansyData *data);
 
-aFuntool::LogFactory::LogFactory() : sys_log {*this, "SYSTEM", log_info} {
-    init_=false;
-    pid_=0;
-    log_ = nullptr;
-    csv_ = nullptr;
+    LogFactory::LogFactory() : sys_log{*this, "SYSTEM", log_info}{
+        init_ = false;
+        pid_ = 0;
+        log_ = nullptr;
+        csv_ = nullptr;
 
-    asyn_=false;
-    log_buf_ = nullptr;
-    plog_buf_ = nullptr;
-}
+        asyn_ = false;
+        log_buf_ = nullptr;
+        plog_buf_ = nullptr;
+    }
 
 /**
  * 函数名: initLogSystem
@@ -84,106 +83,106 @@ aFuntool::LogFactory::LogFactory() : sys_log {*this, "SYSTEM", log_info} {
  * @param is_asyn 是否启用异步
  * @return
  */
-int aFuntool::LogFactory::initLogSystem(ConstFilePath path, bool is_asyn){
-    if (path.size() >= 218)  // 路径过长
-        return 0;
-
-    int re = 1;
-    std::unique_lock<std::mutex> ul{mutex_};
-    if (init_)
-        return 2;
-
-    char log_path[218] = {0};
-    char csv_path[218] = {0};
-    pid_ = getpid();  // 获取进程ID
-
-    char *ti = getTime(nullptr, (char *)"%Y-%m-%d%z");
-    snprintf(log_path, 218, "%s-%s.log", path.c_str(), ti);
-    snprintf(csv_path, 218, "%s-%s.csv", path.c_str(), ti);
-    free(ti);
-
-    uintmax_t log_size = getFileSize(log_path);
-    uintmax_t csv_size = getFileSize(csv_path);
-    bool csv_head_write = (checkFile(csv_path) == 0);  // 文件不存在时才写入头部
-
-    log_ = fileOpen(log_path, "a");
-    if (log_ == nullptr) {
-        perror("ERROR: ");
-        return 0;
-    }
-
-    csv_ = fileOpen(csv_path, (char *)"a");
-    if (csv_ == nullptr)
-        return 0;
+    int LogFactory::initLogSystem(ConstFilePath path, bool is_asyn){
+        if (path.size() >= 218)  // 路径过长
+            return 0;
+
+        int re = 1;
+        std::unique_lock<std::mutex> ul{mutex_};
+        if (init_)
+            return 2;
+
+        char log_path[218] = {0};
+        char csv_path[218] = {0};
+        pid_ = getpid();  // 获取进程ID
+
+        char *ti = getTime(nullptr, (char *) "%Y-%m-%d%z");
+        snprintf(log_path, 218, "%s-%s.log", path.c_str(), ti);
+        snprintf(csv_path, 218, "%s-%s.csv", path.c_str(), ti);
+        free(ti);
+
+        uintmax_t log_size = getFileSize(log_path);
+        uintmax_t csv_size = getFileSize(csv_path);
+        bool csv_head_write = (checkFile(csv_path) == 0);  // 文件不存在时才写入头部
+
+        log_ = fileOpen(log_path, "a");
+        if (log_ == nullptr) {
+            perror("ERROR: ");
+            return 0;
+        }
+
+        csv_ = fileOpen(csv_path, (char *) "a");
+        if (csv_ == nullptr)
+            return 0;
 
 #define CSV_FORMAT "%s,%s,%d,%d,%s,%ld,%s,%d,%s,%s\n"
 #define CSV_TITLE  "Level,Logger,PID,TID,Data,Timestamp,File,Line,Function,Log\n"
-    if (csv_head_write) {
-        fprintf(csv_, CSV_TITLE);  // 设置 cvs 标题
-        fflush(csv_);
-    }
+        if (csv_head_write) {
+            fprintf(csv_, CSV_TITLE);  // 设置 cvs 标题
+            fflush(csv_);
+        }
 #undef CSV_TITLE
 
-    init_ = true;
-    asyn_ = is_asyn;
-    if (is_asyn) {
-        plog_buf_ = &log_buf_;
-        auto *data = new ansyData{*this, mutex_};
-        thread_ = std::thread(staticAnsyWritrLog, data);
-    }
-
-    ul.unlock();
-    infoLog(&this->sys_log, "Log system init success");
-    infoLog(&this->sys_log, "Log .log size %lld", log_size);
-    infoLog(&this->sys_log, "Log .csv size %lld", csv_size);
-    return re;
-}
+        init_ = true;
+        asyn_ = is_asyn;
+        if (is_asyn) {
+            plog_buf_ = &log_buf_;
+            auto *data = new ansyData{*this, mutex_};
+            thread_ = std::thread(staticAnsyWritrLog, data);
+        }
 
-aFuntool::LogFactory::~LogFactory(){
-    std::unique_lock<std::mutex> ul{mutex_};
+        ul.unlock();
+        infoLog(&this->sys_log, "Log system init success");
+        infoLog(&this->sys_log, "Log .log size %lld", log_size);
+        infoLog(&this->sys_log, "Log .csv size %lld", csv_size);
+        return re;
+    }
 
-    ul.unlock();
-    infoLog(&this->sys_log, "Log system destruct by exit.");  // 需要用锁
+    LogFactory::~LogFactory(){
+        std::unique_lock<std::mutex> ul{mutex_};
 
-    ul.lock();
-    init_ = false;
-    if (asyn_) {
         ul.unlock();
-        cond_.notify_all();
-        thread_.join();
+        infoLog(&this->sys_log, "Log system destruct by exit.");  // 需要用锁
+
         ul.lock();
-        if (log_buf_ != nullptr)
-            printf_stderr(0, "Logsystem destruct error.");
+        init_ = false;
+        if (asyn_) {
+            ul.unlock();
+            cond_.notify_all();
+            thread_.join();
+            ul.lock();
+            if (log_buf_ != nullptr)
+                printf_stderr(0, "Logsystem destruct error.");
+        }
+
+        fileClose(log_);
+        fileClose(csv_);
+        log_ = nullptr;
+        csv_ = nullptr;
     }
 
-    fileClose(log_);
-    fileClose(csv_);
-    log_ = nullptr;
-    csv_ = nullptr;
-}
-
 
 /* LogLevel和字符串的转换 */
-static const char *LogLevelName[] = {
-        "TK",  // track 0
-        "DE",  // debug 1
-        "IN",  // info 2
-        "WA",  // warning 3
-        "ER",  // error 4
-        "SE",  // send_error 5
-        "FE",  // fatal_error 6
-};
-
-static const char *LogLevelNameLong[] = {
-        /* 内容输出到终端时使用*/
-        "Track",  // track 0
-        "Debug",  // debug 1
-        "Info",  // info 2
-        "Warning",  // warning 3
-        "Error",  // error 4
-        "Fatal Error",  // send_error 5
-        "*FATAL ERROR*",  // fatal_error 6
-};
+    static const char *LogLevelName[] = {
+            "TK",  // track 0
+            "DE",  // debug 1
+            "IN",  // info 2
+            "WA",  // warning 3
+            "ER",  // error 4
+            "SE",  // send_error 5
+            "FE",  // fatal_error 6
+    };
+
+    static const char *LogLevelNameLong[] = {
+            /* 内容输出到终端时使用*/
+            "Track",  // track 0
+            "Debug",  // debug 1
+            "Info",  // info 2
+            "Warning",  // warning 3
+            "Error",  // error 4
+            "Fatal Error",  // send_error 5
+            "*FATAL ERROR*",  // fatal_error 6
+    };
 
 /**
  * 日志写入到文件
@@ -197,25 +196,25 @@ static const char *LogLevelNameLong[] = {
  * @param func 函数名
  * @param info 日志内容
  */
-void aFuntool::LogFactory::writeLog(LogLevel level,
-                               const char *id, pid_t tid,
-                               const char *ti, time_t t,
-                               const char *file, int line, const char *func,
-                               const char *info) {
+    void LogFactory::writeLog(LogLevel level,
+                              const char *id, pid_t tid,
+                              const char *ti, time_t t,
+                              const char *file, int line, const char *func,
+                              const char *info){
 #define FORMAT "%s/[%s] %d %d {%s %ld} (%s:%d at %s) : '%s' \n"
-    /* 写入文件日志 */
-    if (log_ != nullptr) {
-        fprintf(log_, FORMAT, LogLevelName[level], id, pid_, tid, ti, t, file, line, func, info);
-        fflush(log_);
-    }
-    if (csv_ != nullptr) {
-        fprintf(csv_, CSV_FORMAT, LogLevelName[level], id, pid_, tid, ti, t, file, line, func, info);
-        fflush(csv_);
-    }
+        /* 写入文件日志 */
+        if (log_ != nullptr) {
+            fprintf(log_, FORMAT, LogLevelName[level], id, pid_, tid, ti, t, file, line, func, info);
+            fflush(log_);
+        }
+        if (csv_ != nullptr) {
+            fprintf(csv_, CSV_FORMAT, LogLevelName[level], id, pid_, tid, ti, t, file, line, func, info);
+            fflush(csv_);
+        }
 
 #undef FORMAT
 #undef CSV_FORMAT
-}
+    }
 
 /**
  * 日志写入到控制台
@@ -229,23 +228,23 @@ void aFuntool::LogFactory::writeLog(LogLevel level,
  * @param func 函数名
  * @param info 日志内容
  */
-void aFuntool::LogFactory::writeConsole(LogLevel level,
-                                        const char *id, pid_t tid,
-                                        const char *ti, time_t t,
-                                        const char *file, int line, const char *func,
-                                        const char *info) {
+    void LogFactory::writeConsole(LogLevel level,
+                                  const char *id, pid_t tid,
+                                  const char *ti, time_t t,
+                                  const char *file, int line, const char *func,
+                                  const char *info){
 #define FORMAT_SHORT "\r* %s[%s] %d %s %ld (%s:%d) : %s \n"  // 显示到终端, 添加\r回车符确保顶行显示
 #define STD_BUF_SIZE (strlen(info) + 1024)
-    if (level < log_warning) {
-        printf_stdout(STD_BUF_SIZE, FORMAT_SHORT, LogLevelNameLong[level], id, tid, ti, t, file, line, info);
-        fflush(stdout);
-    } else {
-        printf_stderr(STD_BUF_SIZE, FORMAT_SHORT, LogLevelNameLong[level], id, tid, ti, t, file, line, info);
-        fflush(stderr);
-    }
+        if (level < log_warning) {
+            printf_stdout(STD_BUF_SIZE, FORMAT_SHORT, LogLevelNameLong[level], id, tid, ti, t, file, line, info);
+            fflush(stdout);
+        } else {
+            printf_stderr(STD_BUF_SIZE, FORMAT_SHORT, LogLevelNameLong[level], id, tid, ti, t, file, line, info);
+            fflush(stderr);
+        }
 #undef FORMAT_SHORT
 #undef STD_BUF_SIZE
-}
+    }
 
 /**
  * 日志异步写入
@@ -259,64 +258,64 @@ void aFuntool::LogFactory::writeConsole(LogLevel level,
  * @param func 函数名
  * @param info 日志内容
  */
-void aFuntool::LogFactory::writeLogAsyn(LogLevel level,
-                                        const char *id, pid_t tid,
-                                        const char *ti, time_t t,
-                                        const char *file, int line, const char *func, const char *info) {
+    void LogFactory::writeLogAsyn(LogLevel level,
+                                  const char *id, pid_t tid,
+                                  const char *ti, time_t t,
+                                  const char *file, int line, const char *func, const char *info){
 #define D(i) (*(plog_buf_))->i
-    *(plog_buf_) = new aFuntool::LogNode;
-    D(level) = level;
-    D(id) = id;
-    D(tid) = tid;
-    D(date) = strCopy(ti);
-    D(time) = t;
-    D(file) = file;
-    D(line) = line;
-    D(func) = func;
-    D(info) = strCopy(info);
-    plog_buf_ = &(D(next));
+        *(plog_buf_) = new LogNode;
+        D(level) = level;
+        D(id) = id;
+        D(tid) = tid;
+        D(date) = strCopy(ti);
+        D(time) = t;
+        D(file) = file;
+        D(line) = line;
+        D(func) = func;
+        D(info) = strCopy(info);
+        plog_buf_ = &(D(next));
 #undef D
-}
+    }
 
 
-aFuntool::LogNode *aFuntool::LogFactory::pop(){
-    struct LogNode *n = log_buf_;
-    if (n != nullptr) {
-        log_buf_ = n->next;
-        if (log_buf_ == nullptr)
-            plog_buf_ = &log_buf_;
+    LogNode *LogFactory::pop(){
+        struct LogNode *n = log_buf_;
+        if (n != nullptr) {
+            log_buf_ = n->next;
+            if (log_buf_ == nullptr)
+                plog_buf_ = &log_buf_;
+        }
+        return n;
     }
-    return n;
-}
 
 
-void staticAnsyWritrLog(LogFactory::ansyData *data) {
-    data->factor.ansyWritrLog(data);
-}
+    void staticAnsyWritrLog(LogFactory::ansyData *data){
+        data->factor.ansyWritrLog(data);
+    }
 
 
 /**
  * 异步写入日志程序
  * @return
  */
-void LogFactory::ansyWritrLog(ansyData *data) {
-    std::unique_lock<std::mutex> ul{mutex_};
-    while (true) {
-        while (init_ && log_buf_ == nullptr)
-            cond_.wait(ul);
-        if (!init_ && log_buf_ == nullptr)
-            break;
-
-        LogNode *tmp = data->factor.pop();
+    void LogFactory::ansyWritrLog(ansyData *data){
+        std::unique_lock<std::mutex> ul{mutex_};
+        while (true) {
+            while (init_ && log_buf_ == nullptr)
+                cond_.wait(ul);
+            if (!init_ && log_buf_ == nullptr)
+                break;
+
+            LogNode *tmp = data->factor.pop();
 #define D(i) tmp->i
-        data->factor.writeLog(D(level), D(id), D(tid), D(date), D(time), D(file), D(line), D(func), D(info));
+            data->factor.writeLog(D(level), D(id), D(tid), D(date), D(time), D(file), D(line), D(func), D(info));
 #undef D
-        free(tmp->date);
-        free(tmp->info);
-        delete tmp;
+            free(tmp->date);
+            free(tmp->info);
+            delete tmp;
+        }
+        delete data;
     }
-    delete data;
-}
 
 /**
  * 日志器 写入日志
@@ -330,122 +329,130 @@ void LogFactory::ansyWritrLog(ansyData *data) {
  * @param ap 格式字符串内容
  * @return
  */
-int aFuntool::LogFactory::newLog(Logger *logger,
-                                 bool pc,
-                                 LogLevel level,
-                                 const char *file, int line, const char *func,
-                                 const char *format, va_list ap){
-    if (logger->level_ > level)
-        return 2;
-
-    std::unique_lock<std::mutex> ul{mutex_};
-    if (!init_ || log_ == nullptr) {
-        return 1;
-    }
-    clear_ferror(log_);
-
-    // 输出 head 信息
-    time_t t = 0;
-    char *ti = getTime(&t, ("%Y-%m-%d %H:%M:%S"));
-    pid_t tid = gettid();
+    int LogFactory::newLog(Logger *logger,
+                           bool pc,
+                           LogLevel level,
+                           const char *file, int line, const char *func,
+                           const char *format, va_list ap){
+        if (logger->level_ > level)
+            return 2;
+
+        std::unique_lock<std::mutex> ul{mutex_};
+        if (!init_ || log_ == nullptr) {
+            return 1;
+        }
+        clear_ferror(log_);
+
+        // 输出 head 信息
+        time_t t = 0;
+        char *ti = getTime(&t, ("%Y-%m-%d %H:%M:%S"));
+        pid_t tid = gettid();
+
+        char tmp[2048] = {0};
+        vsnprintf(tmp, 1024, format, ap);  // ap只使用一次
+        va_end(ap);
+
+        if (asyn_)
+            writeLogAsyn(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
+        else
+            writeLog(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
+
+        if (pc)
+            writeConsole(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
 
-    char tmp[2048] = {0};
-    vsnprintf(tmp, 1024, format, ap);  // ap只使用一次
-    va_end(ap);
-
-    if (asyn_)
-        writeLogAsyn(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
-    else
-        writeLog(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
-
-    if (pc)
-        writeConsole(level, logger->id_.c_str(), tid, ti, t, file, line, func, tmp);
-
-    ul.unlock();
-    if (asyn_)
-        cond_.notify_all();
-    free(ti);
-    return 0;
-}
+        ul.unlock();
+        if (asyn_)
+            cond_.notify_all();
+        free(ti);
+        return 0;
+    }
 
 #undef trackLog
-int aFuntool::Logger::writeTrackLog(const char *file, int line, const char *func,
-                                    const char *format, ...) {
+
+    int Logger::writeTrackLog(const char *file, int line, const char *func,
+                              const char *format, ...){
 #if aFunWriteTrack
-    va_list ap;
-    va_start(ap, format);
-    return this->factor_.newLog(this, aFunConsoleTrack, log_track, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        return this->factor_.newLog(this, aFunConsoleTrack, log_track, file, line, func, format, ap);
 #endif
-}
+    }
 
 #undef debugLog
-int aFuntool::Logger::writeDebugLog(const char *file, int line, const char *func,
-                                    const char *format, ...) {
+
+    int Logger::writeDebugLog(const char *file, int line, const char *func,
+                              const char *format, ...){
 #if aFunWriteDebug
-    va_list ap;
-    va_start(ap, format);
-    return this->factor_.newLog(this, aFunConsoleDebug, log_debug, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        return this->factor_.newLog(this, aFunConsoleDebug, log_debug, file, line, func, format, ap);
 #endif
-}
+    }
 
 #undef infoLog
-int aFuntool::Logger::writeInfoLog(const char *file, int line, const char *func,
-                                   const char *format, ...) {
+
+    int Logger::writeInfoLog(const char *file, int line, const char *func,
+                             const char *format, ...){
 #if aFunWriteInfo
-    va_list ap;
-    va_start(ap, format);
-    return this->factor_.newLog(this, aFunConsoleInfo, log_info, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        return this->factor_.newLog(this, aFunConsoleInfo, log_info, file, line, func, format, ap);
 #endif
-}
+    }
 
 #undef warningLog
-int aFuntool::Logger::writeWarningLog(const char *file, int line, const char *func,
-                                      const char *format, ...) {
+
+    int Logger::writeWarningLog(const char *file, int line, const char *func,
+                                const char *format, ...){
 #if !aFunIgnoreWarning
-    va_list ap;
-    va_start(ap, format);
-    return this->factor_.newLog(this, aFunConsoleWarning, log_warning, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        return this->factor_.newLog(this, aFunConsoleWarning, log_warning, file, line, func, format, ap);
 #endif
-}
+    }
 
 #undef errorLog
-int aFuntool::Logger::writeErrorLog(const char *file, int line, const char *func,
-                                    const char *format, ...) {
+
+    int Logger::writeErrorLog(const char *file, int line, const char *func,
+                              const char *format, ...){
 #if !aFunIgnoreError
-    va_list ap;
-    va_start(ap, format);
-    return this->factor_.newLog(this, aFunConsoleError, log_error, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        return this->factor_.newLog(this, aFunConsoleError, log_error, file, line, func, format, ap);
 #endif
-}
+    }
 
 #undef sendErrorLog
-int aFuntool::Logger::writeSendErrorLog(const char *file, int line, const char *func,
-                                        const char *format, ...) {
+
+    int Logger::writeSendErrorLog(const char *file, int line, const char *func,
+                                  const char *format, ...){
 #ifndef aFunOFFAllLog
 #if !aFunIgnoreSendError
-    va_list ap;
-    va_start(ap, format);
-    this->factor_.newLog(this, aFunConsoleSendError, log_send_error, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        this->factor_.newLog(this, aFunConsoleSendError, log_send_error, file, line, func, format, ap);
 #endif
 
-    if (this->exit_)
-        throw LogFatalError("Log Fatal Error");
-    aFunExit(EXIT_FAILURE);
+        if (this->exit_)
+            throw LogFatalError("Log Fatal Error");
+        aFunExit(EXIT_FAILURE);
 #endif
-}
+    }
 
 #undef fatalErrorLog
-int aFuntool::Logger::writeFatalErrorLog(const char *file, int line, const char *func,
-                                         int exit_code, const char *format, ...) {
+
+    int Logger::writeFatalErrorLog(const char *file, int line, const char *func,
+                                   int exit_code, const char *format, ...){
 #ifndef aFunOFFAllLog
 #if !aFunIgnoreFatal
-    va_list ap;
-    va_start(ap, format);
-    this->factor_.newLog(this, aFunConsoleFatalError, log_fatal_error, file, line, func, format, ap);
+        va_list ap;
+        va_start(ap, format);
+        this->factor_.newLog(this, aFunConsoleFatalError, log_fatal_error, file, line, func, format, ap);
 #endif
-    if (exit_code == EXIT_SUCCESS)
-        abort();
-    else
-        aFunExit(exit_code);
+        if (exit_code == EXIT_SUCCESS)
+            abort();
+        else
+            aFunExit(exit_code);
 #endif
-}
+    }
+}

+ 198 - 200
src/tool/md5.cpp

@@ -12,217 +12,215 @@
 #include "tool-exception.h"
 #include "__md5.h"
 
-using namespace aFuntool;
-
 namespace aFuntool {
     struct MD5_CTX {
         unsigned int count[2];
         unsigned int state[4];
         unsigned char buffer[64];
     };
-}
-
-static void MD5Transform(unsigned int state[4],unsigned char block[64]);
-static void MD5Encode(unsigned char *output,const unsigned int *input,unsigned int len);
-static void MD5Decode(unsigned int *output,const unsigned char *input,unsigned int len);
-
-unsigned char PADDING[] = {
-                0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-                0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-                0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-                0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
-        };
-
-MD5_CTX *aFuntool::MD5Init() {
-    auto context = calloc(1, MD5_CTX);
-    context->count[0] = 0;
-    context->count[1] = 0;
-    context->state[0] = 0x67452301;
-    context->state[1] = 0xEFCDAB89;
-    context->state[2] = 0x98BADCFE;
-    context->state[3] = 0x10325476;
-    return context;
-}
-
-void aFuntool::MD5Update(MD5_CTX *context, unsigned char *input, unsigned int input_len) {
-    unsigned int i;
-    unsigned int index;
-    unsigned int part_len;
-
-    index = (context->count[0] >> (unsigned)3) & (unsigned)0x3F;
-    part_len = 64 - index;
-    context->count[0] += input_len << (unsigned)3;
-
-    if(context->count[0] < (input_len << (unsigned)3))
-        context->count[1]++;
-    context->count[1] += input_len >> (unsigned)29;
-
-    if(input_len >= part_len) {
-        memcpy(&context->buffer[index], input, part_len);
-        MD5Transform(context->state, context->buffer);
-
-        for(i = part_len; i + 64 <= input_len; i+=64)
-            MD5Transform(context->state, &input[i]);
-
-        index = 0;
+
+    static void MD5Transform(unsigned int state[4], unsigned char block[64]);
+
+    static void MD5Encode(unsigned char *output, const unsigned int *input, unsigned int len);
+
+    static void MD5Decode(unsigned int *output, const unsigned char *input, unsigned int len);
+
+    unsigned char PADDING[] = {
+            0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+    };
+
+    MD5_CTX *MD5Init(){
+        auto context = calloc(1, MD5_CTX);
+        context->count[0] = 0;
+        context->count[1] = 0;
+        context->state[0] = 0x67452301;
+        context->state[1] = 0xEFCDAB89;
+        context->state[2] = 0x98BADCFE;
+        context->state[3] = 0x10325476;
+        return context;
     }
-    else
-        i = 0;
-    memcpy(&context->buffer[index], &input[i], input_len - i);
-}
-
-void aFuntool::MD5Final(MD5_CTX *context, unsigned char digest[16]) {
-    unsigned int index;
-    unsigned int pad_len;
-    unsigned char bits[8];
-
-    index = (context->count[0] >> (unsigned)3) & (unsigned)0x3F;
-    pad_len = (index < 56) ? (56 - index) : (120 - index);
-    MD5Encode(bits, context->count, 8);
-    MD5Update(context, PADDING, pad_len);
-    MD5Update(context, bits, 8);
-    MD5Encode(digest, context->state, 16);
-    free(context);
-}
-
-static void MD5Encode(unsigned char *output,const unsigned int *input, unsigned int len) {
-    unsigned int i = 0;
-    unsigned int j = 0;
-
-    while(j < len)
-    {
-        output[j] = input[i] & (unsigned)0xFF;
-        output[j+1] = (input[i] >> (unsigned)8) & (unsigned)0xFF;
-        output[j+2] = (input[i] >> (unsigned)16) & (unsigned)0xFF;
-        output[j+3] = (input[i] >> (unsigned)24) & (unsigned)0xFF;
-        i++;
-        j += 4;
+
+    void MD5Update(MD5_CTX *context, unsigned char *input, unsigned int input_len){
+        unsigned int i;
+        unsigned int index;
+        unsigned int part_len;
+
+        index = (context->count[0] >> (unsigned) 3) & (unsigned) 0x3F;
+        part_len = 64 - index;
+        context->count[0] += input_len << (unsigned) 3;
+
+        if (context->count[0] < (input_len << (unsigned) 3))
+            context->count[1]++;
+        context->count[1] += input_len >> (unsigned) 29;
+
+        if (input_len >= part_len) {
+            memcpy(&context->buffer[index], input, part_len);
+            MD5Transform(context->state, context->buffer);
+
+            for (i = part_len; i + 64 <= input_len; i += 64)
+                MD5Transform(context->state, &input[i]);
+
+            index = 0;
+        } else
+            i = 0;
+        memcpy(&context->buffer[index], &input[i], input_len - i);
     }
-}
-
-static void MD5Decode(unsigned int *output, const unsigned char *input, unsigned int len) {
-    for (unsigned int i=0, j=0; j < len; i++, j+=4) {
-        output[i] = (input[j]) |
-                    (input[j+1] << (unsigned)8) |
-                    (input[j+2] << (unsigned)16) |
-                    (input[j+3] << (unsigned)24);
+
+    void MD5Final(MD5_CTX *context, unsigned char digest[16]){
+        unsigned int index;
+        unsigned int pad_len;
+        unsigned char bits[8];
+
+        index = (context->count[0] >> (unsigned) 3) & (unsigned) 0x3F;
+        pad_len = (index < 56) ? (56 - index) : (120 - index);
+        MD5Encode(bits, context->count, 8);
+        MD5Update(context, PADDING, pad_len);
+        MD5Update(context, bits, 8);
+        MD5Encode(digest, context->state, 16);
+        free(context);
+    }
+
+    static void MD5Encode(unsigned char *output, const unsigned int *input, unsigned int len){
+        unsigned int i = 0;
+        unsigned int j = 0;
+
+        while (j < len) {
+            output[j] = input[i] & (unsigned) 0xFF;
+            output[j + 1] = (input[i] >> (unsigned) 8) & (unsigned) 0xFF;
+            output[j + 2] = (input[i] >> (unsigned) 16) & (unsigned) 0xFF;
+            output[j + 3] = (input[i] >> (unsigned) 24) & (unsigned) 0xFF;
+            i++;
+            j += 4;
+        }
     }
-}
-
-static void MD5Transform(unsigned int state[4], unsigned char block[64]) {
-    unsigned int a = state[0];
-    unsigned int b = state[1];
-    unsigned int c = state[2];
-    unsigned int d = state[3];
-    unsigned int x[64];
-
-    MD5Decode(x,block,64);
-
-    FF(a, b, c, d, x[ 0], 7, 0xd76aa478); /* 1 */
-    FF(d, a, b, c, x[ 1], 12, 0xe8c7b756); /* 2 */
-    FF(c, d, a, b, x[ 2], 17, 0x242070db); /* 3 */
-    FF(b, c, d, a, x[ 3], 22, 0xc1bdceee); /* 4 */
-    FF(a, b, c, d, x[ 4], 7, 0xf57c0faf); /* 5 */
-    FF(d, a, b, c, x[ 5], 12, 0x4787c62a); /* 6 */
-    FF(c, d, a, b, x[ 6], 17, 0xa8304613); /* 7 */
-    FF(b, c, d, a, x[ 7], 22, 0xfd469501); /* 8 */
-    FF(a, b, c, d, x[ 8], 7, 0x698098d8); /* 9 */
-    FF(d, a, b, c, x[ 9], 12, 0x8b44f7af); /* 10 */
-    FF(c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */
-    FF(b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */
-    FF(a, b, c, d, x[12], 7, 0x6b901122); /* 13 */
-    FF(d, a, b, c, x[13], 12, 0xfd987193); /* 14 */
-    FF(c, d, a, b, x[14], 17, 0xa679438e); /* 15 */
-    FF(b, c, d, a, x[15], 22, 0x49b40821); /* 16 */
-
-    /* Round 2 */
-    GG(a, b, c, d, x[ 1], 5, 0xf61e2562); /* 17 */
-    GG(d, a, b, c, x[ 6], 9, 0xc040b340); /* 18 */
-    GG(c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */
-    GG(b, c, d, a, x[ 0], 20, 0xe9b6c7aa); /* 20 */
-    GG(a, b, c, d, x[ 5], 5, 0xd62f105d); /* 21 */
-    GG(d, a, b, c, x[10], 9,  0x2441453); /* 22 */
-    GG(c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */
-    GG(b, c, d, a, x[ 4], 20, 0xe7d3fbc8); /* 24 */
-    GG(a, b, c, d, x[ 9], 5, 0x21e1cde6); /* 25 */
-    GG(d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */
-    GG(c, d, a, b, x[ 3], 14, 0xf4d50d87); /* 27 */
-    GG(b, c, d, a, x[ 8], 20, 0x455a14ed); /* 28 */
-    GG(a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */
-    GG(d, a, b, c, x[ 2], 9, 0xfcefa3f8); /* 30 */
-    GG(c, d, a, b, x[ 7], 14, 0x676f02d9); /* 31 */
-    GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */
-
-    /* Round 3 */
-    HH(a, b, c, d, x[ 5], 4, 0xfffa3942); /* 33 */
-    HH(d, a, b, c, x[ 8], 11, 0x8771f681); /* 34 */
-    HH(c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */
-    HH(b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */
-    HH(a, b, c, d, x[ 1], 4, 0xa4beea44); /* 37 */
-    HH(d, a, b, c, x[ 4], 11, 0x4bdecfa9); /* 38 */
-    HH(c, d, a, b, x[ 7], 16, 0xf6bb4b60); /* 39 */
-    HH(b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */
-    HH(a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */
-    HH(d, a, b, c, x[ 0], 11, 0xeaa127fa); /* 42 */
-    HH(c, d, a, b, x[ 3], 16, 0xd4ef3085); /* 43 */
-    HH(b, c, d, a, x[ 6], 23,  0x4881d05); /* 44 */
-    HH(a, b, c, d, x[ 9], 4, 0xd9d4d039); /* 45 */
-    HH(d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */
-    HH(c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */
-    HH(b, c, d, a, x[ 2], 23, 0xc4ac5665); /* 48 */
-
-    /* Round 4 */
-    II(a, b, c, d, x[ 0], 6, 0xf4292244); /* 49 */
-    II(d, a, b, c, x[ 7], 10, 0x432aff97); /* 50 */
-    II(c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */
-    II(b, c, d, a, x[ 5], 21, 0xfc93a039); /* 52 */
-    II(a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */
-    II(d, a, b, c, x[ 3], 10, 0x8f0ccc92); /* 54 */
-    II(c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */
-    II(b, c, d, a, x[ 1], 21, 0x85845dd1); /* 56 */
-    II(a, b, c, d, x[ 8], 6, 0x6fa87e4f); /* 57 */
-    II(d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */
-    II(c, d, a, b, x[ 6], 15, 0xa3014314); /* 59 */
-    II(b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */
-    II(a, b, c, d, x[ 4], 6, 0xf7537e82); /* 61 */
-    II(d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */
-    II(c, d, a, b, x[ 2], 15, 0x2ad7d2bb); /* 63 */
-    II(b, c, d, a, x[ 9], 21, 0xeb86d391); /* 64 */
-    state[0] += a;
-    state[1] += b;
-    state[2] += c;
-    state[3] += d;
-}
-
-
-template <typename T>
-T aFuntool::getFileMd5(T &path) {
-    FILE *fd;
-
-    unsigned long ret;
-    unsigned char data[READ_DATA_SIZE];
-    unsigned char md5_value[MD5_SIZE];
-
-    if ((fd = fileOpen(path, "rb")) == nullptr)
-        throw FileOpenException(path);
-
-    char *md5str = calloc(MD5_STRING, char);
-    MD5_CTX *md5 = MD5Init();
-    while (true) {
-        ret = fread(data, 1, READ_DATA_SIZE, fd);
-        MD5Update(md5, data, ret);
-        if (ret < READ_DATA_SIZE)
-            break;
+
+    static void MD5Decode(unsigned int *output, const unsigned char *input, unsigned int len){
+        for (unsigned int i = 0, j = 0; j < len; i++, j += 4) {
+            output[i] = (input[j]) |
+                        (input[j + 1] << (unsigned) 8) |
+                        (input[j + 2] << (unsigned) 16) |
+                        (input[j + 3] << (unsigned) 24);
+        }
+    }
+
+    static void MD5Transform(unsigned int state[4], unsigned char block[64]){
+        unsigned int a = state[0];
+        unsigned int b = state[1];
+        unsigned int c = state[2];
+        unsigned int d = state[3];
+        unsigned int x[64];
+
+        MD5Decode(x, block, 64);
+
+        FF(a, b, c, d, x[0], 7, 0xd76aa478); /* 1 */
+        FF(d, a, b, c, x[1], 12, 0xe8c7b756); /* 2 */
+        FF(c, d, a, b, x[2], 17, 0x242070db); /* 3 */
+        FF(b, c, d, a, x[3], 22, 0xc1bdceee); /* 4 */
+        FF(a, b, c, d, x[4], 7, 0xf57c0faf); /* 5 */
+        FF(d, a, b, c, x[5], 12, 0x4787c62a); /* 6 */
+        FF(c, d, a, b, x[6], 17, 0xa8304613); /* 7 */
+        FF(b, c, d, a, x[7], 22, 0xfd469501); /* 8 */
+        FF(a, b, c, d, x[8], 7, 0x698098d8); /* 9 */
+        FF(d, a, b, c, x[9], 12, 0x8b44f7af); /* 10 */
+        FF(c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */
+        FF(b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */
+        FF(a, b, c, d, x[12], 7, 0x6b901122); /* 13 */
+        FF(d, a, b, c, x[13], 12, 0xfd987193); /* 14 */
+        FF(c, d, a, b, x[14], 17, 0xa679438e); /* 15 */
+        FF(b, c, d, a, x[15], 22, 0x49b40821); /* 16 */
+
+        /* Round 2 */
+        GG(a, b, c, d, x[1], 5, 0xf61e2562); /* 17 */
+        GG(d, a, b, c, x[6], 9, 0xc040b340); /* 18 */
+        GG(c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */
+        GG(b, c, d, a, x[0], 20, 0xe9b6c7aa); /* 20 */
+        GG(a, b, c, d, x[5], 5, 0xd62f105d); /* 21 */
+        GG(d, a, b, c, x[10], 9, 0x2441453); /* 22 */
+        GG(c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */
+        GG(b, c, d, a, x[4], 20, 0xe7d3fbc8); /* 24 */
+        GG(a, b, c, d, x[9], 5, 0x21e1cde6); /* 25 */
+        GG(d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */
+        GG(c, d, a, b, x[3], 14, 0xf4d50d87); /* 27 */
+        GG(b, c, d, a, x[8], 20, 0x455a14ed); /* 28 */
+        GG(a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */
+        GG(d, a, b, c, x[2], 9, 0xfcefa3f8); /* 30 */
+        GG(c, d, a, b, x[7], 14, 0x676f02d9); /* 31 */
+        GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */
+
+        /* Round 3 */
+        HH(a, b, c, d, x[5], 4, 0xfffa3942); /* 33 */
+        HH(d, a, b, c, x[8], 11, 0x8771f681); /* 34 */
+        HH(c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */
+        HH(b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */
+        HH(a, b, c, d, x[1], 4, 0xa4beea44); /* 37 */
+        HH(d, a, b, c, x[4], 11, 0x4bdecfa9); /* 38 */
+        HH(c, d, a, b, x[7], 16, 0xf6bb4b60); /* 39 */
+        HH(b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */
+        HH(a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */
+        HH(d, a, b, c, x[0], 11, 0xeaa127fa); /* 42 */
+        HH(c, d, a, b, x[3], 16, 0xd4ef3085); /* 43 */
+        HH(b, c, d, a, x[6], 23, 0x4881d05); /* 44 */
+        HH(a, b, c, d, x[9], 4, 0xd9d4d039); /* 45 */
+        HH(d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */
+        HH(c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */
+        HH(b, c, d, a, x[2], 23, 0xc4ac5665); /* 48 */
+
+        /* Round 4 */
+        II(a, b, c, d, x[0], 6, 0xf4292244); /* 49 */
+        II(d, a, b, c, x[7], 10, 0x432aff97); /* 50 */
+        II(c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */
+        II(b, c, d, a, x[5], 21, 0xfc93a039); /* 52 */
+        II(a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */
+        II(d, a, b, c, x[3], 10, 0x8f0ccc92); /* 54 */
+        II(c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */
+        II(b, c, d, a, x[1], 21, 0x85845dd1); /* 56 */
+        II(a, b, c, d, x[8], 6, 0x6fa87e4f); /* 57 */
+        II(d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */
+        II(c, d, a, b, x[6], 15, 0xa3014314); /* 59 */
+        II(b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */
+        II(a, b, c, d, x[4], 6, 0xf7537e82); /* 61 */
+        II(d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */
+        II(c, d, a, b, x[2], 15, 0x2ad7d2bb); /* 63 */
+        II(b, c, d, a, x[9], 21, 0xeb86d391); /* 64 */
+        state[0] += a;
+        state[1] += b;
+        state[2] += c;
+        state[3] += d;
     }
 
-    fileClose(fd);
-    MD5Final(md5, md5_value);
 
-    for(int i = 0; i < MD5_SIZE; i++)
-        snprintf(md5str + i * 2, 2 + 1, "%02x", md5_value[i]);
+    template<typename T>
+    T getFileMd5(T &path){
+        FILE *fd;
 
-    return md5str;
-}
+        unsigned long ret;
+        unsigned char data[READ_DATA_SIZE];
+        unsigned char md5_value[MD5_SIZE];
+
+        if ((fd = fileOpen(path, "rb")) == nullptr)
+            throw FileOpenException(path);
+
+        char *md5str = calloc(MD5_STRING, char);
+        MD5_CTX *md5 = MD5Init();
+        while (true) {
+            ret = fread(data, 1, READ_DATA_SIZE, fd);
+            MD5Update(md5, data, ret);
+            if (ret < READ_DATA_SIZE)
+                break;
+        }
+
+        fileClose(fd);
+        MD5Final(md5, md5_value);
+
+        for (int i = 0; i < MD5_SIZE; i++)
+            snprintf(md5str + i * 2, 2 + 1, "%02x", md5_value[i]);
+
+        return md5str;
+    }
 
-template AFUN_TOOL_EXPORT char *aFuntool::getFileMd5(char *&path);
-template AFUN_TOOL_EXPORT std::string aFuntool::getFileMd5(std::string &path);
+    template AFUN_TOOL_EXPORT char *getFileMd5(char *&path);
+    template AFUN_TOOL_EXPORT std::string getFileMd5(std::string &path);
+}

+ 67 - 64
src/tool/regex.cpp

@@ -8,84 +8,87 @@
 #define PCRE2_CODE_UNIT_WIDTH 8
 #include "pcre2.h"
 #include "regex.h"
-using namespace aFuntool;
 
-aFuntool::Regex::Regex(std::string pattern_) : pattern {std::move(pattern_)} {
-    if (!isCharUTF8(pattern))
-        throw RegexException("Pattern not utf-8");
+namespace aFuntool {
+    Regex::Regex(std::string pattern_) : pattern{std::move(pattern_)}{
+        if (!isCharUTF8(pattern))
+            throw RegexException("Pattern not utf-8");
 
-    int error_code;
-    size_t erroroffset;
-    char regex_error[REGEX_ERROR_SIZE];
+        int error_code;
+        size_t erroroffset;
+        char regex_error[REGEX_ERROR_SIZE];
 
-    this->re = pcre2_compile((PCRE2_SPTR)pattern.c_str(), PCRE2_ZERO_TERMINATED, 0, &error_code, &erroroffset, nullptr);
-    if (re == nullptr) {
-        PCRE2_UCHAR buffer[256];
-        pcre2_get_error_message(error_code, buffer, sizeof(buffer));
-        snprintf(regex_error, sizeof(regex_error), "R%d: %s\n", (int) erroroffset, buffer);
-        throw RegexException(regex_error);
+        this->re = pcre2_compile((PCRE2_SPTR) pattern.c_str(), PCRE2_ZERO_TERMINATED, 0, &error_code, &erroroffset,
+                                 nullptr);
+        if (re == nullptr) {
+            PCRE2_UCHAR buffer[256];
+            pcre2_get_error_message(error_code, buffer, sizeof(buffer));
+            snprintf(regex_error, sizeof(regex_error), "R%d: %s\n", (int) erroroffset, buffer);
+            throw RegexException(regex_error);
+        }
     }
-}
 
-Regex::Regex(const Regex &regex){
-    int error_code;
-    size_t erroroffset;
-    char regex_error[REGEX_ERROR_SIZE];
+    Regex::Regex(const Regex &regex){
+        int error_code;
+        size_t erroroffset;
+        char regex_error[REGEX_ERROR_SIZE];
+
+        this->re = pcre2_compile((PCRE2_SPTR) regex.pattern.c_str(), PCRE2_ZERO_TERMINATED, 0, &error_code,
+                                 &erroroffset, nullptr);
+        if (re == nullptr) {
+            PCRE2_UCHAR buffer[256];
+            pcre2_get_error_message(error_code, buffer, sizeof(buffer));
+            snprintf(regex_error, sizeof(regex_error), "R%d: %s\n", (int) erroroffset, buffer);
+            throw RegexException(regex_error);
+        }
+    }
 
-    this->re = pcre2_compile((PCRE2_SPTR)regex.pattern.c_str(), PCRE2_ZERO_TERMINATED, 0, &error_code, &erroroffset, nullptr);
-    if (re == nullptr) {
-        PCRE2_UCHAR buffer[256];
-        pcre2_get_error_message(error_code, buffer, sizeof(buffer));
-        snprintf(regex_error, sizeof(regex_error), "R%d: %s\n", (int) erroroffset, buffer);
-        throw RegexException(regex_error);
+    Regex::~Regex(){
+        if (re != nullptr)
+            pcre2_code_free(re);
     }
-}
 
-aFuntool::Regex::~Regex() {
-    if (re != nullptr)
-        pcre2_code_free(re);
-}
+    /**
+     * 函数名: matchRegex
+     * 目标: 检查一个字符串是否可被完全匹配一个正则表达式
+     * 返回  (1) - 可完全匹配
+     * 返回  (0) - 不可完全匹配或不可匹配
+     * 返回 (>0) - 失败
+     */
+    int Regex::match(const char *subject) const{
+        if (!isCharUTF8(subject))
+            throw RegexException("Subject not utf-8");
 
-/*
- * 函数名: matchRegex
- * 目标: 检查一个字符串是否可被完全匹配一个正则表达式
- * 返回  (1) - 可完全匹配
- * 返回  (0) - 不可完全匹配或不可匹配
- * 返回 (>0) - 失败
- */
-int aFuntool::Regex::match(const char *subject) const {
-    if (!isCharUTF8(subject))
-        throw RegexException("Subject not utf-8");
+        char regex_error[REGEX_ERROR_SIZE];
+        PCRE2_SIZE sub_len = strlen(subject);
+        pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(re, nullptr);
+        int rc = pcre2_match(re, (PCRE2_SPTR) subject, sub_len, 0, 0, match_data, nullptr);
 
-    char regex_error[REGEX_ERROR_SIZE];
-    PCRE2_SIZE sub_len = strlen(subject);
-    pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(re, nullptr);
-    int rc = pcre2_match(re, (PCRE2_SPTR)subject, sub_len, 0, 0, match_data, nullptr);
+        if (rc < 0) {
+            pcre2_match_data_free(match_data);
+            if (rc == PCRE2_ERROR_NOMATCH)
+                return 0;
+            else {
+                snprintf(regex_error, sizeof(regex_error),
+                         "Regex match '%s' failed by '%s'\n", subject, pattern.c_str());
+                throw RegexException(regex_error);
+            }
+        }
 
-    if (rc < 0) {
-        pcre2_match_data_free(match_data);
-        if (rc == PCRE2_ERROR_NOMATCH)
-            return 0;
-        else {
+        PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
+        if (ovector[0] > ovector[1]) {
             snprintf(regex_error, sizeof(regex_error),
-                     "Regex match '%s' failed by '%s'\n", subject, pattern.c_str());
+                     "\\K was used in an assertion to set the match start after its end.\n"
+                     "From end to start the match was: %.*s\n",
+                     (int) (ovector[0] - ovector[1]), (char *) (subject + ovector[1]));
+            pcre2_match_data_free(match_data);
             throw RegexException(regex_error);
         }
-    }
 
-    PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
-    if (ovector[0] > ovector[1]) {
-        snprintf(regex_error, sizeof(regex_error),
-                 "\\K was used in an assertion to set the match start after its end.\n"
-                 "From end to start the match was: %.*s\n",
-                 (int) (ovector[0] - ovector[1]), (char *) (subject + ovector[1]));
+        int ret = 0;
+        if (ovector[0] == 0 && ovector[1] == sub_len) // 完全匹配
+            ret = 1;
         pcre2_match_data_free(match_data);
-        throw RegexException(regex_error);
+        return ret;
     }
-
-    int ret = 0;
-    if (ovector[0] == 0 && ovector[1] == sub_len) // 完全匹配
-        ret = 1;
-    pcre2_match_data_free(match_data);
-    return ret;
-}
+}

+ 413 - 412
src/tool/stdio_.cpp

@@ -8,7 +8,6 @@
 #include "tool.h"
 #include "stdio_.h"
 #include "mutex"
-using namespace aFuntool;
 
 /* 注意:
  * checkStdin在Windows和Linux之前行为具有差别, 本质目标时检查缓冲区是否有内容
@@ -25,436 +24,439 @@ using namespace aFuntool;
 // 获取CodePage, 并将内存中utf-8字符串转换为对应编码输出
 // cygwin环境下, 终端默认为uft-8
 
-const int BUFF_SIZE = 40960;
-static char buffer[BUFF_SIZE + 1] = "";
-static size_t index = 0;
-static size_t next = 0;
-static size_t end = 0;
-volatile sig_atomic_t ctrl_c = 0;
-static std::mutex buffer_mutex;  // 只有 export 的函数统一处理该互斥锁
-
-static int setCursorPosition(HANDLE std_o, CONSOLE_SCREEN_BUFFER_INFO *info_, SHORT x_) {
-    CONSOLE_SCREEN_BUFFER_INFO info;
-    if (info_ == nullptr) {
-        if (!GetConsoleScreenBufferInfo(std_o, &info))
-            return -1;
-        info_ = &info;
-    }
-    int x = info_->dwCursorPosition.X;
-    int y = info_->dwCursorPosition.Y;
-
-    x += x_;
-    while (x >= info_->dwSize.X) {
-        x -= info_->dwSize.X;
-        y++;
-    }
-
-    while (x < 0) {
-        x += info_->dwSize.X;
-        y--;
-    }
-
-    if (y < 0)
-        y = 0;
-    else if (y > info_->dwSize.Y)
-        y = info_->dwSize.Y;
+namespace aFuntool {
+    const int BUFF_SIZE = 40960;
+    static char buffer[BUFF_SIZE + 1] = "";
+    static size_t index = 0;
+    static size_t next = 0;
+    static size_t end = 0;
+    volatile sig_atomic_t ctrl_c = 0;
+    static std::mutex buffer_mutex;  // 只有 export 的函数统一处理该互斥锁
+
+    static int setCursorPosition(HANDLE std_o, CONSOLE_SCREEN_BUFFER_INFO *info_, SHORT x_){
+        CONSOLE_SCREEN_BUFFER_INFO info;
+        if (info_ == nullptr) {
+            if (!GetConsoleScreenBufferInfo(std_o, &info))
+                return -1;
+            info_ = &info;
+        }
+        int x = info_->dwCursorPosition.X;
+        int y = info_->dwCursorPosition.Y;
 
-    COORD coord = {.X=(SHORT)x, .Y=(SHORT)y};
-    SetConsoleCursorPosition(std_o, coord);
-    return 1;
-}
+        x += x_;
+        while (x >= info_->dwSize.X) {
+            x -= info_->dwSize.X;
+            y++;
+        }
 
-static int nextToEnd(HANDLE std_o) {
-    CONSOLE_SCREEN_BUFFER_INFO info;
-    if (!GetConsoleScreenBufferInfo(std_o, &info))
-        return 0;
-    if (setCursorPosition(std_o, &info, (SHORT)(end - next)) == -1)
-        return 0;
-    next = end;
-    return 1;
-}
+        while (x < 0) {
+            x += info_->dwSize.X;
+            y--;
+        }
 
-static int moveBuffer() {
-    if (index == 0)
-        return 0;
-    memmove(buffer, buffer + index, BUFF_SIZE - index);
-    end = end - index;
-    next = next - index;
-    index = 0;
-    memset(buffer + end, 0, BUFF_SIZE - end);
-    return 1;
-}
+        if (y < 0)
+            y = 0;
+        else if (y > info_->dwSize.Y)
+            y = info_->dwSize.Y;
 
-static int backChar(HANDLE std_o) {
-    if (index != next) {  // 删除一个字符
-        if (setCursorPosition(std_o, nullptr, -1) == -1)  // 先一定位置在-1
-            return 0;
+        COORD coord = {.X=(SHORT) x, .Y=(SHORT) y};
+        SetConsoleCursorPosition(std_o, coord);
+        return 1;
+    }
 
+    static int nextToEnd(HANDLE std_o){
         CONSOLE_SCREEN_BUFFER_INFO info;
         if (!GetConsoleScreenBufferInfo(std_o, &info))
             return 0;
-        memmove(buffer + next - 1, buffer + next, end - next + 1);
+        if (setCursorPosition(std_o, &info, (SHORT) (end - next)) == -1)
+            return 0;
+        next = end;
+        return 1;
+    }
 
-        SetConsoleCursorPosition(std_o, info.dwCursorPosition);
-        for (size_t n = next - 1; n < end; n++)
-            fputc(' ', stdout);
+    static int moveBuffer(){
+        if (index == 0)
+            return 0;
+        memmove(buffer, buffer + index, BUFF_SIZE - index);
+        end = end - index;
+        next = next - index;
+        index = 0;
+        memset(buffer + end, 0, BUFF_SIZE - end);
+        return 1;
+    }
 
-        SetConsoleCursorPosition(std_o, info.dwCursorPosition);
-        fputs(buffer + next - 1, stdout);
+    static int backChar(HANDLE std_o){
+        if (index != next) {  // 删除一个字符
+            if (setCursorPosition(std_o, nullptr, -1) == -1)  // 先一定位置在-1
+                return 0;
 
-        SetConsoleCursorPosition(std_o, info.dwCursorPosition);
-        next--;
-        end--;
-    }
-    return 1;
-}
+            CONSOLE_SCREEN_BUFFER_INFO info;
+            if (!GetConsoleScreenBufferInfo(std_o, &info))
+                return 0;
+            memmove(buffer + next - 1, buffer + next, end - next + 1);
 
-static int enterChar(HANDLE std_o) {
-    if(!nextToEnd(std_o))
-        return 0;
-    buffer[end] = '\n';
-    end++;
-    next++;
-    fputc('\n', stdout);
-    return 1;
-}
+            SetConsoleCursorPosition(std_o, info.dwCursorPosition);
+            for (size_t n = next - 1; n < end; n++)
+                fputc(' ', stdout);
 
-/*
- * 函数名: newChar
- * 目标: 记录字符并显示
- * 返回1表示成功
- * 返回0表示失败
- */
-static int newChar(HANDLE std_i, char ch) {
-    if (ch == 0)
+            SetConsoleCursorPosition(std_o, info.dwCursorPosition);
+            fputs(buffer + next - 1, stdout);
+
+            SetConsoleCursorPosition(std_o, info.dwCursorPosition);
+            next--;
+            end--;
+        }
         return 1;
-    if (end == BUFF_SIZE && !moveBuffer())  // 对比 end 而不是 next
-        return 0;
+    }
 
-    if (next != end) {  // insert 模式
-        CONSOLE_SCREEN_BUFFER_INFO info;
-        if (!GetConsoleScreenBufferInfo(std_i, &info))
+    static int enterChar(HANDLE std_o){
+        if (!nextToEnd(std_o))
             return 0;
-        memmove(buffer + next + 1, buffer + next, end - next);
-        buffer[next] = ch;
-        fputs(buffer + next, stdout);
-        if (setCursorPosition(std_i, &info, 1) == -1)
+        buffer[end] = '\n';
+        end++;
+        next++;
+        fputc('\n', stdout);
+        return 1;
+    }
+
+    /*
+     * 函数名: newChar
+     * 目标: 记录字符并显示
+     * 返回1表示成功
+     * 返回0表示失败
+     */
+    static int newChar(HANDLE std_i, char ch){
+        if (ch == 0)
+            return 1;
+        if (end == BUFF_SIZE && !moveBuffer())  // 对比 end 而不是 next
             return 0;
-    } else {
-        buffer[next] = ch;
-        fputc(ch, stdout);
+
+        if (next != end) {  // insert 模式
+            CONSOLE_SCREEN_BUFFER_INFO info;
+            if (!GetConsoleScreenBufferInfo(std_i, &info))
+                return 0;
+            memmove(buffer + next + 1, buffer + next, end - next);
+            buffer[next] = ch;
+            fputs(buffer + next, stdout);
+            if (setCursorPosition(std_i, &info, 1) == -1)
+                return 0;
+        } else {
+            buffer[next] = ch;
+            fputc(ch, stdout);
+        }
+
+        next++;
+        end++;
+        return 1;
     }
 
-    next++;
-    end++;
-    return 1;
-}
+    /*
+     * 函数名: checkNewInput
+     * 目标: 获取输入并且显示
+     * 返回-1表示遭遇错误
+     * 返回0表示未完成行读取
+     * 返回1表示完成行读取
+     */
+    static int checkNewInput(HANDLE std_i, HANDLE std_o){
+        DWORD len = 0;
+        DWORD oldm;
+        if (!GetConsoleMode(std_i, &oldm))
+            return -1;
 
-/*
- * 函数名: checkNewInput
- * 目标: 获取输入并且显示
- * 返回-1表示遭遇错误
- * 返回0表示未完成行读取
- * 返回1表示完成行读取
- */
-static int checkNewInput(HANDLE std_i, HANDLE std_o) {
-    DWORD len = 0;
-    DWORD oldm;
-    if (!GetConsoleMode(std_i, &oldm))
-        return -1;
-
-    if (!GetNumberOfConsoleInputEvents(std_i, &len))
-        return -1;
-
-    for (int i = 0; i < len; i++) {
-        INPUT_RECORD record;
-        DWORD read_len;
-        if (!ReadConsoleInputA(std_i, &record, 1, &read_len) || read_len == 0)
+        if (!GetNumberOfConsoleInputEvents(std_i, &len))
             return -1;
-        if (record.EventType == KEY_EVENT) {
-            if (!record.Event.KeyEvent.bKeyDown)
-                continue;
-            else if (record.Event.KeyEvent.uChar.AsciiChar == 3) {
-                ctrl_c = 1;
-                continue;
-            } else if (record.Event.KeyEvent.wVirtualKeyCode == VK_BACK) {  // 退格
-                if (backChar(std_o) == 0)
-                    return -1;
-                continue;
-            } if (record.Event.KeyEvent.wVirtualKeyCode == VK_RETURN) {  // 回车
-                if (enterChar(std_o) == 0)
-                    return -1;
-                return 1;
-            } else if (record.Event.KeyEvent.wVirtualKeyCode == VK_LEFT) {  // 左
-                CONSOLE_SCREEN_BUFFER_INFO info;
-                if (!GetConsoleScreenBufferInfo(std_o, &info))
-                    return -1;
-                if (next > index) {
-                    next--;
-                    if (setCursorPosition(std_o, nullptr, -1) == -1)
-                        return 0;
+
+        for (int i = 0; i < len; i++) {
+            INPUT_RECORD record;
+            DWORD read_len;
+            if (!ReadConsoleInputA(std_i, &record, 1, &read_len) || read_len == 0)
+                return -1;
+            if (record.EventType == KEY_EVENT) {
+                if (!record.Event.KeyEvent.bKeyDown)
+                    continue;
+                else if (record.Event.KeyEvent.uChar.AsciiChar == 3) {
+                    ctrl_c = 1;
+                    continue;
+                } else if (record.Event.KeyEvent.wVirtualKeyCode == VK_BACK) {  // 退格
+                    if (backChar(std_o) == 0)
+                        return -1;
+                    continue;
                 }
-                return 0;
-            } else if (record.Event.KeyEvent.wVirtualKeyCode == VK_RIGHT) {  // 右
-                if (next < end) {
-                    next++;
-                    if(setCursorPosition(std_o, nullptr, 1) == -1)
-                        return 0;
+                if (record.Event.KeyEvent.wVirtualKeyCode == VK_RETURN) {  // 回车
+                    if (enterChar(std_o) == 0)
+                        return -1;
+                    return 1;
+                } else if (record.Event.KeyEvent.wVirtualKeyCode == VK_LEFT) {  // 左
+                    CONSOLE_SCREEN_BUFFER_INFO info;
+                    if (!GetConsoleScreenBufferInfo(std_o, &info))
+                        return -1;
+                    if (next > index) {
+                        next--;
+                        if (setCursorPosition(std_o, nullptr, -1) == -1)
+                            return 0;
+                    }
+                    return 0;
+                } else if (record.Event.KeyEvent.wVirtualKeyCode == VK_RIGHT) {  // 右
+                    if (next < end) {
+                        next++;
+                        if (setCursorPosition(std_o, nullptr, 1) == -1)
+                            return 0;
+                    }
+                    return 0;
                 }
-                return 0;
-            }
 
-            for (int r = record.Event.KeyEvent.wRepeatCount; r > 0; r--) {
-                if (newChar(std_o, record.Event.KeyEvent.uChar.AsciiChar) == 0)
-                    return -1;
+                for (int r = record.Event.KeyEvent.wRepeatCount; r > 0; r--) {
+                    if (newChar(std_o, record.Event.KeyEvent.uChar.AsciiChar) == 0)
+                        return -1;
+                }
             }
         }
+        return 0;
     }
-    return 0;
-}
 
-static int fcheck_stdin(HANDLE std_i, HANDLE std_o) {
-    if (end == index || end == 0 || buffer[end - 1] != '\n')
-        return checkNewInput(std_i, std_o);
-    return 1;
-}
-
-int aFuntool::fgetc_stdin() {
-    if (!_isatty(_fileno(stdin)))
-        return fgetc(stdin);
+    static int fcheck_stdin(HANDLE std_i, HANDLE std_o){
+        if (end == index || end == 0 || buffer[end - 1] != '\n')
+            return checkNewInput(std_i, std_o);
+        return 1;
+    }
 
-    HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
-    HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
-    if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
-        return EOF;
+    int fgetc_stdin(){
+        if (!_isatty(_fileno(stdin)))
+            return fgetc(stdin);
 
-    int re = EOF;
-    std::unique_lock<std::mutex> ul{buffer_mutex};
-    for (int fs = 0; fs != 1 ; fs = fcheck_stdin(std_i, std_o)) {  // 阻塞
-        if (fs == -1)
+        HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
+        HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
+        if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
             return EOF;
-    }
 
-    re = (unsigned char)buffer[index];
-    index++;
-    return re;
-}
+        int re = EOF;
+        std::unique_lock<std::mutex> ul{buffer_mutex};
+        for (int fs = 0; fs != 1; fs = fcheck_stdin(std_i, std_o)) {  // 阻塞
+            if (fs == -1)
+                return EOF;
+        }
 
-char *aFuntool::fgets_stdin_(char *buf, size_t len) {
-    if (!_isatty(_fileno(stdin)))
-        return fgets(buf, (int)len, stdin);
+        re = (unsigned char) buffer[index];
+        index++;
+        return re;
+    }
 
-    HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
-    HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
-    if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
-        return nullptr;
+    char *fgets_stdin_(char *buf, size_t len){
+        if (!_isatty(_fileno(stdin)))
+            return fgets(buf, (int) len, stdin);
 
-    std::unique_lock<std::mutex> ul{buffer_mutex};
-    for (int fs = 0; fs != 1 ; fs = fcheck_stdin(std_i, std_o)) {  // 阻塞
-        if (fs == -1) {
-            buf = nullptr;
+        HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
+        HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
+        if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE)
             return nullptr;
+
+        std::unique_lock<std::mutex> ul{buffer_mutex};
+        for (int fs = 0; fs != 1; fs = fcheck_stdin(std_i, std_o)) {  // 阻塞
+            if (fs == -1) {
+                buf = nullptr;
+                return nullptr;
+            }
         }
-    }
 
-    {
-        size_t len_ = len - 1;
-        if (end - index < len_)
-            len_ = end - index;
-        memcpy(buf, buffer + index, len_);
-        index += len_;
-        nextToEnd(std_o);
-        buf[len_] = '\0';  // 最后一位
+        {
+            size_t len_ = len - 1;
+            if (end - index < len_)
+                len_ = end - index;
+            memcpy(buf, buffer + index, len_);
+            index += len_;
+            nextToEnd(std_o);
+            buf[len_] = '\0';  // 最后一位
+        }
+
+        return buf;
     }
 
-    return buf;
-}
+    bool fclear_stdin(){
+        if (!_isatty(_fileno(stdin))) {
+            rewind(stdin);  // 仅 winAPI 可用
+            return true;
+        }
 
-bool aFuntool::fclear_stdin() {
-    if (!_isatty(_fileno(stdin))) {
-        rewind(stdin);  // 仅 winAPI 可用
-        return true;
-    }
+        HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
+        if (std_o == INVALID_HANDLE_VALUE)
+            return true;
 
-    HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
-    if (std_o == INVALID_HANDLE_VALUE)
-        return true;
+        std::unique_lock<std::mutex> ul{buffer_mutex};
+        nextToEnd(std_o);
+        index = 0;
+        end = 0;
+        next = 0;
+        memset(buffer, 0, BUFF_SIZE);
+        return false;
+    }
 
-    std::unique_lock<std::mutex> ul{buffer_mutex};
-    nextToEnd(std_o);
-    index = 0;
-    end = 0;
-    next = 0;
-    memset(buffer, 0, BUFF_SIZE);
-    return false;
-}
+    /**
+     * 接管ctrl+c信号初始化
+     * @param signal 初始化/还原
+     */
+    void stdio_signal_init(bool signal){
+        HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
+        DWORD mode;
+        GetConsoleMode(std_i, &mode);
+        if (signal)
+            mode &= ~ENABLE_PROCESSED_INPUT;
+        else
+            mode |= ENABLE_PROCESSED_INPUT;  // 系统接管 ^c
+        SetConsoleMode(std_i, mode);
+    }
 
-/**
- * 接管ctrl+c信号初始化
- * @param signal 初始化/还原
- */
-void aFuntool::stdio_signal_init(bool signal) {
-    HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
-    DWORD  mode;
-    GetConsoleMode(std_i, &mode);
-    if (signal)
-        mode &= ~ENABLE_PROCESSED_INPUT;
-    else
-        mode |= ENABLE_PROCESSED_INPUT;  // 系统接管 ^c
-    SetConsoleMode(std_i, mode);
-}
+    /**
+     * 检查是否有ctrl+c信号
+     */
+    bool stdio_check_signal(){
+        HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
+        HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
+        if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE) {
+            return false;
+        }
 
-/**
- * 检查是否有ctrl+c信号
- */
-bool aFuntool::stdio_check_signal() {
-    HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
-    HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
-    if (std_i == INVALID_HANDLE_VALUE || std_o == INVALID_HANDLE_VALUE) {
-        return false;
+        std::unique_lock<std::mutex> ul{buffer_mutex};
+        fcheck_stdin(std_i, std_o);
+        bool res = ctrl_c == 1;
+        ctrl_c = 0;
+        return res;
     }
 
-    std::unique_lock<std::mutex> ul{buffer_mutex};
-    fcheck_stdin(std_i, std_o);
-    bool res = ctrl_c == 1;
-    ctrl_c = 0;
-    return res;
-}
+    int convertMultiByte(char **dest, const char *str, UINT from, UINT to){
+        if (str == nullptr || dest == nullptr)
+            return 0;
 
-int aFuntool::convertMultiByte(char **dest, const char *str, UINT from, UINT to) {
-    if (str == nullptr || dest == nullptr)
-        return 0;
+        int tmp_len = MultiByteToWideChar(from, 0, str, -1, nullptr, 0);
+        if (tmp_len == 0)
+            return 0;
 
-    int tmp_len = MultiByteToWideChar(from, 0, str, -1, nullptr, 0);
-    if (tmp_len == 0)
-        return 0;
+        auto tmp = calloc(tmp_len + 1, wchar_t);
+        if (MultiByteToWideChar(from, 0, str, -1, tmp, tmp_len) == 0)
+            return 0;
 
-    auto tmp = calloc(tmp_len + 1, wchar_t);
-    if (MultiByteToWideChar(from, 0, str, -1, tmp, tmp_len) == 0)
-        return 0;
+        int dest_len = WideCharToMultiByte(to, 0, tmp, -1, nullptr, 0, nullptr, nullptr);
+        if (dest_len == 0)
+            return 0;
 
-    int dest_len = WideCharToMultiByte(to, 0, tmp, -1, nullptr, 0, nullptr, nullptr);
-    if (dest_len == 0)
-        return 0;
+        *dest = calloc(dest_len + 1, char);
+        int re = WideCharToMultiByte(to, 0, tmp, -1, *dest, dest_len, nullptr, nullptr);
 
-    *dest = calloc(dest_len + 1, char);
-    int re = WideCharToMultiByte(to, 0, tmp, -1, *dest, dest_len, nullptr, nullptr);
+        free(tmp);
+        return re;
+    }
 
-    free(tmp);
-    return re;
-}
+    int convertWideByte(wchar_t **dest, const char *str, UINT from){
+        if (str == nullptr || dest == nullptr)
+            return 0;
 
-int aFuntool::convertWideByte(wchar_t **dest, const char *str, UINT from) {
-    if (str == nullptr || dest == nullptr)
-        return 0;
+        int tmp_len = MultiByteToWideChar(from, 0, str, -1, nullptr, 0);
+        if (tmp_len == 0)
+            return 0;
 
-    int tmp_len = MultiByteToWideChar(from, 0, str, -1, nullptr, 0);
-    if (tmp_len == 0)
-        return 0;
+        *dest = calloc(tmp_len + 1, wchar_t);
+        return MultiByteToWideChar(from, 0, str, -1, *dest, tmp_len);
+    }
 
-    *dest = calloc(tmp_len + 1, wchar_t);
-    return MultiByteToWideChar(from, 0, str, -1, *dest, tmp_len);
-}
+    int convertFromWideByte(char **dest, const wchar_t *str, UINT to){
+        if (str == nullptr || dest == nullptr)
+            return 0;
 
-int aFuntool::convertFromWideByte(char **dest, const wchar_t *str, UINT to) {
-    if (str == nullptr || dest == nullptr)
-        return 0;
+        int dest_len = WideCharToMultiByte(to, 0, str, -1, nullptr, 0, nullptr, nullptr);
+        if (dest_len == 0)
+            return 0;
 
-    int dest_len = WideCharToMultiByte(to, 0, str, -1, nullptr, 0, nullptr, nullptr);
-    if (dest_len == 0)
-        return 0;
+        *dest = calloc(dest_len + 1, char);
+        return WideCharToMultiByte(to, 0, str, -1, *dest, dest_len, nullptr, nullptr);
+    }
 
-    *dest = calloc(dest_len + 1, char);
-    return WideCharToMultiByte(to, 0, str, -1, *dest, dest_len, nullptr, nullptr);
-}
+    int fgets_stdin(char **dest, int len){
+        int re = 0;
+        if (!_isatty(_fileno(stdin))) {
+            *dest = calloc(len + 1, char);
+            re = fgets(*dest, len, stdin) != nullptr;
+            if (!re)
+                free(*dest);
+            return re;
+        }
 
-int aFuntool::fgets_stdin(char **dest, int len) {
-    int re = 0;
-    if (!_isatty(_fileno(stdin))) {
-        *dest = calloc(len + 1, char);
-        re = fgets(*dest, len, stdin) != nullptr;
-        if (!re)
-            free(*dest);
+        char *wstr = calloc(len, char);
+        UINT code_page = GetConsoleCP();
+        if (fgets_stdin_(wstr, len) != nullptr)  // 已经有互斥锁
+            re = convertMultiByte(dest, wstr, code_page, CP_UTF8);
         return re;
     }
 
-    char *wstr = calloc(len, char);
-    UINT code_page = GetConsoleCP();
-    if (fgets_stdin_(wstr, len) != nullptr)  // 已经有互斥锁
-        re = convertMultiByte(dest, wstr, code_page, CP_UTF8);
-    return re;
-}
+    int fungetc_stdin(int ch){
+        if (!_isatty(_fileno(stdin)))
+            return ungetc(ch, stdin);
 
-int aFuntool::fungetc_stdin(int ch) {
-    if (!_isatty(_fileno(stdin)))
-        return ungetc(ch, stdin);
+        std::unique_lock<std::mutex> ul{buffer_mutex};
+        if (ch == 0 || index == 0 && end == BUFF_SIZE) {
+            return 0;
+        }
 
-    std::unique_lock<std::mutex> ul{buffer_mutex};
-    if (ch == 0 || index == 0 && end == BUFF_SIZE) {
-        return 0;
-    }
+        if (index != 0) {
+            index--;
+            buffer[index] = (char) ch;
+        } else if (end != BUFF_SIZE) {  // index == 0;
+            memmove(buffer, buffer + 1, end);  // 往回移动
+            end++;
+            next++;
+            buffer[0] = (char) ch;
+        }
 
-    if (index != 0) {
-        index--;
-        buffer[index] = (char)ch;
-    } else if (end != BUFF_SIZE) {  // index == 0;
-        memmove(buffer, buffer + 1, end);  // 往回移动
-        end++;
-        next++;
-        buffer[0] = (char) ch;
+        return 1;
     }
 
-    return 1;
-}
-
-/*
- * 函数名: checkStdin
- * 目标: 检查stdin缓冲区是否有内容
- * 有内容则返回true
- * 无内容则返回false
- */
-bool aFuntool::checkStdin() {
-    HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
-    HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
-    std::unique_lock<std::mutex> ul{buffer_mutex};
-    if (fcheck_stdin(std_i, std_o) == 0)
-        return false;
-    return true;
-}
+    /*
+     * 函数名: checkStdin
+     * 目标: 检查stdin缓冲区是否有内容
+     * 有内容则返回true
+     * 无内容则返回false
+     */
+    bool checkStdin(){
+        HANDLE std_i = GetStdHandle(STD_INPUT_HANDLE);
+        HANDLE std_o = GetStdHandle(STD_OUTPUT_HANDLE);
+        std::unique_lock<std::mutex> ul{buffer_mutex};
+        if (fcheck_stdin(std_i, std_o) == 0)
+            return false;
+        return true;
+    }
 
-int aFuntool::fputs_std_(const char *str, FILE *std) {
-    if (std == nullptr)
-        return 0;
+    int fputs_std_(const char *str, FILE *std){
+        if (std == nullptr)
+            return 0;
 
-    if (!_isatty(_fileno(std)))
-        return fputs(str, std);
+        if (!_isatty(_fileno(std)))
+            return fputs(str, std);
 
-    UINT code_page = GetConsoleCP();
-    char *wstr = nullptr;
-    int re = EOF;
-    if (convertMultiByte(&wstr, str, CP_UTF8, code_page) == 0 || wstr != nullptr) {
-        re = fputs(wstr, std);
-        free(wstr);
+        UINT code_page = GetConsoleCP();
+        char *wstr = nullptr;
+        int re = EOF;
+        if (convertMultiByte(&wstr, str, CP_UTF8, code_page) == 0 || wstr != nullptr) {
+            re = fputs(wstr, std);
+            free(wstr);
+        }
+        return re;
     }
-    return re;
-}
 
-size_t aFuntool::vprintf_std_(FILE *std, size_t buf_len, const char *format, va_list ap) {
-    if (std == nullptr)
-        return 0;
+    size_t vprintf_std_(FILE *std, size_t buf_len, const char *format, va_list ap){
+        if (std == nullptr)
+            return 0;
 
-    if (!_isatty(_fileno(std)))
-        return vfprintf(std, format, ap);
-
-    if (buf_len == 0)
-        buf_len = 1024;
-    buf_len += 10;  // 预留更多位置
-    char *buf = calloc(buf_len, char);
-    size_t re = vsnprintf(buf, buf_len, format, ap);
-    if (fputs_std_(buf, std) == EOF)
-        re = 0;
-    free(buf);
-    return re;
+        if (!_isatty(_fileno(std)))
+            return vfprintf(std, format, ap);
+
+        if (buf_len == 0)
+            buf_len = 1024;
+        buf_len += 10;  // 预留更多位置
+        char *buf = calloc(buf_len, char);
+        size_t re = vsnprintf(buf, buf_len, format, ap);
+        if (fputs_std_(buf, std) == EOF)
+            re = 0;
+        free(buf);
+        return re;
+    }
 }
 
 #else
@@ -463,62 +465,61 @@ size_t aFuntool::vprintf_std_(FILE *std, size_t buf_len, const char *format, va_
 
 namespace aFuntool {
     static std::mutex fcntl_mutex;  // 只有 export 的函数统一处理该互斥锁
-}
-
-// 用于Linux平台的IO函数
-// 默认Linux平台均使用utf-8
-
-int aFuntool::fgets_stdin(char **dest, int len) {
-    *dest = calloc(len, char);
-    if (fgets(*dest, len, stdin) == nullptr)
-        return 0;
-    return 1;
-}
-/*
- * 函数名: checkStdin
- * 目标: 检查stdin缓冲区是否有内容
- * 有内容则返回true
- * 无内容则返回false
- *
- * 参考自: https://gist.github.com/SuperH-0630/a4190b89d21c349a8d6882ca71453ae6
- */
-bool aFuntool::checkStdin() {
-    if (!isatty(fileno(stdin)))
-        return true;
-    bool re = false;
-
-    std::unique_lock<std::mutex> ul{fcntl_mutex};
-    int oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
-    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
-
-    int ch = fgetc(stdin);
-    clear_ferror(stdin);
-
-    if (ch != EOF) {
-        ungetc(ch, stdin);
-        re = true;
+    
+    // 用于Linux平台的IO函数
+    // 默认Linux平台均使用utf-8
+    
+    int fgets_stdin(char **dest, int len) {
+        *dest = calloc(len, char);
+        if (fgets(*dest, len, stdin) == nullptr)
+            return 0;
+        return 1;
     }
-
-    fcntl(STDIN_FILENO, F_SETFL, oldf);
-    return re;
-}
-
-bool aFuntool::fclear_stdin() {
-    if (!isatty(fileno(stdin)))
-        return true;
-
-    std::unique_lock<std::mutex> ul{fcntl_mutex};
-    int oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
-    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
-
-    int ch;
-    do {
-        ch = fgetc(stdin);
+    /*
+     * 函数名: checkStdin
+     * 目标: 检查stdin缓冲区是否有内容
+     * 有内容则返回true
+     * 无内容则返回false
+     *
+     * 参考自: https://gist.github.com/SuperH-0630/a4190b89d21c349a8d6882ca71453ae6
+     */
+    bool checkStdin() {
+        if (!isatty(fileno(stdin)))
+            return true;
+        bool re = false;
+    
+        std::unique_lock<std::mutex> ul{fcntl_mutex};
+        int oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
+        fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
+    
+        int ch = fgetc(stdin);
         clear_ferror(stdin);
-    } while (ch != EOF);
-
-    fcntl(STDIN_FILENO, F_SETFL, oldf);
-    return !ferror(stdin) && !feof(stdin);
+    
+        if (ch != EOF) {
+            ungetc(ch, stdin);
+            re = true;
+        }
+    
+        fcntl(STDIN_FILENO, F_SETFL, oldf);
+        return re;
+    }
+    
+    bool fclear_stdin() {
+        if (!isatty(fileno(stdin)))
+            return true;
+    
+        std::unique_lock<std::mutex> ul{fcntl_mutex};
+        int oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
+        fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
+    
+        int ch;
+        do {
+            ch = fgetc(stdin);
+            clear_ferror(stdin);
+        } while (ch != EOF);
+    
+        fcntl(STDIN_FILENO, F_SETFL, oldf);
+        return !ferror(stdin) && !feof(stdin);
+    }
 }
-
 #endif

+ 67 - 71
src/tool/string.cpp

@@ -8,8 +8,6 @@
 #include "tool.h"
 #include "str.h"
 
-using namespace aFuntool;
-
 #define EQ_STR(str1, str2) (!strcmp((str1), (str2)))
 #define EQ_WSTR(wid1, wid2) (!wcscmp((wid1), (wid2)))
 
@@ -19,83 +17,81 @@ using namespace aFuntool;
 #define STR_LEN(p) (((p) == NULL) ? 0 : strlen((p)))
 #define WSTR_LEN(p) (((p) == NULL) ? 0 : wcslen((p)))
 
-char *aFuntool::charToStr(char ch) {
-    if (ch == NUL)
-        return nullptr;
-    char *tmp = NEW_STR(1);
-    *tmp = ch;
-    return tmp;
-}
-
-char *aFuntool::strCopy(const char *str){
-    if (str != nullptr) {
-        char *tmp = NEW_STR(STR_LEN(str));
-        strcpy(tmp, str);
+namespace aFuntool {
+    char *charToStr(char ch){
+        if (ch == NUL)
+            return nullptr;
+        char *tmp = NEW_STR(1);
+        *tmp = ch;
         return tmp;
     }
-    return nullptr;
-}
-
 
-/*
- * 函数名: strJoin
- * 目标: 拼接两个字符串
- */
-char *aFuntool::strJoin(const char *first, const char *second, bool free_first, bool free_last) {
-    if (first == nullptr && second == nullptr)
+    char *strCopy(const char *str){
+        if (str != nullptr) {
+            char *tmp = NEW_STR(STR_LEN(str));
+            strcpy(tmp, str);
+            return tmp;
+        }
         return nullptr;
-    else if (first == nullptr){
-        first = second;
-        second = nullptr;
-        free_first = free_last;
-        free_last = false;
     }
-
-    char *new_str = NEW_STR(STR_LEN(first) + STR_LEN(second));
-    strcat(new_str, first);
-    if (second != nullptr)
-        strcat(new_str, second);
-
-    if (free_first) {
-        auto free_ = const_cast<char *>(first);
-        free(free_);
+    
+    /**
+     * 拼接两个字符串
+     */
+    char *strJoin(const char *first, const char *second, bool free_first, bool free_last){
+        if (first == nullptr && second == nullptr)
+            return nullptr;
+        else if (first == nullptr) {
+            first = second;
+            second = nullptr;
+            free_first = free_last;
+            free_last = false;
+        }
+
+        char *new_str = NEW_STR(STR_LEN(first) + STR_LEN(second));
+        strcat(new_str, first);
+        if (second != nullptr)
+            strcat(new_str, second);
+
+        if (free_first) {
+            auto free_ = const_cast<char *>(first);
+            free(free_);
+        }
+
+        if (free_last) {
+            auto free_ = const_cast<char *>(second);
+            free(free_);
+        }
+        return new_str;
     }
 
-    if (free_last) {
-        auto free_ = const_cast<char *>(second);
-        free(free_);
-    }
-    return new_str;
-}
-
-/*
- * 函数名: convertToWstr
- * 目标: char *转换为wchar_t *
- */
-wchar_t *aFuntool::convertToWstr(const char *str, bool free_old) {
-    size_t len = STR_LEN(str);
-    auto tmp = NEW_WSTR(len);
-    mbstowcs(tmp, str, len);
-
-    if (free_old) {
-        auto free_ = const_cast<char *>(str);
-        free(free_);
+    /**
+     * char *转换为wchar_t *
+     */
+    wchar_t *convertToWstr(const char *str, bool free_old){
+        size_t len = STR_LEN(str);
+        auto tmp = NEW_WSTR(len);
+        mbstowcs(tmp, str, len);
+
+        if (free_old) {
+            auto free_ = const_cast<char *>(str);
+            free(free_);
+        }
+        return tmp;
     }
-    return tmp;
-}
 
-/*
- * 函数名: convertToStr
- * 目标: wchar_t *转换为char *
- */
-char *aFuntool::convertToStr(const wchar_t *wstr, bool free_old) {
-    size_t len = WSTR_LEN(wstr);
-    auto tmp = NEW_STR(len);
-    wcstombs(tmp, wstr, len);
-
-    if (free_old) {
-        auto free_ = const_cast<wchar_t *>(wstr);
-        free(free_);
+    /**
+     * wchar_t *转换为char *
+     */
+    char *convertToStr(const wchar_t *wstr, bool free_old){
+        size_t len = WSTR_LEN(wstr);
+        auto tmp = NEW_STR(len);
+        wcstombs(tmp, wstr, len);
+
+        if (free_old) {
+            auto free_ = const_cast<wchar_t *>(wstr);
+            free(free_);
+        }
+        return tmp;
     }
-    return tmp;
 }

+ 66 - 64
src/tool/time.cpp

@@ -9,80 +9,82 @@
 #include "stdio_.h"
 #include "str.h"
 
-/**
- * 等待指定的秒数(ms) 支持小数
- */
-void aFuntool::safeSleep(double ms) {
-    time_t start = clock();
-    time_t now;
-    time_t d_time;
-    auto ms_t = (time_t) (ms * CLOCKS_PER_SEC);
-    do {
-        now = clock();
-        d_time = now - start;
-    } while (d_time < ms_t);
-}
+namespace aFuntool {
+    /**
+     * 等待指定的秒数(ms) 支持小数
+     */
+    void safeSleep(double ms){
+        time_t start = clock();
+        time_t now;
+        time_t d_time;
+        auto ms_t = (time_t) (ms * CLOCKS_PER_SEC);
+        do {
+            now = clock();
+            d_time = now - start;
+        } while (d_time < ms_t);
+    }
 
-/**
- * 格式化输出时间
- * 注意: 该函数不可以使用log模块
- */
-char *aFuntool::getTime(time_t *t, const char *format) {
-    time_t tmp;
-    if (t == nullptr)
-        t = &tmp;
+    /**
+     * 格式化输出时间
+     * 注意: 该函数不可以使用log模块
+     */
+    char *getTime(time_t *t, const char *format){
+        time_t tmp;
+        if (t == nullptr)
+            t = &tmp;
 
-    time (t);  // 获取时间戳
+        time(t);  // 获取时间戳
 #ifdef aFunWIN32_NO_CYGWIN
-    struct tm lt{};
-    if (localtime_s(&lt, t) != 0)
-        return nullptr;
-    wchar_t time_str[100];
-    wchar_t *format_ = nullptr;
-    if (convertWideByte(&format_, format, CP_UTF8) == 0)
-        return nullptr;
-    wcsftime(time_str, 100, format_, &lt);
-    free(format_);
+        struct tm lt{};
+        if (localtime_s(&lt, t) != 0)
+            return nullptr;
+        wchar_t time_str[100];
+        wchar_t *format_ = nullptr;
+        if (convertWideByte(&format_, format, CP_UTF8) == 0)
+            return nullptr;
+        wcsftime(time_str, 100, format_, &lt);
+        free(format_);
 
-    char *re = nullptr;
-    if (convertFromWideByte(&re, time_str, CP_UTF8) == 0)
-        return nullptr;
-    return re;
+        char *re = nullptr;
+        if (convertFromWideByte(&re, time_str, CP_UTF8) == 0)
+            return nullptr;
+        return re;
 #else
-    struct tm *lt = localtime (t);
-    char time_str[100];
-    strftime(time_str, 100, format, lt);
-    return strCopy(time_str);
+        struct tm *lt = localtime (t);
+        char time_str[100];
+        strftime(time_str, 100, format, lt);
+        return strCopy(time_str);
 #endif
-}
+    }
 
-std::string aFuntool::getTime(time_t *t, const std::string &format) {
-    time_t tmp;
-    if (t == nullptr)
-        t = &tmp;
+    std::string getTime(time_t *t, const std::string &format){
+        time_t tmp;
+        if (t == nullptr)
+            t = &tmp;
 
-    time (t);  // 获取时间戳
+        time(t);  // 获取时间戳
 #ifdef aFunWIN32_NO_CYGWIN
-    struct tm lt{};
-    if (localtime_s(&lt, t) != 0)
-        return "";
-    wchar_t time_str[100];
-    wchar_t *format_ = nullptr;
-    if (convertWideByte(&format_, format.c_str(), CP_UTF8) == 0)
-        return "";
-    wcsftime(time_str, 100, format_, &lt);
-    free(format_);
+        struct tm lt{};
+        if (localtime_s(&lt, t) != 0)
+            return "";
+        wchar_t time_str[100];
+        wchar_t *format_ = nullptr;
+        if (convertWideByte(&format_, format.c_str(), CP_UTF8) == 0)
+            return "";
+        wcsftime(time_str, 100, format_, &lt);
+        free(format_);
 
-    char *tmp_ch = nullptr;
-    if (convertFromWideByte(&tmp_ch, time_str, CP_UTF8) == 0)
-        return "";
+        char *tmp_ch = nullptr;
+        if (convertFromWideByte(&tmp_ch, time_str, CP_UTF8) == 0)
+            return "";
 #else
-    struct tm *lt = localtime (t);
-    char time_str[100];
-    strftime(time_str, 100, format.c_str(), lt);
-    char *tmp_ch = strCopy(time_str);;
+        struct tm *lt = localtime (t);
+        char time_str[100];
+        strftime(time_str, 100, format.c_str(), lt);
+        char *tmp_ch = strCopy(time_str);;
 #endif
-    std::string ret = tmp_ch;
-    free(tmp_ch);
-    return ret;
+        std::string ret = tmp_ch;
+        free(tmp_ch);
+        return ret;
+    }
 }