VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
SteamId.cpp
Go to the documentation of this file.
2#include <charconv>
3#include <format>
4#include <string_view>
5
6namespace VoltMod
7{
8
10{
12 return std::format("[U:1:{}]", accountId);
13}
14
16{
20 return std::format("STEAM_0:{}:{}", authServer, accountNum);
21}
22
23std::optional<int64_t> SteamId::FromSteamId3(const std::string& steamId3)
24{
25 // Was regex `\[U:1:(\d+)\]` (full match).
26 constexpr std::string_view prefix = "[U:1:";
27 if (!steamId3.starts_with(prefix) || steamId3.size() <= prefix.size() + 1 || steamId3.back() != ']')
28 {
29 return std::nullopt;
30 }
31
32 const char* first = steamId3.data() + prefix.size();
33 const char* last = steamId3.data() + steamId3.size() - 1; // the trailing ']'
35 auto [ptr, ec] = std::from_chars(first, last, accountId);
36
37 if (ec != std::errc{} || ptr != last)
38 {
39 return std::nullopt;
40 }
41
42 return SteamId64Base + accountId;
43}
44
45std::optional<int64_t> SteamId::FromSteamId(const std::string& steamId)
46{
47 // Was regex `STEAM_[0-5]:([01]):(\d+)` (full match). Fixed shape after the prefix:
48 // <universe 0-5> ':' <auth 0|1> ':' <accountNum>.
49 constexpr std::string_view prefix = "STEAM_";
50 if (!steamId.starts_with(prefix) || steamId.size() < prefix.size() + 4)
51 {
52 return std::nullopt;
53 }
54
55 const char universe = steamId[prefix.size()];
56 const char auth = steamId[prefix.size() + 2];
57 if (universe < '0' || universe > '5' || auth < '0' || auth > '1' || steamId[prefix.size() + 1] != ':' ||
58 steamId[prefix.size() + 3] != ':')
59 {
60 return std::nullopt;
61 }
62
63 const char* first = steamId.data() + prefix.size() + 4;
64 const char* last = steamId.data() + steamId.size();
66 auto [ptr, ec] = std::from_chars(first, last, accountNum);
67 if (ec != std::errc{} || ptr != last) // (\d+) requires ≥1 digit and no trailing junk
68 {
69 return std::nullopt;
70 }
71
72 const uint32_t accountId = accountNum * 2 + static_cast<uint32_t>(auth - '0');
73 return SteamId64Base + accountId;
74}
75
77{
78 return steamId64 >= SteamId64Base && steamId64 < (SteamId64Base + 0x100000000LL); // account IDs are 32-bit
79}
80
82{
83 return static_cast<uint32_t>(steamId64 - SteamId64Base);
84}
85
86} // namespace VoltMod
static std::string ToSteamId3(int64_t steamId64)
Definition SteamId.cpp:9
static std::optional< int64_t > FromSteamId3(const std::string &steamId3)
Definition SteamId.cpp:23
static uint32_t GetAccountId(int64_t steamId64)
Definition SteamId.cpp:81
static bool IsValid(int64_t steamId64)
Definition SteamId.cpp:76
static std::string ToSteamId(int64_t steamId64)
Definition SteamId.cpp:15
static std::optional< int64_t > FromSteamId(const std::string &steamId)
Definition SteamId.cpp:45
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56