Carl Shapiro | 1fb8620 | 2011-06-27 17:43:13 -0700 | [diff] [blame] | 1 | // Copyright 2011 Google Inc. All Rights Reserved. |
| 2 | |
| 3 | #ifndef ART_SRC_LEB128_H_ |
| 4 | #define ART_SRC_LEB128_H_ |
| 5 | |
| 6 | #include "src/globals.h" |
| 7 | |
| 8 | namespace art { |
| 9 | |
| 10 | // Reads an unsigned LEB128 value, updating the given pointer to point |
| 11 | // just past the end of the read value. This function tolerates |
| 12 | // non-zero high-order bits in the fifth encoded byte. |
| 13 | static inline uint32_t DecodeUnsignedLeb128(const byte** data) { |
| 14 | const byte* ptr = *data; |
| 15 | int result = *(ptr++); |
| 16 | if (result > 0x7f) { |
| 17 | int cur = *(ptr++); |
| 18 | result = (result & 0x7f) | ((cur & 0x7f) << 7); |
| 19 | if (cur > 0x7f) { |
| 20 | cur = *(ptr++); |
| 21 | result |= (cur & 0x7f) << 14; |
| 22 | if (cur > 0x7f) { |
| 23 | cur = *(ptr++); |
| 24 | result |= (cur & 0x7f) << 21; |
| 25 | if (cur > 0x7f) { |
| 26 | // Note: We don't check to see if cur is out of range here, |
| 27 | // meaning we tolerate garbage in the four high-order bits. |
| 28 | cur = *(ptr++); |
| 29 | result |= cur << 28; |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | *data = ptr; |
| 35 | return (uint32_t)result; |
| 36 | } |
| 37 | |
| 38 | // Reads a signed LEB128 value, updating the given pointer to point |
| 39 | // just past the end of the read value. This function tolerates |
| 40 | // non-zero high-order bits in the fifth encoded byte. |
| 41 | static inline int32_t DecodeSignedLeb128(const byte** data) { |
| 42 | const byte* ptr = *data; |
| 43 | int32_t result = *(ptr++); |
| 44 | if (result <= 0x7f) { |
| 45 | result = (result << 25) >> 25; |
| 46 | } else { |
| 47 | int cur = *(ptr++); |
| 48 | result = (result & 0x7f) | ((cur & 0x7f) << 7); |
| 49 | if (cur <= 0x7f) { |
| 50 | result = (result << 18) >> 18; |
| 51 | } else { |
| 52 | cur = *(ptr++); |
| 53 | result |= (cur & 0x7f) << 14; |
| 54 | if (cur <= 0x7f) { |
| 55 | result = (result << 11) >> 11; |
| 56 | } else { |
| 57 | cur = *(ptr++); |
| 58 | result |= (cur & 0x7f) << 21; |
| 59 | if (cur <= 0x7f) { |
| 60 | result = (result << 4) >> 4; |
| 61 | } else { |
| 62 | // Note: We don't check to see if cur is out of range here, |
| 63 | // meaning we tolerate garbage in the four high-order bits. |
| 64 | cur = *(ptr++); |
| 65 | result |= cur << 28; |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | *data = ptr; |
| 71 | return result; |
| 72 | } |
| 73 | |
| 74 | } // namespace art |
| 75 | |
| 76 | #endif // ART_SRC_LEB128_H_ |