1 //
2 // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 #pragma once
8 
9 #include "td/telegram/Version.h"
10 
11 #include "td/utils/common.h"
12 #include "td/utils/StringBuilder.h"
13 
14 #include <functional>
15 #include <type_traits>
16 
17 namespace td {
18 
19 class UserId {
20   int64 id = 0;
21 
22  public:
23   static constexpr int64 MAX_USER_ID = (1ll << 40) - 1;
24 
25   UserId() = default;
26 
UserId(int64 user_id)27   explicit UserId(int64 user_id) : id(user_id) {
28   }
29   template <class T, typename = std::enable_if_t<std::is_convertible<T, int64>::value>>
30   UserId(T user_id) = delete;
31 
get_user_ids(const vector<int64> & input_user_ids)32   static vector<UserId> get_user_ids(const vector<int64> &input_user_ids) {
33     vector<UserId> user_ids;
34     user_ids.reserve(input_user_ids.size());
35     for (auto &input_user_id : input_user_ids) {
36       user_ids.emplace_back(input_user_id);
37     }
38     return user_ids;
39   }
40 
get_input_user_ids(const vector<UserId> & user_ids)41   static vector<int64> get_input_user_ids(const vector<UserId> &user_ids) {
42     vector<int64> input_user_ids;
43     input_user_ids.reserve(user_ids.size());
44     for (auto &user_id : user_ids) {
45       input_user_ids.emplace_back(user_id.get());
46     }
47     return input_user_ids;
48   }
49 
is_valid()50   bool is_valid() const {
51     return 0 < id && id <= MAX_USER_ID;
52   }
53 
get()54   int64 get() const {
55     return id;
56   }
57 
58   bool operator==(const UserId &other) const {
59     return id == other.id;
60   }
61 
62   bool operator!=(const UserId &other) const {
63     return id != other.id;
64   }
65 
66   template <class StorerT>
store(StorerT & storer)67   void store(StorerT &storer) const {
68     storer.store_long(id);
69   }
70 
71   template <class ParserT>
parse(ParserT & parser)72   void parse(ParserT &parser) {
73     if (parser.version() >= static_cast<int32>(Version::Support64BitIds)) {
74       id = parser.fetch_long();
75     } else {
76       id = parser.fetch_int();
77     }
78   }
79 };
80 
81 struct UserIdHash {
operatorUserIdHash82   std::size_t operator()(UserId user_id) const {
83     return std::hash<int64>()(user_id.get());
84   }
85 };
86 
87 inline StringBuilder &operator<<(StringBuilder &string_builder, UserId user_id) {
88   return string_builder << "user " << user_id.get();
89 }
90 
91 }  // namespace td
92