aboutsummaryrefslogtreecommitdiffhomepage
path: root/tdutils/td/utils/Status.h
blob: f62318a0163b5813ff78f8a0f8e04b4ac3ec0a75 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2025
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once

#include "td/utils/common.h"
#include "td/utils/logging.h"
#include "td/utils/ScopeGuard.h"
#include "td/utils/Slice.h"
#include "td/utils/StackAllocator.h"
#include "td/utils/StringBuilder.h"

#include <cerrno>
#include <cstring>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>

#define TRY_STATUS(status)                      \
  {                                             \
    auto try_status = (status);                 \
    if (try_status.is_error()) {                \
      return try_status.move_as_error_unsafe(); \
    }                                           \
  }

#define TRY_STATUS_PREFIX(status, prefix)                    \
  {                                                          \
    auto try_status = (status);                              \
    if (try_status.is_error()) {                             \
      return try_status.move_as_error_prefix_unsafe(prefix); \
    }                                                        \
  }

#define TRY_STATUS_PROMISE(promise_name, status)                        \
  {                                                                     \
    auto try_status = (status);                                         \
    if (try_status.is_error()) {                                        \
      return promise_name.set_error(try_status.move_as_error_unsafe()); \
    }                                                                   \
  }

#define TRY_STATUS_PROMISE_PREFIX(promise_name, status, prefix)                      \
  {                                                                                  \
    auto try_status = (status);                                                      \
    if (try_status.is_error()) {                                                     \
      return promise_name.set_error(try_status.move_as_error_prefix_unsafe(prefix)); \
    }                                                                                \
  }

#define TRY_RESULT(name, result) TRY_RESULT_IMPL(TD_CONCAT(TD_CONCAT(r_, name), __LINE__), auto name, result)

#define TRY_RESULT_PROMISE(promise_name, name, result) \
  TRY_RESULT_PROMISE_IMPL(promise_name, TD_CONCAT(TD_CONCAT(r_, name), __LINE__), auto name, result)

#define TRY_RESULT_ASSIGN(name, result) TRY_RESULT_IMPL(TD_CONCAT(r_response, __LINE__), name, result)

#define TRY_RESULT_PROMISE_ASSIGN(promise_name, name, result) \
  TRY_RESULT_PROMISE_IMPL(promise_name, TD_CONCAT(TD_CONCAT(r_, name), __LINE__), name, result)

#define TRY_RESULT_PREFIX(name, result, prefix) \
  TRY_RESULT_PREFIX_IMPL(TD_CONCAT(TD_CONCAT(r_, name), __LINE__), auto name, result, prefix)

#define TRY_RESULT_PREFIX_ASSIGN(name, result, prefix) \
  TRY_RESULT_PREFIX_IMPL(TD_CONCAT(TD_CONCAT(r_, name), __LINE__), name, result, prefix)

#define TRY_RESULT_PROMISE_PREFIX(promise_name, name, result, prefix) \
  TRY_RESULT_PROMISE_PREFIX_IMPL(promise_name, TD_CONCAT(TD_CONCAT(r_, name), __LINE__), auto name, result, prefix)

#define TRY_RESULT_PROMISE_PREFIX_ASSIGN(promise_name, name, result, prefix) \
  TRY_RESULT_PROMISE_PREFIX_IMPL(promise_name, TD_CONCAT(TD_CONCAT(r_, name), __LINE__), name, result, prefix)

#define TRY_RESULT_IMPL(r_name, name, result) \
  auto r_name = (result);                     \
  if (r_name.is_error()) {                    \
    return r_name.move_as_error_unsafe();     \
  }                                           \
  name = r_name.move_as_ok_unsafe();

#define TRY_RESULT_PREFIX_IMPL(r_name, name, result, prefix) \
  auto r_name = (result);                                    \
  if (r_name.is_error()) {                                   \
    return r_name.move_as_error_prefix_unsafe(prefix);       \
  }                                                          \
  name = r_name.move_as_ok_unsafe();

#define TRY_RESULT_PROMISE_IMPL(promise_name, r_name, name, result) \
  auto r_name = (result);                                           \
  if (r_name.is_error()) {                                          \
    return promise_name.set_error(r_name.move_as_error_unsafe());   \
  }                                                                 \
  name = r_name.move_as_ok_unsafe();

#define TRY_RESULT_PROMISE_PREFIX_IMPL(promise_name, r_name, name, result, prefix) \
  auto r_name = (result);                                                          \
  if (r_name.is_error()) {                                                         \
    return promise_name.set_error(r_name.move_as_error_prefix_unsafe(prefix));     \
  }                                                                                \
  name = r_name.move_as_ok_unsafe();

#define LOG_STATUS(status)                             \
  {                                                    \
    auto log_status = (status);                        \
    if (log_status.is_error()) {                       \
      LOG(ERROR) << log_status.move_as_error_unsafe(); \
    }                                                  \
  }

#ifndef TD_STATUS_NO_ENSURE
#define ensure() ensure_impl(__FILE__, __LINE__)
#define ensure_error() ensure_error_impl(__FILE__, __LINE__)
#endif

#if TD_PORT_POSIX
#define OS_ERROR(message)                                    \
  [&] {                                                      \
    auto saved_errno = errno;                                \
    return ::td::Status::PosixError(saved_errno, (message)); \
  }()
#define OS_SOCKET_ERROR(message) OS_ERROR(message)
#elif TD_PORT_WINDOWS
#define OS_ERROR(message)                                      \
  [&] {                                                        \
    auto saved_error = ::GetLastError();                       \
    return ::td::Status::WindowsError(saved_error, (message)); \
  }()
#define OS_SOCKET_ERROR(message)                               \
  [&] {                                                        \
    auto saved_error = ::WSAGetLastError();                    \
    return ::td::Status::WindowsError(saved_error, (message)); \
  }()
#endif

namespace td {

#if TD_PORT_POSIX
CSlice strerror_safe(int code);
#endif

#if TD_PORT_WINDOWS
string winerror_to_string(int code);
#endif

class Status {
  enum class ErrorType : int8 { General, Os };

 public:
  Status() = default;

  bool is_static() const {
    if (is_ok()) {
      return true;
    }
    return get_info().static_flag;
  }

  Status clone() const TD_WARN_UNUSED_RESULT {
    if (is_ok()) {
      return Status();
    }
    auto info = get_info();
    if (info.static_flag) {
      return clone_static(-999);
    }
    return Status(false, info.error_type, info.error_code, message());
  }

  static Status OK() TD_WARN_UNUSED_RESULT {
    return Status();
  }

  static Status Error(int err, Slice message = Slice()) TD_WARN_UNUSED_RESULT {
    return Status(false, ErrorType::General, err, message);
  }

  static Status Error(Slice message) TD_WARN_UNUSED_RESULT {
    return Error(0, message);
  }

#if TD_PORT_WINDOWS
  static Status WindowsError(int saved_error, Slice message) TD_WARN_UNUSED_RESULT {
    return Status(false, ErrorType::Os, saved_error, message);
  }
#endif

#if TD_PORT_POSIX
  static Status PosixError(int32 saved_errno, Slice message) TD_WARN_UNUSED_RESULT {
    return Status(false, ErrorType::Os, saved_errno, message);
  }
#endif

  template <int Code>
  static Status Error() {
    static Status status(true, ErrorType::General, Code, "");
    return status.clone_static(Code);
  }

  StringBuilder &print(StringBuilder &sb) const {
    if (is_ok()) {
      return sb << "OK";
    }
    Info info = get_info();
    switch (info.error_type) {
      case ErrorType::General:
        sb << "[Error";
        break;
      case ErrorType::Os:
#if TD_PORT_POSIX
        sb << "[PosixError : " << strerror_safe(info.error_code);
#elif TD_PORT_WINDOWS
        sb << "[WindowsError : " << winerror_to_string(info.error_code);
#endif
        break;
      default:
        UNREACHABLE();
        break;
    }
    sb << " : " << code() << " : " << message() << "]";
    return sb;
  }

  string to_string() const {
    auto buf = StackAllocator::alloc(4096);
    StringBuilder sb(buf.as_slice());
    print(sb);
    return sb.as_cslice().str();
  }

  // Default interface
  bool is_ok() const TD_WARN_UNUSED_RESULT {
    return !is_error();
  }

  bool is_error() const TD_WARN_UNUSED_RESULT {
    return ptr_ != nullptr;
  }

#ifdef TD_STATUS_NO_ENSURE
  void ensure() const {
    if (!is_ok()) {
      LOG(FATAL) << "Unexpected Status " << to_string();
    }
  }
  void ensure_error() const {
    if (is_ok()) {
      LOG(FATAL) << "Unexpected Status::OK";
    }
  }
#else
  void ensure_impl(CSlice file_name, int line) const {
    if (!is_ok()) {
      LOG(FATAL) << "Unexpected Status " << to_string() << " in file " << file_name << " at line " << line;
    }
  }
  void ensure_error_impl(CSlice file_name, int line) const {
    if (is_ok()) {
      LOG(FATAL) << "Unexpected Status::OK in file " << file_name << " at line " << line;
    }
  }
#endif

  void ignore() const {
    // nop
  }

  int32 code() const {
    if (is_ok()) {
      return 0;
    }
    return get_info().error_code;
  }

  CSlice message() const {
    if (is_ok()) {
      return CSlice("OK");
    }
    return CSlice(ptr_.get() + sizeof(Info));
  }

  string public_message() const {
    if (is_ok()) {
      return "OK";
    }
    Info info = get_info();
    switch (info.error_type) {
      case ErrorType::General:
        return message().str();
      case ErrorType::Os:
#if TD_PORT_POSIX
        return strerror_safe(info.error_code).str();
#elif TD_PORT_WINDOWS
        return winerror_to_string(info.error_code);
#endif
      default:
        UNREACHABLE();
        return "";
    }
  }

  const Status &error() const {
    return *this;
  }

  Status move() TD_WARN_UNUSED_RESULT {
    return std::move(*this);
  }

  Status move_as_error() TD_WARN_UNUSED_RESULT {
    return std::move(*this);
  }

  Status move_as_error_unsafe() TD_WARN_UNUSED_RESULT {
    return std::move(*this);
  }

  Status move_as_ok() = delete;

  Status move_as_ok_unsafe() = delete;

  Status move_as_error_prefix(const Status &status) const TD_WARN_UNUSED_RESULT {
    return status.move_as_error_suffix(message());
  }

  Status move_as_error_prefix(Slice prefix) const TD_WARN_UNUSED_RESULT;

  Status move_as_error_prefix_unsafe(Slice prefix) const TD_WARN_UNUSED_RESULT;

  Status move_as_error_suffix(Slice suffix) const TD_WARN_UNUSED_RESULT;

  Status move_as_error_suffix_unsafe(Slice suffix) const TD_WARN_UNUSED_RESULT;

 private:
  struct Info {
    bool static_flag : 1;
    signed int error_code : 23;
    ErrorType error_type;
  };

  struct Deleter {
    void operator()(char *ptr) {
      if (!get_info(ptr).static_flag) {
        delete[] ptr;
      }
    }
  };
  std::unique_ptr<char[], Deleter> ptr_;

  Status(Info info, Slice message) {
    size_t size = sizeof(Info) + message.size() + 1;
    ptr_ = std::unique_ptr<char[], Deleter>(new char[size]);
    char *ptr = ptr_.get();
    reinterpret_cast<Info *>(ptr)[0] = info;
    ptr += sizeof(Info);
    std::memcpy(ptr, message.begin(), message.size());
    ptr += message.size();
    *ptr = 0;
  }

  Status(bool static_flag, ErrorType error_type, int error_code, Slice message)
      : Status(to_info(static_flag, error_type, error_code), message) {
    if (static_flag) {
      TD_LSAN_IGNORE(ptr_.get());
    }
  }

  Status clone_static(int code) const TD_WARN_UNUSED_RESULT {
    LOG_CHECK(ptr_ != nullptr && get_info().static_flag) << static_cast<const void *>(ptr_.get()) << ' ' << code;
    Status result;
    result.ptr_ = std::unique_ptr<char[], Deleter>(ptr_.get());
    return result;
  }

  static Info to_info(bool static_flag, ErrorType error_type, int error_code) {
    const int MIN_ERROR_CODE = -(1 << 22) + 1;
    const int MAX_ERROR_CODE = (1 << 22) - 1;
    Info tmp;
    tmp.static_flag = static_flag;
    tmp.error_type = error_type;

    if (error_code < MIN_ERROR_CODE) {
      LOG(ERROR) << "Error code value is altered from " << error_code;
      error_code = MIN_ERROR_CODE;
    }
    if (error_code > MAX_ERROR_CODE) {
      LOG(ERROR) << "Error code value is altered from " << error_code;
      error_code = MAX_ERROR_CODE;
    }

#if TD_GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#endif
    tmp.error_code = error_code;
#if TD_GCC
#pragma GCC diagnostic pop
#endif
    CHECK(error_code == tmp.error_code);
    return tmp;
  }

  Info get_info() const {
    return get_info(ptr_.get());
  }
  static Info get_info(char *ptr) {
    return reinterpret_cast<Info *>(ptr)[0];
  }
};

template <class T = Unit>
class Result {
 public:
  using ValueT = T;
  Result() : status_(Status::Error<-1>()) {
  }
  template <class S, std::enable_if_t<!std::is_same<std::decay_t<S>, Result>::value, int> = 0>
  Result(S &&x) : status_(), value_(std::forward<S>(x)) {
  }
  struct emplace_t {};
  template <class... ArgsT>
  Result(emplace_t, ArgsT &&...args) : status_(), value_(std::forward<ArgsT>(args)...) {
  }
  Result(Status &&status) : status_(std::move(status)) {
    CHECK(status_.is_error());
  }
  Result(const Result &) = delete;
  Result &operator=(const Result &) = delete;
  Result(Result &&other) noexcept : status_(std::move(other.status_)) {
    if (status_.is_ok()) {
      new (&value_) T(std::move(other.value_));
      other.value_.~T();
    }
    other.status_ = Status::Error<-2>();
  }
  Result &operator=(Result &&other) noexcept {
    CHECK(this != &other);
    if (status_.is_ok()) {
      value_.~T();
    }
    if (other.status_.is_ok()) {
#if TD_GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
      new (&value_) T(std::move(other.value_));
#if TD_GCC
#pragma GCC diagnostic pop
#endif
      other.value_.~T();
    }
    status_ = std::move(other.status_);
    other.status_ = Status::Error<-3>();
    return *this;
  }
  template <class... ArgsT>
  void emplace(ArgsT &&...args) {
    if (status_.is_ok()) {
      value_.~T();
    }
    new (&value_) T(std::forward<ArgsT>(args)...);
    status_ = Status::OK();
  }
  ~Result() {
    if (status_.is_ok()) {
      value_.~T();
    }
  }

#ifdef TD_STATUS_NO_ENSURE
  void ensure() const {
    status_.ensure();
  }
  void ensure_error() const {
    status_.ensure_error();
  }
#else
  void ensure_impl(CSlice file_name, int line) const {
    status_.ensure_impl(file_name, line);
  }
  void ensure_error_impl(CSlice file_name, int line) const {
    status_.ensure_error_impl(file_name, line);
  }
#endif
  void ignore() const {
    status_.ignore();
  }
  bool is_ok() const {
    return status_.is_ok();
  }
  bool is_error() const {
    return status_.is_error();
  }
  const Status &error() const {
    CHECK(status_.is_error());
    return status_;
  }
  Status move_as_error() TD_WARN_UNUSED_RESULT {
    CHECK(status_.is_error());
    SCOPE_EXIT {
      status_ = Status::Error<-4>();
    };
    return std::move(status_);
  }
  Status move_as_error_unsafe() TD_WARN_UNUSED_RESULT {
    SCOPE_EXIT {
      status_ = Status::Error<-5>();
    };
    return std::move(status_);
  }
  Status move_as_error_prefix(Slice prefix) TD_WARN_UNUSED_RESULT {
    SCOPE_EXIT {
      status_ = Status::Error<-6>();
    };
    return status_.move_as_error_prefix(prefix);
  }
  Status move_as_error_prefix_unsafe(Slice prefix) TD_WARN_UNUSED_RESULT {
    SCOPE_EXIT {
      status_ = Status::Error<-7>();
    };
    return status_.move_as_error_prefix_unsafe(prefix);
  }
  Status move_as_error_prefix(const Status &prefix) TD_WARN_UNUSED_RESULT {
    SCOPE_EXIT {
      status_ = Status::Error<-8>();
    };
    return status_.move_as_error_prefix(prefix);
  }

  Status move_as_error_suffix(Slice suffix) TD_WARN_UNUSED_RESULT {
    SCOPE_EXIT {
      status_ = Status::Error<-9>();
    };
    return status_.move_as_error_suffix(suffix);
  }
  Status move_as_error_suffix_unsafe(Slice suffix) TD_WARN_UNUSED_RESULT {
    SCOPE_EXIT {
      status_ = Status::Error<-10>();
    };
    return status_.move_as_error_suffix_unsafe(suffix);
  }

  const T &ok() const {
    LOG_CHECK(status_.is_ok()) << status_;
    return value_;
  }
  T &ok_ref() {
    LOG_CHECK(status_.is_ok()) << status_;
    return value_;
  }
  const T &ok_ref() const {
    LOG_CHECK(status_.is_ok()) << status_;
    return value_;
  }
  T move_as_ok() {
    LOG_CHECK(status_.is_ok()) << status_;
    return std::move(value_);
  }
  T move_as_ok_unsafe() {
    return std::move(value_);
  }

  Result<T> clone() const TD_WARN_UNUSED_RESULT {
    if (is_ok()) {
      return Result<T>(ok());  // TODO: return clone(ok());
    }
    return error().clone();
  }
  void clear() {
    *this = Result<T>();
  }

  template <class F>
  Result<decltype(std::declval<F>()(std::declval<T>()))> move_map(F &&f) {
    if (is_error()) {
      return move_as_error_unsafe();
    }
    return f(move_as_ok_unsafe());
  }

  template <class F>
  decltype(std::declval<F>()(std::declval<T>())) move_fmap(F &&f) {
    if (is_error()) {
      return move_as_error_unsafe();
    }
    return f(move_as_ok_unsafe());
  }

 private:
  Status status_;
  union {
    T value_;
  };
};

template <>
inline Result<Unit>::Result(Status &&status) : status_(std::move(status)) {
  // no assert
}

inline StringBuilder &operator<<(StringBuilder &string_builder, const Status &status) {
  return status.print(string_builder);
}

template <class T>
StringBuilder &operator<<(StringBuilder &sb, const Result<T> &result) {
  if (result.is_ok()) {
    return sb << "Ok{" << result.ok() << '}';
  }
  return sb << result.error();
}

template <class T, class S>
bool operator==(const S &a, const Result<T> &b) {
  return b.is_ok() && a == b.ok();
}

template <class T, class S>
bool operator==(const Result<S> &a, const T &b) {
  return a.is_ok() && a.ok() == b;
}

}  // namespace td