summaryrefslogtreecommitdiffstats
path: root/server/src/locale.cppm
blob: 00a3d3658f3553d63b2fa100ee89a9e3bbb89e3d (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
module;

#include <boost/locale.hpp>
#include <unicode/localematcher.h>

export module routemon:locale;

import std;
import :util;

export namespace blocale = boost::locale;

export namespace routemon {

using lformat = blocale::format;
using blocale::gettext;
using blocale::translate;

} // namespace routemon

namespace routemon::locale {

export template <class T>
concept locale_input_range =
    std::ranges::input_range<T>
    && std::
        same_as<std::locale const&, std::ranges::range_const_reference_t<T>>;

class bcp47_tag : public std::locale::facet
{
  std::string tag_;

public:
  static std::locale::id id;

  explicit bcp47_tag(std::locale locale);
  ~bcp47_tag() override = default;

  auto tag() const -> std::string_view;
};

// Helps select a locale based on the Accept-Language header in an
// HTTP request.
export class selector
{
  std::vector<std::locale> supported_;
  std::locale default_;
  icu::LocaleMatcher matcher_;

  static auto make_matcher(std::vector<std::locale> const& supported_locales)
      -> icu::LocaleMatcher;

  // Trimming optional whitespace as defined in RFC 9110, § 12.4.2.
  static auto ltrim_ows(std::string_view s) -> std::string_view;
  static auto rtrim_ows(std::string_view s) -> std::string_view;
  static auto trim_ows(std::string_view s) -> std::string_view;

public:
  explicit selector(locale_input_range auto supported, std::locale default_)
    : supported_{
        std::from_range,
        supported
            | std::views::transform(
                [](std::locale const& locale) -> std::locale
                { return std::locale{locale, new bcp47_tag{locale}}; })
      },
      default_{std::locale{default_, new bcp47_tag{default_}}},
      matcher_{make_matcher(supported_)}
  {
  }

  auto select(std::string_view accept_language) const -> std::locale;
};

export auto make_generator() -> std::shared_ptr<blocale::generator const>;

} // namespace routemon::locale