1 // Copyright 2019 The Android Open Source Project
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 // http://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 #pragma once
16
17 // This file defines macroes ARRAY_SIZE() and STRING_LITERAL_LENGTH for static
18 // array size and string literal length detection
19 // If used from C, it's just a standard division of sizes. In C++ though, it
20 // would give you a compile-time error if used with something other than
21 // a built-in array or std::array<>
22 // Also, C++ defines corresponding constexpr functions for the same purpose
23
24 #ifndef __cplusplus
25 # define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
26 # define STRING_LITERAL_LENGTH(str) (ARRAY_SIZE(str) - 1))
27 #else
28
29 #include <array>
30 #include <stddef.h>
31
32 namespace android {
33 namespace base {
34
35 template <class T, size_t N>
arraySize(const T (& arr)[N])36 static constexpr size_t arraySize(const T (&arr)[N]) {
37 return N;
38 }
39
40 template <class T, size_t N>
arraySize(const std::array<T,N> & arr)41 static constexpr size_t arraySize(const std::array<T, N>& arr) {
42 return N;
43 }
44
45 template <size_t N>
stringLiteralLength(const char (& str)[N])46 static constexpr size_t stringLiteralLength(const char (&str)[N]) {
47 return N - 1;
48 }
49
50 } // namespace base
51 } // namespace android
52
53 // for those who like macros, define it to be a simple function call
54 #define ARRAY_SIZE(arr) (::android::base::arraySize(arr))
55 #define STRING_LITERAL_LENGTH(str) (::android::base::stringLiteralLength(str))
56
57 #endif // __cplusplus
58