1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 * Miscellaneous uncategorized functionality. Please add new functionality to
9 * new headers, or to other appropriate existing headers, not here.
12 #ifndef mozilla_Util_h
13 #define mozilla_Util_h
15 #include "mozilla/Assertions.h"
16 #include "mozilla/Attributes.h"
17 #include "mozilla/Types.h"
21 #include "mozilla/Alignment.h"
26 * Safely subtract two pointers when it is known that end >= begin. This avoids
27 * the common compiler bug that if (size_t(end) - size_t(begin)) has the MSB
28 * set, the unsigned subtraction followed by right shift will produce -1, or
29 * size_t(-1), instead of the real difference.
32 MOZ_ALWAYS_INLINE
size_t
33 PointerRangeSize(T
* begin
, T
* end
)
35 MOZ_ASSERT(end
>= begin
);
36 return (size_t(end
) - size_t(begin
)) / sizeof(T
);
40 * Compute the length of an array with constant length. (Use of this method
41 * with a non-array pointer will not compile.)
43 * Beware of the implicit trailing '\0' when using this with string constants.
45 template<typename T
, size_t N
>
47 ArrayLength(T (&arr
)[N
])
53 * Compute the address one past the last element of a constant-length array.
55 * Beware of the implicit trailing '\0' when using this with string constants.
57 template<typename T
, size_t N
>
61 return arr
+ ArrayLength(arr
);
64 } /* namespace mozilla */
66 #endif /* __cplusplus */
69 * MOZ_ARRAY_LENGTH() is an alternative to mozilla::ArrayLength() for C files
70 * that can't use C++ template functions and for static_assert() calls that
71 * can't call ArrayLength() when it is not a C++11 constexpr function.
73 #ifdef MOZ_HAVE_CXX11_CONSTEXPR
74 # define MOZ_ARRAY_LENGTH(array) mozilla::ArrayLength(array)
76 # define MOZ_ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0]))
79 #endif /* mozilla_Util_h */