token_type.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_TYPES_TOKEN_TYPE_H_
  5. #define BASE_TYPES_TOKEN_TYPE_H_
  6. #include <type_traits>
  7. #include "base/check.h"
  8. #include "base/types/strong_alias.h"
  9. #include "base/unguessable_token.h"
  10. namespace base {
  11. // A specialization of StrongAlias for UnguessableToken. Unlike
  12. // UnguessableToken, a TokenType<...> does not default to null and does not
  13. // expose the concept of null tokens. If you need to indicate a null token,
  14. // please use absl::optional<TokenType<...>>.
  15. template <typename TypeMarker>
  16. class TokenType : public StrongAlias<TypeMarker, UnguessableToken> {
  17. private:
  18. using Super = StrongAlias<TypeMarker, UnguessableToken>;
  19. public:
  20. TokenType() : Super(UnguessableToken::Create()) {}
  21. explicit TokenType(const UnguessableToken& token) : Super(token) {
  22. // Disallow attempts to force a null UnguessableToken into a strongly-typed
  23. // token. Allowing in-place nullability of UnguessableToken was a design
  24. // mistake; do not propagate that mistake here as well.
  25. CHECK(!token.is_empty());
  26. }
  27. TokenType(const TokenType& token) : Super(token.value()) {}
  28. TokenType(TokenType&& token) noexcept : Super(token.value()) {}
  29. TokenType& operator=(const TokenType& token) = default;
  30. TokenType& operator=(TokenType&& token) noexcept = default;
  31. // This object allows default assignment operators for compatibility with
  32. // STL containers.
  33. // Hash functor for use in unordered containers.
  34. struct Hasher {
  35. using argument_type = TokenType;
  36. using result_type = size_t;
  37. result_type operator()(const argument_type& token) const {
  38. return UnguessableTokenHash()(token.value());
  39. }
  40. };
  41. // Mimic the UnguessableToken API for ease and familiarity of use.
  42. std::string ToString() const { return this->value().ToString(); }
  43. };
  44. } // namespace base
  45. #endif // BASE_TYPES_TOKEN_TYPE_H_