xref: /aosp_15_r20/external/abseil-cpp/absl/base/internal/unique_small_name_test.cc (revision 9356374a3709195abf420251b3e825997ff56c0f)
1 // Copyright 2020 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "gtest/gtest.h"
16 #include "absl/base/optimization.h"
17 #include "absl/strings/string_view.h"
18 
19 // This test by itself does not do anything fancy, but it serves as binary I can
20 // query in shell test.
21 
22 namespace {
23 
24 template <class T>
DoNotOptimize(const T & var)25 void DoNotOptimize(const T& var) {
26 #ifdef __GNUC__
27   asm volatile("" : "+m"(const_cast<T&>(var)));
28 #else
29   std::cout << (void*)&var;
30 #endif
31 }
32 
33 int very_long_int_variable_name ABSL_INTERNAL_UNIQUE_SMALL_NAME() = 0;
34 char very_long_str_variable_name[] ABSL_INTERNAL_UNIQUE_SMALL_NAME() = "abc";
35 
TEST(UniqueSmallName,NonAutomaticVar)36 TEST(UniqueSmallName, NonAutomaticVar) {
37   EXPECT_EQ(very_long_int_variable_name, 0);
38   EXPECT_EQ(absl::string_view(very_long_str_variable_name), "abc");
39 }
40 
41 int VeryLongFreeFunctionName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
42 
TEST(UniqueSmallName,FreeFunction)43 TEST(UniqueSmallName, FreeFunction) {
44   DoNotOptimize(&VeryLongFreeFunctionName);
45 
46   EXPECT_EQ(VeryLongFreeFunctionName(), 456);
47 }
48 
VeryLongFreeFunctionName()49 int VeryLongFreeFunctionName() { return 456; }
50 
51 struct VeryLongStructName {
52   explicit VeryLongStructName(int i);
53 
54   int VeryLongMethodName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
55 
56   static int VeryLongStaticMethodName() ABSL_INTERNAL_UNIQUE_SMALL_NAME();
57 
58  private:
59   int fld;
60 };
61 
TEST(UniqueSmallName,Struct)62 TEST(UniqueSmallName, Struct) {
63   VeryLongStructName var(10);
64 
65   DoNotOptimize(var);
66   DoNotOptimize(&VeryLongStructName::VeryLongMethodName);
67   DoNotOptimize(&VeryLongStructName::VeryLongStaticMethodName);
68 
69   EXPECT_EQ(var.VeryLongMethodName(), 10);
70   EXPECT_EQ(VeryLongStructName::VeryLongStaticMethodName(), 123);
71 }
72 
VeryLongStructName(int i)73 VeryLongStructName::VeryLongStructName(int i) : fld(i) {}
VeryLongMethodName()74 int VeryLongStructName::VeryLongMethodName() { return fld; }
VeryLongStaticMethodName()75 int VeryLongStructName::VeryLongStaticMethodName() { return 123; }
76 
77 }  // namespace
78