summaryrefslogtreecommitdiff
path: root/protocols/Telegram/tdlib/td/tddb/td/db/TsSeqKeyValue.h
blob: 8d94d7967308cf2073f16fa745c564b966bfa3bb (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
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// 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/db/SeqKeyValue.h"

#include "td/utils/port/RwMutex.h"
#include "td/utils/Slice.h"

#include <unordered_map>
#include <utility>

namespace td {
class TsSeqKeyValue {
 public:
  using SeqNo = SeqKeyValue::SeqNo;
  TsSeqKeyValue() = default;
  explicit TsSeqKeyValue(SeqKeyValue kv) : kv_(std::move(kv)) {
  }

  TsSeqKeyValue(TsSeqKeyValue &&) = default;
  TsSeqKeyValue &operator=(TsSeqKeyValue &&) = default;
  TsSeqKeyValue(const TsSeqKeyValue &) = delete;
  TsSeqKeyValue &operator=(const TsSeqKeyValue &) = delete;
  ~TsSeqKeyValue() = default;

  SeqNo set(Slice key, Slice value) {
    auto lock = rw_mutex_.lock_write().move_as_ok();
    return kv_.set(key, value);
  }
  std::pair<SeqNo, RwMutex::WriteLock> set_and_lock(Slice key, Slice value) {
    auto lock = rw_mutex_.lock_write().move_as_ok();
    return std::make_pair(kv_.set(key, value), std::move(lock));
  }
  SeqNo erase(const string &key) {
    auto lock = rw_mutex_.lock_write().move_as_ok();
    return kv_.erase(key);
  }
  std::pair<SeqNo, RwMutex::WriteLock> erase_and_lock(const string &key) {
    auto lock = rw_mutex_.lock_write().move_as_ok();
    return std::make_pair(kv_.erase(key), std::move(lock));
  }
  string get(const string &key) {
    auto lock = rw_mutex_.lock_read().move_as_ok();
    return kv_.get(key);
  }
  size_t size() const {
    return kv_.size();
  }
  std::unordered_map<string, string> get_all() {
    auto lock = rw_mutex_.lock_write().move_as_ok();
    return kv_.get_all();
  }
  // not thread safe method
  SeqKeyValue &inner() {
    return kv_;
  }

  auto lock() {
    return rw_mutex_.lock_write().move_as_ok();
  }

 private:
  RwMutex rw_mutex_;
  SeqKeyValue kv_;
};
}  // namespace td