From 1b86d41c7844729768b2ffd096e1cded3c145a93 Mon Sep 17 00:00:00 2001 From: Elliott Hughes Date: Fri, 6 Apr 2018 17:45:22 -0700 Subject: [PATCH] Add SIZEOF_MEMBER. Bug: N/A Test: ran tests Change-Id: Icb7e8ae83d242c867b71a990b08eb1a62ed1482c --- base/Android.bp | 1 + base/include/android-base/macros.h | 4 ++++ base/macros_test.cpp | 30 ++++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 base/macros_test.cpp diff --git a/base/Android.bp b/base/Android.bp index 7b0ba11d0..12b396957 100644 --- a/base/Android.bp +++ b/base/Android.bp @@ -124,6 +124,7 @@ cc_test { "errors_test.cpp", "file_test.cpp", "logging_test.cpp", + "macros_test.cpp", "parsedouble_test.cpp", "parseint_test.cpp", "parsenetaddress_test.cpp", diff --git a/base/include/android-base/macros.h b/base/include/android-base/macros.h index 25f2ff4ed..fd6efb2a8 100644 --- a/base/include/android-base/macros.h +++ b/base/include/android-base/macros.h @@ -20,6 +20,8 @@ #include // for size_t #include // for TEMP_FAILURE_RETRY +#include + // bionic and glibc both have TEMP_FAILURE_RETRY, but eg Mac OS' libc doesn't. #ifndef TEMP_FAILURE_RETRY #define TEMP_FAILURE_RETRY(exp) \ @@ -114,6 +116,8 @@ char(&ArraySizeHelper(T(&array)[N]))[N]; // NOLINT(readability/casting) ((sizeof(a) / sizeof(*(a))) / \ static_cast(!(sizeof(a) % sizeof(*(a))))) +#define SIZEOF_MEMBER(t, f) sizeof(std::declval().f) + // Changing this definition will cause you a lot of pain. A majority of // vendor code defines LIKELY and UNLIKELY this way, and includes // this header through an indirect path. diff --git a/base/macros_test.cpp b/base/macros_test.cpp new file mode 100644 index 000000000..2b522db5c --- /dev/null +++ b/base/macros_test.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "android-base/macros.h" + +#include + +#include + +TEST(macros, SIZEOF_MEMBER_macro) { + struct S { + int32_t i32; + double d; + }; + ASSERT_EQ(4U, SIZEOF_MEMBER(S, i32)); + ASSERT_EQ(8U, SIZEOF_MEMBER(S, d)); +}