blob: 3844e7d96590084dc1d594498045e002956e6fc5 [file] [log] [blame]
Mark Salyzyn0eeb06b2016-12-02 10:08:48 -08001/*
2 * Copyright (C) 2014-2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _ANDROID_UTILS_FASTSTRCMP_H__
18#define _ANDROID_UTILS_FASTSTRCMP_H__
19
20#ifdef __cplusplus
21
22// Optimized for instruction cache locality
23//
24// Template class fastcmp used to create more time-efficient str*cmp
25// functions by pre-checking the first character before resorting
26// to calling the underlying string function. Profiled with a
27// measurable speedup when used in hot code. Usage is of the form:
28//
29// fastcmp<strncmp>(str1, str2, len)
30//
31// NB: Does not work for the case insensitive str*cmp functions.
32// NB: Returns boolean, do not use if expecting to check negative value.
33// Thus not semantically identical to the expected function behavior.
34
35template <int (*cmp)(const char *l, const char *r, const size_t s)>
36static inline int fastcmp(const char *l, const char *r, const size_t s) {
37 return (*l != *r) || cmp(l + 1, r + 1, s - 1);
38}
39
40template <int (*cmp)(const void *l, const void *r, const size_t s)>
41static inline int fastcmp(const void *lv, const void *rv, const size_t s) {
42 const char *l = static_cast<const char *>(lv);
43 const char *r = static_cast<const char *>(rv);
44 return (*l != *r) || cmp(l + 1, r + 1, s - 1);
45}
46
47template <int (*cmp)(const char *l, const char *r)>
48static inline int fastcmp(const char *l, const char *r) {
49 return (*l != *r) || cmp(l + 1, r + 1);
50}
51
52#endif
53
54#endif // _ANDROID_UTILS_FASTSTRCMP_H__