1/*
2 * Copyright (C) 2007 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.dx.dex.file;
18
19/**
20 * An item in a Dalvik file which is referenced by index.
21 */
22public abstract class IndexedItem extends Item {
23    /** {@code >= -1;} assigned index of the item, or {@code -1} if not
24     * yet assigned */
25    private int index;
26
27    /**
28     * Constructs an instance. The index is initially unassigned.
29     */
30    public IndexedItem() {
31        index = -1;
32    }
33
34    /**
35     * Gets whether or not this instance has been assigned an index.
36     *
37     * @return {@code true} iff this instance has been assigned an index
38     */
39    public final boolean hasIndex() {
40        return (index >= 0);
41    }
42
43    /**
44     * Gets the item index.
45     *
46     * @return {@code >= 0;} the index
47     * @throws RuntimeException thrown if the item index is not yet assigned
48     */
49    public final int getIndex() {
50        if (index < 0) {
51            throw new RuntimeException("index not yet set");
52        }
53
54        return index;
55    }
56
57    /**
58     * Sets the item index. This method may only ever be called once
59     * per instance, and this will throw a {@code RuntimeException} if
60     * called a second (or subsequent) time.
61     *
62     * @param index {@code >= 0;} the item index
63     */
64    public final void setIndex(int index) {
65        if (this.index != -1) {
66            throw new RuntimeException("index already set");
67        }
68
69        this.index = index;
70    }
71
72    /**
73     * Gets the index of this item as a string, suitable for including in
74     * annotations.
75     *
76     * @return {@code non-null;} the index string
77     */
78    public final String indexString() {
79        return '[' + Integer.toHexString(index) + ']';
80    }
81}
82