summaryrefslogtreecommitdiff
path: root/chromium/components/sessions/core/session_id.h
blob: 47b240195fe6ca879ffe73ad134c86472649a30a (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
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_SESSIONS_CORE_SESSION_ID_H_
#define COMPONENTS_SESSIONS_CORE_SESSION_ID_H_

#include <stdint.h>
#include <functional>
#include <iosfwd>

#include "components/sessions/core/sessions_export.h"

// Uniquely identifies a tab or window for the duration of a session. Pass by
// value.
class SESSIONS_EXPORT SessionID {
 public:
  typedef int32_t id_type;

  // Creates a new instance representing an ID that has never been used before
  // locally (even across browser restarts).
  static SessionID NewUnique();

  // Special value representing a null-like, invalid ID. It's the only value
  // that returns false for is_valid().
  static constexpr SessionID InvalidValue() { return SessionID(-1); }

  // Should be used rarely because it can lead to collisions.
  static constexpr SessionID FromSerializedValue(id_type value) {
    return IsValidValue(value) ? SessionID(value) : InvalidValue();
  }

  // Returns whether a certain underlying ID value would represent a valid
  // SessionID instance. Note that zero is also considered invalid.
  static constexpr bool IsValidValue(id_type value) { return value > 0; }

  // All IDs are valid except InvalidValue() above.
  bool is_valid() const { return IsValidValue(id_); }

  // Returns the underlying id.
  id_type id() const { return id_; }

  struct Hasher {
    inline std::size_t operator()(SessionID id) const { return id.id(); }
  };

 private:
  explicit constexpr SessionID(id_type id) : id_(id) {}

  id_type id_;
};

inline bool operator==(SessionID lhs, SessionID rhs) {
  return lhs.id() == rhs.id();
}

inline bool operator!=(SessionID lhs, SessionID rhs) {
  return lhs.id() != rhs.id();
}

inline bool operator<(SessionID lhs, SessionID rhs) {
  return lhs.id() < rhs.id();
}

// For use in gtest-based unit tests.
SESSIONS_EXPORT std::ostream& operator<<(std::ostream& out, SessionID id);

#endif  // COMPONENTS_SESSIONS_CORE_SESSION_ID_H_