1/*
2 * Copyright (C) 2012 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
17package com.android.layoutlib.bridge.util;
18
19import com.android.resources.ResourceType;
20import com.android.util.Pair;
21
22import android.util.SparseArray;
23
24import java.util.HashMap;
25import java.util.Map;
26
27public class DynamicIdMap {
28
29    private final Map<Pair<ResourceType, String>, Integer> mDynamicIds = new HashMap<Pair<ResourceType, String>, Integer>();
30    private final SparseArray<Pair<ResourceType, String>> mRevDynamicIds = new SparseArray<Pair<ResourceType, String>>();
31    private int mDynamicSeed;
32
33    public DynamicIdMap(int seed) {
34        mDynamicSeed = seed;
35    }
36
37    public void reset(int seed) {
38        mDynamicIds.clear();
39        mRevDynamicIds.clear();
40        mDynamicSeed = seed;
41    }
42
43    /**
44     * Returns a dynamic integer for the given resource type/name, creating it if it doesn't
45     * already exist.
46     *
47     * @param type the type of the resource
48     * @param name the name of the resource
49     * @return an integer.
50     */
51    public Integer getId(ResourceType type, String name) {
52        return getId(Pair.of(type, name));
53    }
54
55    /**
56     * Returns a dynamic integer for the given resource type/name, creating it if it doesn't
57     * already exist.
58     *
59     * @param resource the type/name of the resource
60     * @return an integer.
61     */
62    public Integer getId(Pair<ResourceType, String> resource) {
63        Integer value = mDynamicIds.get(resource);
64        if (value == null) {
65            value = Integer.valueOf(++mDynamicSeed);
66            mDynamicIds.put(resource, value);
67            mRevDynamicIds.put(value, resource);
68        }
69
70        return value;
71    }
72
73    public Pair<ResourceType, String> resolveId(int id) {
74        return mRevDynamicIds.get(id);
75    }
76}
77