Pārlūkot izejas kodu

1、添加lock_exe函数;
2、添加写protobuf配置文件

LiuZe 10 mēneši atpakaļ
vecāks
revīzija
cd976b684c
2 mainītis faili ar 80 papildinājumiem un 0 dzēšanām
  1. 53 0
      tool/load_protobuf.hpp
  2. 27 0
      tool/lock_class.hpp

+ 53 - 0
tool/load_protobuf.hpp

@@ -77,3 +77,56 @@ static Error_manager loadProtobufFile(const std::string &file, ::google::protobu
         return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()};
     }
 }
+
+static bool writeTxtProtobufFile(const std::string &file, const google::protobuf::Message &message) {
+    int fd = open(file.c_str(), std::ios::out);
+
+    FileOutputStream * output = new FileOutputStream(fd);
+
+    google::protobuf::TextFormat::Print(message, output);
+    delete output;
+    close(fd);
+    return true;
+}
+
+static bool writeJsonProtobufFile(const std::string &file, const google::protobuf::Message &message) {
+    std::string str;
+    google::protobuf::util::JsonPrintOptions options;
+    options.add_whitespace = true;
+    options.always_print_primitive_fields = true;
+    options.preserve_proto_field_names = true;
+    if (google::protobuf::util::MessageToJsonString(message, &str, options) != absl::OkStatus()) {
+        return false;
+    }
+
+    //输出到文件
+    std::ofstream os;
+    os.open(file, std::ios::out);
+    if (!os.is_open())
+        std::cout << "error:can not find or create the file which named \" demo.json\"." << std::endl;
+    os << str;
+    os.close();
+    return true;
+}
+
+static Error_manager writeProtobufFile(const std::string &file, ::google::protobuf::Message &message) {
+    std::string ext = getFileExtension(file);
+    if (ext.empty()) {
+        return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s ext failed.", file.c_str()};
+    }
+
+    bool ret = false;
+    if (ext == "prototxt") {
+        ret = writeTxtProtobufFile(file, message);
+    } else if (ext == "json") {
+        ret = writeJsonProtobufFile(file, message);
+    } else {
+        return {PARSE_FAILED, MINOR_ERROR, "protobuf file %s type error.", file.c_str()};
+    }
+
+    if (ret) {
+        return {SUCCESS, NORMAL, "prase protobuf file %s success.", file.c_str()};
+    } else {
+        return {PARSE_FAILED, MINOR_ERROR, "prase protobuf file %s failed.", file.c_str()};
+    }
+}

+ 27 - 0
tool/lock_class.hpp

@@ -0,0 +1,27 @@
+#pragma once
+
+#include <thread>
+#include <mutex>
+
+template <class Type>
+class lockFunc {
+public:
+    template<class Func, class ... Args>
+    int lock_exe(Func func, Args&&... args) {
+        lock.lock();
+        bool ret = ((Type* )this->*func)(args...);
+        lock.unlock();
+        return ret;
+    }
+
+    template<class Func, class ... Args>
+    int lock_exe(Func func, Type* p, Args&&... args) {
+        lock.lock();
+        bool ret = (p->*func)(args...);
+        lock.unlock();
+        return ret;
+    }
+
+private:
+    std::mutex lock;
+};