Skip to content
Merged
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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Changelog

## 0.4.9

- **Where the user is (`locale`).** `locale::region()` is the region of the
user's locale, ISO 3166-1 alpha-2 in capitals: the first of `LC_ALL`,
`LC_MESSAGES` and `LANG` that names one, and on Windows the user's geographic
location before them. `locale::time_zone()` is the system's time zone as the
system names it: an IANA name from `TZ`, else from the zoneinfo file
`/etc/localtime` links to, else `/etc/timezone`; the zone's key on Windows.
Both are read without the network and without starting a program; an image
and a wasm module read what they can of the same. `region_of` and `zone_of`
read a locale's name and a TZ value or zoneinfo path. A program that chooses
a default by them states the choice and keeps an override: neither names
where the machine is, only what its user set (mcpp's download mirror).

## 0.4.8

- **A link's own stamp (`fs::stamp_of(node, false)`).** With `resolve` false
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ at a time). `windows::console_text_code_page()` and
| `mcpplibs.os.ipc` | a listener and a connection at a name in a directory; `single_instance` |
| `mcpplibs.os.net` | loopback TCP |
| `mcpplibs.os.machine` | the machine's architecture (through Rosetta and WoW64), memory and the memory available now, processors (logical, physical, of differing speed), the processor's model |
| `mcpplibs.os.locale` | where the user is, as the system states it: the region of the user's locale (`region`, `region_of`) and the system's time zone (`time_zone`, `zone_of`), read without the network or a started program |
| `mcpplibs.os.random` | bytes from the system's source of unpredictable bytes; `hex` |
| `mcpplibs.os.library` | shared libraries at run time: `open` (a path or a name the system searches for), `loaded` (one the process has, without loading it), a handle's `symbol` / `function<F>`, `process_symbol` (as the loader resolves one), `suffix` |
| `mcpplibs.os.linux` / `.macos` / `.windows` / `.posix` | platform modules: declared on every target, defined on their own and, where an image can answer, in an image; the system's object models, through which its services that are not functions are reached: `windows::com` (COM and the Windows Runtime) and `macos::objc` (the Objective-C runtime) |
Expand Down
6 changes: 6 additions & 0 deletions checks/emscripten/tests/locale_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// locale_test.cpp of mcpplibs.os, compiled in this arrangement. The imports are restated
// because the dependency scan reads this file and not the one it includes.
import std;
import mcpplibs.os;
import mcpplibs.mtest;
#include "../../../tests/locale_test.cpp"
6 changes: 6 additions & 0 deletions checks/hosted/tests/locale_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// locale_test.cpp of mcpplibs.os, compiled in this arrangement. The imports are restated
// because the dependency scan reads this file and not the one it includes.
import std;
import mcpplibs.os;
import mcpplibs.mtest;
#include "../../../tests/locale_test.cpp"
7 changes: 6 additions & 1 deletion mcpp.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
namespace = "mcpplibs"
name = "os"
version = "0.4.8"
version = "0.4.9"
description = "mcpplibs.os: a C++ operating-system library over openkal --- processes, files, environment, terminals, directories and local IPC, with compile-time platform constants and a few platform modules."
license = "Apache-2.0"
authors = ["mcpplibs"]
Expand Down Expand Up @@ -47,6 +47,11 @@ sources = ["src/*.cppm", "src/*.cpp"]
[target.'cfg(not(os = "emscripten"))'.build]
sources = ["src/kal/interrupt.cpp"]

# Where the user is (`locale'): the environment and the zoneinfo files on every
# target but Windows, which answers from kernel32 (src/windows/locale.cpp).
[target.'cfg(not(windows))'.build]
sources = ["src/locale/system.cpp"]

# The architecture of the build, as a constant beside the platform's.
[target.'cfg(arch = "x86_64")'.build]
sources = ["src/arch/x86_64.cppm"]
Expand Down
71 changes: 71 additions & 0 deletions src/locale.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
module mcpplibs.os.locale;

import std;
import mcpplibs.os.env;

namespace mcpplibs::os::locale {

namespace {

bool alpha(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }
bool digit(char c) { return c >= '0' && c <= '9'; }

} // namespace

// `language[_territory][.codeset][@modifier]' (POSIX) or a BCP 47 tag
// (`zh-Hans-CN'): the territory is the first two-letter subtag after the
// language, before the codeset and the modifier.
std::optional<std::string> region_of(std::string_view locale) {
locale = locale.substr(0, locale.find_first_of(".@"));
if (locale.empty() || locale == "C" || locale == "POSIX") return std::nullopt;
std::size_t at = locale.find_first_of("_-");
while (at != std::string_view::npos) {
const auto next = locale.find_first_of("_-", at + 1);
const auto tag = locale.substr(at + 1, next == std::string_view::npos ? std::string_view::npos : next - at - 1);
if (auto region = detail::region_code(tag)) return region;
at = next;
}
return std::nullopt;
}

// A name is letters, digits and `/_-+', and begins with a letter; one with a
// digit and no `/' is a POSIX rule (`CST-8', `UTC0'), not a name.
std::optional<std::string> zone_of(std::string_view value) {
if (value.starts_with(':')) value.remove_prefix(1);
if (const auto at = value.rfind("zoneinfo/"); at != std::string_view::npos)
value.remove_prefix(at + std::string_view("zoneinfo/").size());
else if (value.starts_with('/'))
return std::nullopt;
while (!value.empty() && (value.back() == '\n' || value.back() == '\r' || value.back() == ' ')) value.remove_suffix(1);
if (value.empty() || !alpha(value.front())) return std::nullopt;
bool slash = false, digits = false;
for (const char c : value) {
if (c == '/') slash = true;
else if (digit(c)) digits = true;
else if (!alpha(c) && c != '_' && c != '-' && c != '+') return std::nullopt;
}
if (digits && !slash) return std::nullopt;
return std::string(value);
}

namespace detail {

// LC_ALL=C is often stated for a program's output alone, with the user's
// locale in LANG: the first variable that names a region answers.
std::optional<std::string> region_code(std::string_view code) {
if (code.size() != 2 || !alpha(code[0]) || !alpha(code[1])) return std::nullopt;
std::string region(code);
for (auto& c : region) c = static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c);
return region;
}

std::optional<std::string> region_from_environment() {
for (const auto* name : {"LC_ALL", "LC_MESSAGES", "LANG"})
if (const auto value = os::env::get(name))
if (auto region = region_of(*value)) return region;
return std::nullopt;
}

} // namespace detail

} // namespace mcpplibs::os::locale
46 changes: 46 additions & 0 deletions src/locale.cppm
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// mcpplibs.os.locale --- where the user is, as the system states it: the
// region of the user's locale and the system's time zone (0.4.9).
//
// Neither is a question of the kernel layer. Both are read without the network
// and without starting a program: the environment and the zoneinfo files on a
// POSIX system, the user's geographic location and the dynamic time zone on
// Windows; an image and a wasm module read what they can of the same. A
// program that chooses a default by them (a download mirror, a unit system)
// states the choice and keeps an explicit override: neither names where the
// machine is, only what its user set.
export module mcpplibs.os.locale;

import std;

export namespace mcpplibs::os::locale {

// The region of the user's locale, ISO 3166-1 alpha-2 in capitals (`CN',
// `US'): the first of LC_ALL, LC_MESSAGES and LANG that names one, and on
// Windows the user's geographic location before them. Nothing when none names
// a region (`C', `POSIX', a language alone).
std::optional<std::string> region();

// The system's time zone as the system names it: an IANA name on a POSIX
// system (`Asia/Shanghai'), from TZ, else from the zoneinfo file
// /etc/localtime links to, else /etc/timezone; the zone's key on Windows
// (`China Standard Time'). Nothing when none states one, and when TZ holds a
// rule rather than a name (`CST-8').
std::optional<std::string> time_zone();

// The region a locale's name states: `zh_CN.UTF-8', `sr_RS@latin' and
// `zh-Hans-CN' give `CN', `RS' and `CN'; `C', `POSIX' and `en' give nothing.
std::optional<std::string> region_of(std::string_view locale);

// The zone a TZ value or a zoneinfo path names: `Asia/Shanghai',
// `:Asia/Shanghai' and `/usr/share/zoneinfo/Asia/Shanghai' give
// `Asia/Shanghai'; a POSIX rule (`CST-8') and an empty value give nothing.
std::optional<std::string> zone_of(std::string_view value);

} // namespace mcpplibs::os::locale

// What every system reads alike (src/locale.cpp): the region the locale
// variables of the environment state, and a code of two letters in capitals.
namespace mcpplibs::os::locale::detail {
std::optional<std::string> region_from_environment();
std::optional<std::string> region_code(std::string_view code);
} // namespace mcpplibs::os::locale::detail
26 changes: 26 additions & 0 deletions src/locale/system.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// mcpplibs.os.locale on every system but Windows: the environment, then the
// zoneinfo file /etc/localtime links to, then /etc/timezone, where a Debian
// system keeps the name when /etc/localtime is a copy. An image reads its
// host's files through openkal, and a wasm module what its host gives it.
module mcpplibs.os.locale;

import std;
import mcpplibs.os.env;
import mcpplibs.os.fs;

namespace mcpplibs::os::locale {

std::optional<std::string> region() { return detail::region_from_environment(); }

// TZ governs when it is set, named or not: a rule (`CST-8') names no zone, and
// the files would name another.
std::optional<std::string> time_zone() {
if (const auto tz = os::env::get("TZ"); tz && !tz->empty()) return zone_of(*tz);
if (const auto target = os::fs::read_link("/etc/localtime"))
if (auto zone = zone_of(*target)) return zone;
if (const auto text = os::fs::read("/etc/timezone", 256))
return zone_of(std::string_view(*text).substr(0, text->find('\n')));
return std::nullopt;
}

} // namespace mcpplibs::os::locale
1 change: 1 addition & 0 deletions src/os.cppm
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export import mcpplibs.os.dirs;
export import mcpplibs.os.ipc;
export import mcpplibs.os.net;
export import mcpplibs.os.machine;
export import mcpplibs.os.locale;
export import mcpplibs.os.random;
export import mcpplibs.os.library;
export import mcpplibs.os.linux;
Expand Down
53 changes: 53 additions & 0 deletions src/windows/locale.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// mcpplibs.os.locale on Windows: the user's geographic location and the
// system's dynamic time zone, from kernel32 at run time (src/windows/win32.h).
module;
#include "win32.h"

module mcpplibs.os.locale;

import std;

namespace mcpplibs::os::locale {

namespace {

std::string narrow(std::u16string_view wide) {
const int n = WideCharToMultiByte(65001, 0, wide.data(), static_cast<int>(wide.size()), nullptr, 0, nullptr, nullptr);
if (n <= 0) return {};
std::string text(static_cast<std::size_t>(n), '\0');
WideCharToMultiByte(65001, 0, wide.data(), static_cast<int>(wide.size()), text.data(), n, nullptr, nullptr);
return text;
}

} // namespace

// GetUserDefaultGeoName (Windows 10 1709): the ISO 3166-1 code of the location
// the user set; a UN M.49 number, for a location without a code, names no
// region here. The locale variables answer where it gives none (a shell that
// states LANG).
std::optional<std::string> region() {
if (const auto get = late::find<int(__stdcall*)(okos_wchar*, int)>("GetUserDefaultGeoName")) {
okos_wchar name[16] = {};
if (get(name, 16) > 0)
if (auto region = detail::region_code(narrow(std::u16string_view(name)))) return region;
}
return detail::region_from_environment();
}

// DYNAMIC_TIME_ZONE_INFORMATION is 432 bytes: the bias, the standard and
// daylight names, dates and biases (172 bytes), then TimeZoneKeyName, 128
// UTF-16 units, the name the registry keys the zone by.
std::optional<std::string> time_zone() {
const auto get = late::find<okos_dword(__stdcall*)(void*)>("GetDynamicTimeZoneInformation");
if (!get) return std::nullopt;
alignas(4) unsigned char info[432] = {};
if (get(info) == 0xFFFFFFFFu /* TIME_ZONE_ID_INVALID */) return std::nullopt;
okos_wchar key[128] = {};
std::memcpy(key, info + 172, sizeof key);
key[127] = 0;
auto name = narrow(std::u16string_view(key));
if (name.empty()) return std::nullopt;
return name;
}

} // namespace mcpplibs::os::locale
60 changes: 60 additions & 0 deletions tests/locale_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Where the user is (0.4.9): the region of a locale's name, the zone of a TZ
// value or a zoneinfo path, and the answers of this machine, which agree with
// what its environment and files state.
import std;
import mcpplibs.os;
import mcpplibs.mtest;

namespace os = mcpplibs::os;
namespace locale = mcpplibs::os::locale;
using namespace mcpplibs::mtest;

UTest locale_tests{"locale", [] {
// A locale's name: POSIX and BCP 47 spellings.
expect(locale::region_of("zh_CN.UTF-8") == std::optional<std::string>("CN")) << "zh_CN.UTF-8";
expect(locale::region_of("en_US") == std::optional<std::string>("US")) << "en_US";
expect(locale::region_of("sr_RS@latin") == std::optional<std::string>("RS")) << "sr_RS@latin";
expect(locale::region_of("zh-Hans-CN") == std::optional<std::string>("CN")) << "zh-Hans-CN";
expect(locale::region_of("de-de") == std::optional<std::string>("DE")) << "de-de";
for (std::string_view none : {"", "C", "POSIX", "C.UTF-8", "en", "zh_Hans"})
expect(!locale::region_of(none).has_value()) << std::format("`{}' names no region", none).c_str();

// A TZ value or a zoneinfo path.
expect(locale::zone_of("Asia/Shanghai") == std::optional<std::string>("Asia/Shanghai")) << "a name";
expect(locale::zone_of(":Asia/Shanghai") == std::optional<std::string>("Asia/Shanghai")) << "TZ's `:' form";
expect(locale::zone_of("/usr/share/zoneinfo/Asia/Shanghai") == std::optional<std::string>("Asia/Shanghai"))
<< "a zoneinfo path";
expect(locale::zone_of("/var/db/timezone/zoneinfo/America/New_York") == std::optional<std::string>("America/New_York"))
<< "macOS's zoneinfo";
expect(locale::zone_of("../usr/share/zoneinfo/Etc/GMT-8") == std::optional<std::string>("Etc/GMT-8"))
<< "a relative link";
expect(locale::zone_of("PRC\n") == std::optional<std::string>("PRC")) << "/etc/timezone's line";
expect(locale::zone_of("UTC") == std::optional<std::string>("UTC")) << "UTC";
for (std::string_view none : {"", "CST-8", "UTC0", "/etc/localtime", ":", "9/x"})
expect(!locale::zone_of(none).has_value()) << std::format("`{}' names no zone", none).c_str();

// This machine: a region is two capitals; the zone is what TZ, or the
// link of /etc/localtime, names.
const auto region = locale::region();
const auto zone = locale::time_zone();
std::printf(" note region() = %s, time_zone() = %s\n", region ? region->c_str() : "(none)",
zone ? zone->c_str() : "(none)");
if (region)
expect(region->size() == 2 && std::ranges::all_of(*region, [](char c) { return c >= 'A' && c <= 'Z'; }))
<< "a region is two capitals";
if constexpr (!os::is_windows && !os::is_emscripten) {
if (const auto tz = os::env::get("TZ"); tz && !tz->empty()) {
expect(zone == locale::zone_of(*tz)) << "TZ governs";
} else if (const auto link = os::fs::read_link("/etc/localtime"); link && locale::zone_of(*link)) {
expect(zone == locale::zone_of(*link)) << "the zone /etc/localtime links to";
}
bool before = false;
for (const auto* name : {"LC_ALL", "LC_MESSAGES"})
if (const auto v = os::env::get(name); v && locale::region_of(*v)) before = true;
if (const auto lang = os::env::get("LANG"); !before && lang)
expect(region == locale::region_of(*lang)) << "LANG names the region";
}
if constexpr (os::is_windows) {
if (os::env::get("GITHUB_ACTIONS")) expect(zone.has_value()) << "Windows names its time zone";
}
}};
Loading