1/*
2 * Copyright (C) 2010 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#include <sys/types.h>
18
19#include "AAtomizer.h"
20
21namespace android {
22
23// static
24AAtomizer AAtomizer::gAtomizer;
25
26// static
27const char *AAtomizer::Atomize(const char *name) {
28    return gAtomizer.atomize(name);
29}
30
31AAtomizer::AAtomizer() {
32    for (size_t i = 0; i < 128; ++i) {
33        mAtoms.push(List<AString>());
34    }
35}
36
37const char *AAtomizer::atomize(const char *name) {
38    Mutex::Autolock autoLock(mLock);
39
40    const size_t n = mAtoms.size();
41    size_t index = AAtomizer::Hash(name) % n;
42    List<AString> &entry = mAtoms.editItemAt(index);
43    List<AString>::iterator it = entry.begin();
44    while (it != entry.end()) {
45        if ((*it) == name) {
46            return (*it).c_str();
47        }
48        ++it;
49    }
50
51    entry.push_back(AString(name));
52
53    return (*--entry.end()).c_str();
54}
55
56// static
57uint32_t AAtomizer::Hash(const char *s) {
58    uint32_t sum = 0;
59    while (*s != '\0') {
60        sum = (sum * 31) + *s;
61        ++s;
62    }
63
64    return sum;
65}
66
67}  // namespace android
68