| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.android.internal.util; |
| 18 |
|
| 19 |
import android.compat.annotation.UnsupportedAppUsage; |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public class BitwiseOutputStream { |
| 30 |
|
| 31 |
|
| 32 |
private byte[] mBuf; |
| 33 |
|
| 34 |
|
| 35 |
private int mPos; |
| 36 |
|
| 37 |
|
| 38 |
private int mEnd; |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
public static class AccessException extends Exception { |
| 44 |
public AccessException(String s) { |
| 45 |
super("BitwiseOutputStream access failed: " + s); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
@UnsupportedAppUsage |
| 55 |
public BitwiseOutputStream(int startingLength) { |
| 56 |
mBuf = new byte[startingLength]; |
| 57 |
mEnd = startingLength << 3; |
| 58 |
mPos = 0; |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
@UnsupportedAppUsage |
| 67 |
public byte[] toByteArray() { |
| 68 |
int len = (mPos >>> 3) + ((mPos & 0x07) > 0 ? 1 : 0); |
| 69 |
byte[] newBuf = new byte[len]; |
| 70 |
System.arraycopy(mBuf, 0, newBuf, 0, len); |
| 71 |
return newBuf; |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
private void possExpand(int bits) { |
| 80 |
if ((mPos + bits) < mEnd) return; |
| 81 |
byte[] newBuf = new byte[(mPos + bits) >>> 2]; |
| 82 |
System.arraycopy(mBuf, 0, newBuf, 0, mEnd >>> 3); |
| 83 |
mBuf = newBuf; |
| 84 |
mEnd = newBuf.length << 3; |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
@UnsupportedAppUsage |
| 97 |
public void write(int bits, int data) throws AccessException { |
| 98 |
if ((bits < 0) || (bits > 8)) { |
| 99 |
throw new AccessException("illegal write (" + bits + " bits)"); |
| 100 |
} |
| 101 |
possExpand(bits); |
| 102 |
data &= (-1 >>> (32 - bits)); |
| 103 |
int index = mPos >>> 3; |
| 104 |
int offset = 16 - (mPos & 0x07) - bits; |
| 105 |
data <<= offset; |
| 106 |
mPos += bits; |
| 107 |
mBuf[index] |= data >>> 8; |
| 108 |
if (offset < 8) mBuf[index + 1] |= data & 0xFF; |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
@UnsupportedAppUsage |
| 118 |
public void writeByteArray(int bits, byte[] arr) throws AccessException { |
| 119 |
for (int i = 0; i < arr.length; i++) { |
| 120 |
int increment = Math.min(8, bits - (i << 3)); |
| 121 |
if (increment > 0) { |
| 122 |
write(increment, (byte)(arr[i] >>> (8 - increment))); |
| 123 |
} |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
public void skip(int bits) { |
| 133 |
possExpand(bits); |
| 134 |
mPos += bits; |
| 135 |
} |
| 136 |
} |