LeviLamina
Loading...
Searching...
No Matches
I18n.h
1#pragma once
2
3#include "ll/api/Expected.h"
4#include "ll/api/base/Concepts.h"
5#include "ll/api/base/FixedString.h"
6
7#if _HAS_CXX23
8#include <expected>
9#endif
10
11#include "fmt/chrono.h" // IWYU pragma: keep
12#include "fmt/color.h" // IWYU pragma: keep
13#include "fmt/compile.h" // IWYU pragma: keep
14#include "fmt/format.h" // IWYU pragma: keep
15#include "fmt/os.h" // IWYU pragma: keep
16#include "fmt/ranges.h" // IWYU pragma: keep
17#include "fmt/std.h" // IWYU pragma: keep
18
19// #define LL_I18N_COLLECT_STRINGS
20
21namespace ll::i18n {
22
23LLNDAPI std::string_view getDefaultLocaleCode();
24
25class I18n {
26 struct Impl;
27 std::unique_ptr<Impl> impl;
28
29public:
30 LLNDAPI I18n();
31 LLAPI ~I18n();
32
33 LLNDAPI Expected<> load(std::filesystem::path const& path) noexcept;
34
35 LLAPI void clear();
36
37 LLAPI void set(std::string_view localeCode, std::string_view key, std::string_view value);
38
39 LLNDAPI std::string_view get(std::string_view key, std::string_view localeCode) const;
40};
41
42inline I18n& getInstance() {
43 static I18n ins{};
44 return ins;
45}
46
47} // namespace ll::i18n
48
49#ifdef LL_I18N_COLLECT_STRINGS
50#include "ll/api/reflection/TypeName.h"
51
52#ifndef LL_I18N_STRING_LITERAL_TYPE
53#define LL_I18N_STRING_LITERAL_TYPE ::ll::FixedStrWithLoc
54#endif
55
56namespace ll::i18n::detail {
57template <LL_I18N_STRING_LITERAL_TYPE str>
58struct TrStrOut;
59#ifndef LL_I18N_COLLECT_STRINGS_CUSTOM
60template <LL_I18N_STRING_LITERAL_TYPE str>
61struct TrStrOut {
62 static inline int _ = [] {
63 fmt::print("\"{0}\": \"{0}\", // at {1}\n", str.sv(), str.loc().toString());
64 return 0;
65 }();
66};
67#endif
68} // namespace ll::i18n::detail
69#else
70#ifndef LL_I18N_STRING_LITERAL_TYPE
71#define LL_I18N_STRING_LITERAL_TYPE ::ll::FixedString
72#endif
73#endif
74namespace ll::inline literals::inline i18n_literals {
75template <LL_I18N_STRING_LITERAL_TYPE Fmt>
76[[nodiscard]] constexpr auto operator""_tr() {
77#ifdef LL_I18N_COLLECT_STRINGS
78 static i18n::detail::TrStrOut<Fmt> e{};
79#endif
80 return [=]<class... Args>(Args&&... args) {
81 [[maybe_unused]] static constexpr auto checker = fmt::format_string<Args...>(Fmt.sv());
82 return fmt::vformat(i18n::getInstance().get(Fmt.sv(), {}), fmt::make_format_args(args...));
83 };
84}
85template <LL_I18N_STRING_LITERAL_TYPE Fmt>
86[[nodiscard]] constexpr auto operator""_trl() {
87#ifdef LL_I18N_COLLECT_STRINGS
88 static i18n::detail::TrStrOut<Fmt> e{};
89#endif
90 return [=]<class... Args>(std::string_view localeCode, Args&&... args) {
91 [[maybe_unused]] static constexpr auto checker = fmt::format_string<Args...>(Fmt.sv());
92 return fmt::vformat(i18n::getInstance().get(Fmt.sv(), localeCode), fmt::make_format_args(args...));
93 };
94}
95} // namespace ll::inline literals::inline i18n_literals
Definition I18n.h:25