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
|
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/types/strong_alias.h"
#include <cstdint>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include "base/types/supports_ostream_operator.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/perfetto/include/perfetto/test/traced_value_test_support.h"
namespace base {
namespace {
// For test correctnenss, it's important that these getters return lexically
// incrementing values as |index| grows.
template <typename T>
T GetExampleValue(int index);
template <>
int GetExampleValue<int>(int index) {
return 5 + index;
}
template <>
uint64_t GetExampleValue<uint64_t>(int index) {
return 500U + index;
}
template <>
std::string GetExampleValue<std::string>(int index) {
return std::string(index, 'a');
}
template <typename T, typename U>
bool StreamOutputSame(const T& a, const U& b) {
std::stringstream ssa;
ssa << a;
std::stringstream ssb;
ssb << b;
return ssa.str() == ssb.str();
}
} // namespace
template <typename T>
class StrongAliasTest : public ::testing::Test {};
using TestedTypes = ::testing::Types<int, uint64_t, std::string>;
TYPED_TEST_SUITE(StrongAliasTest, TestedTypes);
TYPED_TEST(StrongAliasTest, ValueAccessesUnderlyingValue) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
// Const value getter.
const FooAlias const_alias(GetExampleValue<TypeParam>(1));
EXPECT_EQ(GetExampleValue<TypeParam>(1), const_alias.value());
static_assert(
std::is_const_v<
typename std::remove_reference<decltype(const_alias.value())>::type>,
"Reference returned by const value getter should be const.");
}
TYPED_TEST(StrongAliasTest, ExplicitConversionToUnderlyingValue) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
const FooAlias const_alias(GetExampleValue<TypeParam>(1));
EXPECT_EQ(GetExampleValue<TypeParam>(1), static_cast<TypeParam>(const_alias));
}
TYPED_TEST(StrongAliasTest, CanBeCopyConstructed) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
FooAlias alias(GetExampleValue<TypeParam>(0));
FooAlias copy_constructed = alias;
EXPECT_EQ(copy_constructed, alias);
FooAlias copy_assigned;
copy_assigned = alias;
EXPECT_EQ(copy_assigned, alias);
}
TYPED_TEST(StrongAliasTest, CanBeMoveConstructed) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
FooAlias alias(GetExampleValue<TypeParam>(0));
FooAlias move_constructed = std::move(alias);
EXPECT_EQ(move_constructed, FooAlias(GetExampleValue<TypeParam>(0)));
FooAlias alias2(GetExampleValue<TypeParam>(2));
FooAlias move_assigned;
move_assigned = std::move(alias2);
EXPECT_EQ(move_assigned, FooAlias(GetExampleValue<TypeParam>(2)));
// Check that FooAlias is nothrow move constructible. This matters for
// performance when used in std::vectors.
static_assert(std::is_nothrow_move_constructible_v<FooAlias>,
"Error: Alias is not nothow move constructible");
}
TYPED_TEST(StrongAliasTest, CanBeConstructedFromMoveOnlyType) {
// Note, using a move-only unique_ptr to T:
using FooAlias = StrongAlias<class FooTag, std::unique_ptr<TypeParam>>;
FooAlias a(std::make_unique<TypeParam>(GetExampleValue<TypeParam>(0)));
EXPECT_EQ(*a.value(), GetExampleValue<TypeParam>(0));
auto bare_value = std::make_unique<TypeParam>(GetExampleValue<TypeParam>(1));
FooAlias b(std::move(bare_value));
EXPECT_EQ(*b.value(), GetExampleValue<TypeParam>(1));
}
TYPED_TEST(StrongAliasTest, MutableOperatorArrow) {
// Note, using a move-only unique_ptr to T:
using Ptr = std::unique_ptr<TypeParam>;
using FooAlias = StrongAlias<class FooTag, Ptr>;
FooAlias a(std::make_unique<TypeParam>());
EXPECT_TRUE(a.value());
// Check that `a` can be modified through the use of operator->.
a->reset();
EXPECT_FALSE(a.value());
}
TYPED_TEST(StrongAliasTest, MutableOperatorStar) {
// Note, using a move-only unique_ptr to T:
using Ptr = std::unique_ptr<TypeParam>;
using FooAlias = StrongAlias<class FooTag, Ptr>;
FooAlias a(std::make_unique<TypeParam>());
FooAlias b(std::make_unique<TypeParam>());
EXPECT_TRUE(*a);
EXPECT_TRUE(*b);
// Check that both the mutable l-value and r-value overloads work and we can
// move out of the aliases.
{ Ptr ignore(*std::move(a)); }
{ Ptr ignore(std::move(*b)); }
EXPECT_FALSE(a.value()); // NOLINT(bugprone-use-after-move)
EXPECT_FALSE(b.value());
}
TYPED_TEST(StrongAliasTest, MutableValue) {
// Note, using a move-only unique_ptr to T:
using Ptr = std::unique_ptr<TypeParam>;
using FooAlias = StrongAlias<class FooTag, Ptr>;
FooAlias a(std::make_unique<TypeParam>());
FooAlias b(std::make_unique<TypeParam>());
EXPECT_TRUE(a.value());
EXPECT_TRUE(b.value());
// Check that both the mutable l-value and r-value overloads work and we can
// move out of the aliases.
{ Ptr ignore(std::move(a).value()); }
{ Ptr ignore(std::move(b.value())); }
EXPECT_FALSE(a.value()); // NOLINT(bugprone-use-after-move)
EXPECT_FALSE(b.value());
}
TYPED_TEST(StrongAliasTest, CanBeWrittenToOutputStream) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
const FooAlias a(GetExampleValue<TypeParam>(0));
EXPECT_TRUE(StreamOutputSame(GetExampleValue<TypeParam>(0), a)) << a;
}
TYPED_TEST(StrongAliasTest, SizeSameAsUnderlyingType) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
static_assert(sizeof(FooAlias) == sizeof(TypeParam),
"StrongAlias should be as large as the underlying type.");
}
TYPED_TEST(StrongAliasTest, IsDefaultConstructible) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
static_assert(std::is_default_constructible_v<FooAlias>,
"Should be possible to default-construct a StrongAlias.");
static_assert(
std::is_trivially_default_constructible_v<FooAlias> ==
std::is_trivially_default_constructible_v<TypeParam>,
"Should be possible to trivially default-construct a StrongAlias iff the "
"underlying type is trivially default constructible.");
}
TEST(StrongAliasTest, TrivialTypeAliasIsStandardLayout) {
using FooAlias = StrongAlias<class FooTag, int>;
static_assert(std::is_standard_layout_v<FooAlias>,
"int-based alias should have standard layout. ");
static_assert(std::is_trivially_copyable_v<FooAlias>,
"int-based alias should be trivially copyable. ");
}
TYPED_TEST(StrongAliasTest, CannotBeCreatedFromDifferentAlias) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
using BarAlias = StrongAlias<class BarTag, TypeParam>;
static_assert(!std::is_constructible_v<FooAlias, BarAlias>,
"Should be impossible to construct FooAlias from a BarAlias.");
static_assert(!std::is_convertible_v<BarAlias, FooAlias>,
"Should be impossible to convert a BarAlias into FooAlias.");
}
TYPED_TEST(StrongAliasTest, CannotBeImplicitlyConverterToUnderlyingValue) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
static_assert(!std::is_convertible_v<FooAlias, TypeParam>,
"Should be impossible to implicitly convert a StrongAlias into "
"an underlying type.");
}
TYPED_TEST(StrongAliasTest, ComparesEqualToSameValue) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
// Comparison to self:
const FooAlias a = FooAlias(GetExampleValue<TypeParam>(0));
EXPECT_EQ(a, a);
EXPECT_FALSE(a != a);
EXPECT_TRUE(a >= a);
EXPECT_TRUE(a <= a);
EXPECT_FALSE(a > a);
EXPECT_FALSE(a < a);
// Comparison to other equal object:
const FooAlias b = FooAlias(GetExampleValue<TypeParam>(0));
EXPECT_EQ(a, b);
EXPECT_FALSE(a != b);
EXPECT_TRUE(a >= b);
EXPECT_TRUE(a <= b);
EXPECT_FALSE(a > b);
EXPECT_FALSE(a < b);
}
TYPED_TEST(StrongAliasTest, ComparesCorrectlyToDifferentValue) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
const FooAlias a = FooAlias(GetExampleValue<TypeParam>(0));
const FooAlias b = FooAlias(GetExampleValue<TypeParam>(1));
EXPECT_NE(a, b);
EXPECT_FALSE(a == b);
EXPECT_TRUE(b >= a);
EXPECT_TRUE(a <= b);
EXPECT_TRUE(b > a);
EXPECT_TRUE(a < b);
}
TEST(StrongAliasTest, CanBeDerivedFrom) {
// Aliases can be enriched by custom operations or validations if needed.
// Ideally, one could go from a 'using' declaration to a derived class to add
// those methods without the need to change any other code.
class CountryCode : public StrongAlias<CountryCode, std::string> {
public:
explicit CountryCode(const std::string& value)
: StrongAlias<CountryCode, std::string>::StrongAlias(value) {
if (value_.length() != 2) {
// Country code invalid!
value_.clear(); // is_null() will return true.
}
}
bool is_null() const { return value_.empty(); }
};
CountryCode valid("US");
EXPECT_FALSE(valid.is_null());
CountryCode invalid("United States");
EXPECT_TRUE(invalid.is_null());
}
TEST(StrongAliasTest, CanWrapComplexStructures) {
// A pair of strings implements odering and can, in principle, be used as
// a base of StrongAlias.
using PairOfStrings = std::pair<std::string, std::string>;
using ComplexAlias = StrongAlias<class FooTag, PairOfStrings>;
ComplexAlias a1{std::make_pair("aaa", "bbb")};
ComplexAlias a2{std::make_pair("ccc", "ddd")};
EXPECT_TRUE(a1 < a2);
EXPECT_TRUE(a1.value() == PairOfStrings("aaa", "bbb"));
// Note a caveat, an std::pair doesn't have an overload of operator<<, and it
// cannot be easily added since ADL rules would require it to be in the std
// namespace. So we can't print ComplexAlias.
}
TYPED_TEST(StrongAliasTest, CanBeKeysInStdUnorderedMap) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
std::unordered_map<FooAlias, std::string> map;
FooAlias k1(GetExampleValue<TypeParam>(0));
FooAlias k2(GetExampleValue<TypeParam>(1));
map[k1] = "value1";
map[k2] = "value2";
EXPECT_EQ(map[k1], "value1");
EXPECT_EQ(map[k2], "value2");
}
TYPED_TEST(StrongAliasTest, CanBeKeysInStdMap) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
std::map<FooAlias, std::string> map;
FooAlias k1(GetExampleValue<TypeParam>(0));
FooAlias k2(GetExampleValue<TypeParam>(1));
map[k1] = "value1";
map[k2] = "value2";
EXPECT_EQ(map[k1], "value1");
EXPECT_EQ(map[k2], "value2");
}
TYPED_TEST(StrongAliasTest, CanDifferentiateOverloads) {
using FooAlias = StrongAlias<class FooTag, TypeParam>;
using BarAlias = StrongAlias<class BarTag, TypeParam>;
class Scope {
public:
static std::string Overload(FooAlias) { return "FooAlias"; }
static std::string Overload(BarAlias) { return "BarAlias"; }
};
EXPECT_EQ("FooAlias", Scope::Overload(FooAlias()));
EXPECT_EQ("BarAlias", Scope::Overload(BarAlias()));
}
TEST(StrongAliasTest, EnsureConstexpr) {
using FooAlias = StrongAlias<class FooTag, int>;
using BarAlias = StrongAlias<class BarTag, std::string_view>;
// Check constructors.
static constexpr FooAlias kZero{};
static constexpr FooAlias kOne(1);
static constexpr BarAlias kHello("Hello");
// Check operator->.
static_assert(kHello->size() == 5, "");
// Check operator*.
static_assert(*kZero == 0, "");
static_assert(*kOne == 1, "");
static_assert(*kHello == "Hello", "");
// Check value().
static_assert(kZero.value() == 0, "");
static_assert(kOne.value() == 1, "");
// Check explicit conversions to underlying type.
static_assert(static_cast<int>(kZero) == 0, "");
static_assert(static_cast<int>(kOne) == 1, "");
// Check comparison operations.
static_assert(kZero == kZero, "");
static_assert(kZero != kOne, "");
static_assert(kZero < kOne, "");
static_assert(kZero <= kOne, "");
static_assert(kOne > kZero, "");
static_assert(kOne >= kZero, "");
}
// This next test is compile-time, and thus not in an actual TEST since it would
// just result in running an empty test.
void StreamOperatorExists() {
// Aliases of ints should be streamable because ints are streamable.
using StreamableAlias = StrongAlias<class IntTag, int>;
static_assert(internal::SupportsOstreamOperator<StreamableAlias>);
// Aliases of a class which does not expose a stream operator should
// themselves not be streamable.
class Scope {
public:
Scope() = default;
};
using NonStreamableAlias = StrongAlias<class ScopeTag, Scope>;
static_assert(!internal::SupportsOstreamOperator<NonStreamableAlias>);
}
TEST(StrongAliasTest, TracedValueSupport) {
using IntAlias = StrongAlias<class FooTag, int>;
EXPECT_EQ(perfetto::TracedValueToString(IntAlias(42)), "42");
}
} // namespace base
|