Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better Code orgnization #2

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/alias.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#include <nlohmann/json.hpp>
#include <vector>

// common / frequently used type-alias here

using json = nlohmann::json;
using StrVec = std::vector<std::string>;
39 changes: 39 additions & 0 deletions src/encoding.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#pragma once

#ifdef _WIN32
#include <Windows.h>
#endif
#include <string>

namespace encoding {

#ifdef _WIN32
inline std::string ansi2utf8(const std::string &str) {
int wCharLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, 0, 0);
if (wCharLen == 0)
return "";
wchar_t *wStr = new wchar_t[wCharLen];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wStr, wCharLen);
int utf8Len = WideCharToMultiByte(CP_UTF8, 0, wStr, -1, 0, 0, 0, 0);
if (utf8Len == 0) {
delete[] wStr;
return "";
}
char *utf8Str = new char[utf8Len];
WideCharToMultiByte(CP_UTF8, 0, wStr, -1, utf8Str, utf8Len, 0, 0);
std::string result(utf8Str);
delete[] wStr;
delete[] utf8Str;
return result;
}
#endif

inline std::string platform_str(const std::string &str) {
#ifdef _WIN32
return ansi2utf8(str);
#else
return str;
#endif
}

} // namespace encoding
26 changes: 26 additions & 0 deletions src/json.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#pragma once

#include "alias.hpp"
#include <fstream>
#include <string_view>

namespace jsonutils {

inline json load_from_file(std::string_view filename) {
std::ifstream fin(filename.data());
if (!fin) {
return json();
}
return std::move(json::parse(fin));
}

inline void save_to_file(const json &obj, std::string_view filename) {
std::ofstream fout(filename.data());
if (!fout.good()) {
return;
}
fout << obj.dump(4);
fout.close();
}

} // namespace jsonutils
Loading