Leb128Utils.java revision 83b80f81d311b233188c281059aad4a9f5e8b4e6
1/*
2 * Copyright (C) 2008 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 org.jf.dexlib.Util;
18
19/**
20 * LEB128 (little-endian base 128) utilities.
21 */
22public final class Leb128Utils {
23    /**
24     * This class is uninstantiable.
25     */
26    private Leb128Utils() {
27        // This space intentionally left blank.
28    }
29
30    /**
31     * Gets the number of bytes in the unsigned LEB128 encoding of the
32     * given value.
33     *
34     * @param value the value in question
35     * @return its write size, in bytes
36     */
37    public static int unsignedLeb128Size(int value) {
38        // TODO: This could be much cleverer.
39
40        int remaining = value >> 7;
41        int count = 0;
42
43        while (remaining != 0) {
44            value = remaining;
45            remaining >>= 7;
46            count++;
47        }
48
49        return count + 1;
50    }
51
52    /**
53     * Gets the number of bytes in the signed LEB128 encoding of the
54     * given value.
55     *
56     * @param value the value in question
57     * @return its write size, in bytes
58     */
59    public static int signedLeb128Size(int value) {
60        // TODO: This could be much cleverer.
61
62        int remaining = value >> 7;
63        int count = 0;
64        boolean hasMore = true;
65        int end = ((value & Integer.MIN_VALUE) == 0) ? 0 : -1;
66
67        while (hasMore) {
68            hasMore = (remaining != end)
69                || ((remaining & 1) != ((value >> 6) & 1));
70
71            value = remaining;
72            remaining >>= 7;
73            count++;
74        }
75
76        return count;
77    }
78}
79