summaryrefslogtreecommitdiff
path: root/protocols/Telegram/tdlib/td/tdutils/test/SharedSlice.cpp
blob: 14fd9562a5b6b09a20ffd94e7489a96c04c7f248 (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
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2024
//
// 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)
//
#include "td/utils/common.h"
#include "td/utils/port/thread.h"
#include "td/utils/SharedSlice.h"
#include "td/utils/tests.h"

char disable_linker_warning_about_empty_file_tdutils_test_shared_slice_cpp TD_UNUSED;

#if !TD_THREAD_UNSUPPORTED
TEST(SharedSlice, Hands) {
  {
    td::SharedSlice h("hello");
    ASSERT_EQ("hello", h.as_slice());
    // auto g = h; // CE
    auto g = h.clone();
    ASSERT_EQ("hello", h.as_slice());
    ASSERT_EQ("hello", g.as_slice());
  }

  {
    td::SharedSlice h("hello");
    td::UniqueSharedSlice g(std::move(h));
    ASSERT_EQ("", h.as_slice());
    ASSERT_EQ("hello", g.as_slice());
  }
  {
    td::SharedSlice h("hello");
    td::SharedSlice t = h.clone();
    td::UniqueSharedSlice g(std::move(h));
    ASSERT_EQ("", h.as_slice());
    ASSERT_EQ("hello", g.as_slice());
    ASSERT_EQ("hello", t.as_slice());
  }

  {
    td::UniqueSharedSlice g(5);
    g.as_mutable_slice().copy_from("hello");
    td::SharedSlice h(std::move(g));
    ASSERT_EQ("hello", h);
    ASSERT_EQ("", g);
  }

  {
    td::UniqueSlice h("hello");
    td::UniqueSlice g(std::move(h));
    ASSERT_EQ("", h.as_slice());
    ASSERT_EQ("hello", g.as_slice());
  }

  {
    td::SecureString h("hello");
    td::SecureString g(std::move(h));
    ASSERT_EQ("", h.as_slice());
    ASSERT_EQ("hello", g.as_slice());
  }

  {
    td::Stage stage;
    td::SharedSlice a;
    td::SharedSlice b;
    td::vector<td::thread> threads(2);
    for (int i = 0; i < 2; i++) {
      threads[i] = td::thread([i, &stage, &a, &b] {
        for (int j = 0; j < 10000; j++) {
          if (i == 0) {
            a = td::SharedSlice("hello");
            b = a.clone();
          }
          stage.wait((2 * j + 1) * 2);
          if (i == 0) {
            ASSERT_EQ('h', a[0]);
            a.clear();
          } else {
            td::UniqueSharedSlice c(std::move(b));
            c.as_mutable_slice()[0] = '!';
          }
          stage.wait((2 * j + 2) * 2);
        }
      });
    }
    for (auto &thread : threads) {
      thread.join();
    }
  }
}
#endif