Home | History | Annotate | Download | only in util
      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 
     17 package com.android.dexgen.util;
     18 
     19 /**
     20  * LEB128 (little-endian base 128) utilities.
     21  */
     22 public 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             remaining >>= 7;
     45             count++;
     46         }
     47 
     48         return count + 1;
     49     }
     50 
     51     /**
     52      * Gets the number of bytes in the signed LEB128 encoding of the
     53      * given value.
     54      *
     55      * @param value the value in question
     56      * @return its write size, in bytes
     57      */
     58     public static int signedLeb128Size(int value) {
     59         // TODO: This could be much cleverer.
     60 
     61         int remaining = value >> 7;
     62         int count = 0;
     63         boolean hasMore = true;
     64         int end = ((value & Integer.MIN_VALUE) == 0) ? 0 : -1;
     65 
     66         while (hasMore) {
     67             hasMore = (remaining != end)
     68                 || ((remaining & 1) != ((value >> 6) & 1));
     69 
     70             value = remaining;
     71             remaining >>= 7;
     72             count++;
     73         }
     74 
     75         return count;
     76     }
     77 }
     78