llvm/unittests/ADT/PointerEmbeddedIntTest.cpp
Chandler Carruth ca4af1ae34 [ADT] Add an abstraction for embedding an integer within a pointer-like
type.

This makes it easy and safe to use a set of flags as one elmenet of
a tagged union with pointers. There is quite a bit of code that has
historically done this by casting arbitrary integers to "pointers" and
assuming that this was safe and reliable. It is neither, and has started
to rear its head by triggering safety asserts in various abstractions
like PointerLikeTypeTraits when the integers chosen are invariably poor
choices for *some* platform and *some* situation. Not to mention the
(hopefully unlikely) prospect of one of these integers actually getting
allocated!

With this, it will be straightforward to build type safe abstractions
like this without being error prone. The abstraction itself is also
remarkably simple thanks to the implicit conversion.

This use case and pattern was also independently created by the folks
working on Swift, and they're going to incrementally add any missing
functionality they find.

Differential Revision: http://reviews.llvm.org/D15844

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@257284 91177308-0d34-0410-b5e6-96231b3b80d8
2016-01-10 09:40:13 +00:00

47 lines
1.1 KiB
C++

//===- llvm/unittest/ADT/PointerEmbeddedIntTest.cpp -----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/PointerEmbeddedInt.h"
using namespace llvm;
namespace {
TEST(PointerEmbeddedIntTest, Basic) {
PointerEmbeddedInt<int, CHAR_BIT> I = 42, J = 43;
EXPECT_EQ(42, I);
EXPECT_EQ(43, I + 1);
EXPECT_EQ(sizeof(uintptr_t) * CHAR_BIT - CHAR_BIT,
PointerLikeTypeTraits<decltype(I)>::NumLowBitsAvailable);
EXPECT_FALSE(I == J);
EXPECT_TRUE(I != J);
EXPECT_TRUE(I < J);
EXPECT_FALSE(I > J);
EXPECT_TRUE(I <= J);
EXPECT_FALSE(I >= J);
EXPECT_FALSE(I == 43);
EXPECT_TRUE(I != 43);
EXPECT_TRUE(I < 43);
EXPECT_FALSE(I > 43);
EXPECT_TRUE(I <= 43);
EXPECT_FALSE(I >= 43);
EXPECT_FALSE(42 == J);
EXPECT_TRUE(42 != J);
EXPECT_TRUE(42 < J);
EXPECT_FALSE(42 > J);
EXPECT_TRUE(42 <= J);
EXPECT_FALSE(42 >= J);
}
} // end anonymous namespace