Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ByteUtil.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.Closeable;
  15. import java.io.DataInputStream;
  16. import java.io.FileWriter;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.io.PrintWriter;
  21. import java.nio.ByteBuffer;
  22. import java.nio.ByteOrder;
  23. import java.util.Arrays;
  24. /**
  25. * Byte manipulation and display utilities
  26. * @author Tim McCune
  27. */
  28. public final class ByteUtil {
  29. private static final String[] HEX_CHARS = new String[] {
  30. "0", "1", "2", "3", "4", "5", "6", "7",
  31. "8", "9", "A", "B", "C", "D", "E", "F"};
  32. private static final int NUM_BYTES_PER_BLOCK = 4;
  33. private static final int NUM_BYTES_PER_LINE = 24;
  34. private ByteUtil() {}
  35. /**
  36. * Put an integer into the given buffer at the given offset as a 3-byte
  37. * integer.
  38. * @param buffer buffer into which to insert the int
  39. * @param val Int to convert
  40. */
  41. public static void put3ByteInt(ByteBuffer buffer, int val)
  42. {
  43. put3ByteInt(buffer, val, buffer.order());
  44. }
  45. /**
  46. * Put an integer into the given buffer at the given offset as a 3-byte
  47. * integer.
  48. * @param buffer buffer into which to insert the int
  49. * @param val Int to convert
  50. * @param order the order to insert the bytes of the int
  51. */
  52. public static void put3ByteInt(ByteBuffer buffer, int val, ByteOrder order)
  53. {
  54. int pos = buffer.position();
  55. put3ByteInt(buffer, val, pos, order);
  56. buffer.position(pos + 3);
  57. }
  58. /**
  59. * Put an integer into the given buffer at the given offset as a 3-byte
  60. * integer.
  61. * @param buffer buffer into which to insert the int
  62. * @param val Int to convert
  63. * @param offset offset at which to insert the int
  64. * @param order the order to insert the bytes of the int
  65. */
  66. public static void put3ByteInt(ByteBuffer buffer, int val, int offset,
  67. ByteOrder order) {
  68. int offInc = 1;
  69. if(order == ByteOrder.BIG_ENDIAN) {
  70. offInc = -1;
  71. offset += 2;
  72. }
  73. buffer.put(offset, (byte) (val & 0xFF));
  74. buffer.put(offset + (1 * offInc), (byte) ((val >>> 8) & 0xFF));
  75. buffer.put(offset + (2 * offInc), (byte) ((val >>> 16) & 0xFF));
  76. }
  77. /**
  78. * Read a 3 byte int from a buffer
  79. * @param buffer Buffer containing the bytes
  80. * @return The int
  81. */
  82. public static int get3ByteInt(ByteBuffer buffer) {
  83. return get3ByteInt(buffer, buffer.order());
  84. }
  85. /**
  86. * Read a 3 byte int from a buffer
  87. * @param buffer Buffer containing the bytes
  88. * @param order the order of the bytes of the int
  89. * @return The int
  90. */
  91. public static int get3ByteInt(ByteBuffer buffer, ByteOrder order) {
  92. int pos = buffer.position();
  93. int rtn = get3ByteInt(buffer, pos, order);
  94. buffer.position(pos + 3);
  95. return rtn;
  96. }
  97. /**
  98. * Read a 3 byte int from a buffer
  99. * @param buffer Buffer containing the bytes
  100. * @param offset Offset at which to start reading the int
  101. * @return The int
  102. */
  103. public static int get3ByteInt(ByteBuffer buffer, int offset) {
  104. return get3ByteInt(buffer, offset, buffer.order());
  105. }
  106. /**
  107. * Read a 3 byte int from a buffer
  108. * @param buffer Buffer containing the bytes
  109. * @param offset Offset at which to start reading the int
  110. * @param order the order of the bytes of the int
  111. * @return The int
  112. */
  113. public static int get3ByteInt(ByteBuffer buffer, int offset,
  114. ByteOrder order) {
  115. int offInc = 1;
  116. if(order == ByteOrder.BIG_ENDIAN) {
  117. offInc = -1;
  118. offset += 2;
  119. }
  120. int rtn = getUnsignedByte(buffer, offset);
  121. rtn += (getUnsignedByte(buffer, offset + (1 * offInc)) << 8);
  122. rtn += (getUnsignedByte(buffer, offset + (2 * offInc)) << 16);
  123. return rtn;
  124. }
  125. /**
  126. * Read an unsigned byte from a buffer
  127. * @param buffer Buffer containing the bytes
  128. * @return The unsigned byte as an int
  129. */
  130. public static int getUnsignedByte(ByteBuffer buffer) {
  131. int pos = buffer.position();
  132. int rtn = getUnsignedByte(buffer, pos);
  133. buffer.position(pos + 1);
  134. return rtn;
  135. }
  136. /**
  137. * Read an unsigned byte from a buffer
  138. * @param buffer Buffer containing the bytes
  139. * @param offset Offset at which to read the byte
  140. * @return The unsigned byte as an int
  141. */
  142. public static int getUnsignedByte(ByteBuffer buffer, int offset) {
  143. return asUnsignedByte(buffer.get(offset));
  144. }
  145. /**
  146. * Read an unsigned short from a buffer
  147. * @param buffer Buffer containing the short
  148. * @return The unsigned short as an int
  149. */
  150. public static int getUnsignedShort(ByteBuffer buffer) {
  151. int pos = buffer.position();
  152. int rtn = getUnsignedShort(buffer, pos);
  153. buffer.position(pos + 2);
  154. return rtn;
  155. }
  156. /**
  157. * Read an unsigned short from a buffer
  158. * @param buffer Buffer containing the short
  159. * @param offset Offset at which to read the short
  160. * @return The unsigned short as an int
  161. */
  162. public static int getUnsignedShort(ByteBuffer buffer, int offset) {
  163. return asUnsignedShort(buffer.getShort(offset));
  164. }
  165. /**
  166. * @param buffer Buffer containing the bytes
  167. * @param order the order of the bytes of the int
  168. * @return an int from the current position in the given buffer, read using
  169. * the given ByteOrder
  170. */
  171. public static int getInt(ByteBuffer buffer, ByteOrder order) {
  172. int offset = buffer.position();
  173. int rtn = getInt(buffer, offset, order);
  174. buffer.position(offset + 4);
  175. return rtn;
  176. }
  177. /**
  178. * @param buffer Buffer containing the bytes
  179. * @param offset Offset at which to start reading the int
  180. * @param order the order of the bytes of the int
  181. * @return an int from the given position in the given buffer, read using
  182. * the given ByteOrder
  183. */
  184. public static int getInt(ByteBuffer buffer, int offset, ByteOrder order) {
  185. ByteOrder origOrder = buffer.order();
  186. try {
  187. return buffer.order(order).getInt(offset);
  188. } finally {
  189. buffer.order(origOrder);
  190. }
  191. }
  192. /**
  193. * Writes an int at the current position in the given buffer, using the
  194. * given ByteOrder
  195. * @param buffer buffer into which to insert the int
  196. * @param val Int to insert
  197. * @param order the order to insert the bytes of the int
  198. */
  199. public static void putInt(ByteBuffer buffer, int val, ByteOrder order) {
  200. int offset = buffer.position();
  201. putInt(buffer, val, offset, order);
  202. buffer.position(offset + 4);
  203. }
  204. /**
  205. * Writes an int at the given position in the given buffer, using the
  206. * given ByteOrder
  207. * @param buffer buffer into which to insert the int
  208. * @param val Int to insert
  209. * @param offset offset at which to insert the int
  210. * @param order the order to insert the bytes of the int
  211. */
  212. public static void putInt(ByteBuffer buffer, int val, int offset,
  213. ByteOrder order)
  214. {
  215. ByteOrder origOrder = buffer.order();
  216. try {
  217. buffer.order(order).putInt(offset, val);
  218. } finally {
  219. buffer.order(origOrder);
  220. }
  221. }
  222. /**
  223. * Read an unsigned variable length int from a buffer
  224. * @param buffer Buffer containing the variable length int
  225. * @return The unsigned int
  226. */
  227. public static int getUnsignedVarInt(ByteBuffer buffer, int numBytes) {
  228. int pos = buffer.position();
  229. int rtn = getUnsignedVarInt(buffer, pos, numBytes);
  230. buffer.position(pos + numBytes);
  231. return rtn;
  232. }
  233. /**
  234. * Read an unsigned variable length int from a buffer
  235. * @param buffer Buffer containing the variable length int
  236. * @param offset Offset at which to read the value
  237. * @return The unsigned int
  238. */
  239. public static int getUnsignedVarInt(ByteBuffer buffer, int offset,
  240. int numBytes) {
  241. switch(numBytes) {
  242. case 1:
  243. return getUnsignedByte(buffer, offset);
  244. case 2:
  245. return getUnsignedShort(buffer, offset);
  246. case 3:
  247. return get3ByteInt(buffer, offset);
  248. case 4:
  249. return buffer.getInt(offset);
  250. default:
  251. throw new IllegalArgumentException("Invalid num bytes " + numBytes);
  252. }
  253. }
  254. /**
  255. * Reads an array of bytes from the given buffer
  256. * @param buffer Buffer containing the desired bytes
  257. * @param len length of the desired bytes
  258. * @return a new buffer with the given number of bytes from the current
  259. * position in the given buffer
  260. */
  261. public static byte[] getBytes(ByteBuffer buffer, int len)
  262. {
  263. byte[] bytes = new byte[len];
  264. buffer.get(bytes);
  265. return bytes;
  266. }
  267. /**
  268. * Reads an array of bytes from the given buffer at the given offset
  269. * @param buffer Buffer containing the desired bytes
  270. * @param offset Offset at which to read the bytes
  271. * @param len length of the desired bytes
  272. * @return a new buffer with the given number of bytes from the given
  273. * position in the given buffer
  274. */
  275. public static byte[] getBytes(ByteBuffer buffer, int offset, int len)
  276. {
  277. int origPos = buffer.position();
  278. try {
  279. buffer.position(offset);
  280. return getBytes(buffer, len);
  281. } finally {
  282. buffer.position(origPos);
  283. }
  284. }
  285. /**
  286. * Concatenates and returns the given byte arrays.
  287. */
  288. public static byte[] concat(byte[] b1, byte[] b2) {
  289. byte[] out = new byte[b1.length + b2.length];
  290. System.arraycopy(b1, 0, out, 0, b1.length);
  291. System.arraycopy(b2, 0, out, b1.length, b2.length);
  292. return out;
  293. }
  294. /**
  295. * Sets all bits in the given remaining byte range to 0.
  296. */
  297. public static void clearRemaining(ByteBuffer buffer)
  298. {
  299. if(!buffer.hasRemaining()) {
  300. return;
  301. }
  302. int pos = buffer.position();
  303. clearRange(buffer, pos, pos + buffer.remaining());
  304. }
  305. /**
  306. * Sets all bits in the given byte range to 0.
  307. */
  308. public static void clearRange(ByteBuffer buffer, int start,
  309. int end)
  310. {
  311. putRange(buffer, start, end, (byte)0x00);
  312. }
  313. /**
  314. * Sets all bits in the given byte range to 1.
  315. */
  316. public static void fillRange(ByteBuffer buffer, int start,
  317. int end)
  318. {
  319. putRange(buffer, start, end, (byte)0xff);
  320. }
  321. /**
  322. * Sets all bytes in the given byte range to the given byte value.
  323. */
  324. public static void putRange(ByteBuffer buffer, int start,
  325. int end, byte b)
  326. {
  327. for(int i = start; i < end; ++i) {
  328. buffer.put(i, b);
  329. }
  330. }
  331. /**
  332. * Matches a pattern of bytes against the given buffer starting at the given
  333. * offset.
  334. */
  335. public static boolean matchesRange(ByteBuffer buffer, int start,
  336. byte[] pattern)
  337. {
  338. for(int i = 0; i < pattern.length; ++i) {
  339. if(pattern[i] != buffer.get(start + i)) {
  340. return false;
  341. }
  342. }
  343. return true;
  344. }
  345. /**
  346. * Searches for a pattern of bytes in the given buffer starting at the
  347. * given offset.
  348. * @return the offset of the pattern if a match is found, -1 otherwise
  349. */
  350. public static int findRange(ByteBuffer buffer, int start, byte[] pattern)
  351. {
  352. byte firstByte = pattern[0];
  353. int limit = buffer.limit() - pattern.length;
  354. for(int i = start; i < limit; ++i) {
  355. if((firstByte == buffer.get(i)) && matchesRange(buffer, i, pattern)) {
  356. return i;
  357. }
  358. }
  359. return -1;
  360. }
  361. /**
  362. * Inserts empty data of the given length at the current position of the
  363. * given buffer (moving existing data forward the given length). The limit
  364. * of the buffer is adjusted by the given length. The buffer is expecting
  365. * to have the required capacity available.
  366. */
  367. public static void insertEmptyData(ByteBuffer buffer, int len) {
  368. byte[] buf = buffer.array();
  369. int pos = buffer.position();
  370. int limit = buffer.limit();
  371. System.arraycopy(buf, pos, buf, pos + len, limit - pos);
  372. Arrays.fill(buf, pos, pos + len, (byte)0);
  373. buffer.limit(limit + len);
  374. }
  375. /**
  376. * Convert a byte buffer to a hexadecimal string for display
  377. * @param buffer Buffer to display, starting at offset 0
  378. * @param size Number of bytes to read from the buffer
  379. * @return The display String
  380. */
  381. public static String toHexString(ByteBuffer buffer, int size) {
  382. return toHexString(buffer, 0, size);
  383. }
  384. /**
  385. * Convert a byte array to a hexadecimal string for display
  386. * @param array byte array to display, starting at offset 0
  387. * @return The display String
  388. */
  389. public static String toHexString(byte[] array) {
  390. return toHexString(ByteBuffer.wrap(array), 0, array.length);
  391. }
  392. /**
  393. * Convert a byte buffer to a hexadecimal string for display
  394. * @param buffer Buffer to display, starting at offset 0
  395. * @param offset Offset at which to start reading the buffer
  396. * @param size Number of bytes to read from the buffer
  397. * @return The display String
  398. */
  399. public static String toHexString(ByteBuffer buffer, int offset, int size) {
  400. return toHexString(buffer, offset, size, true);
  401. }
  402. /**
  403. * Convert a byte buffer to a hexadecimal string for display
  404. * @param buffer Buffer to display, starting at offset 0
  405. * @param offset Offset at which to start reading the buffer
  406. * @param size Number of bytes to read from the buffer
  407. * @param formatted flag indicating if formatting is required
  408. * @return The display String
  409. */
  410. public static String toHexString(ByteBuffer buffer,
  411. int offset, int size, boolean formatted) {
  412. int bufLen = size * 2;
  413. if(formatted) {
  414. bufLen += size +
  415. (7 * ((size + NUM_BYTES_PER_LINE - 1) / NUM_BYTES_PER_LINE));
  416. }
  417. StringBuilder rtn = new StringBuilder(bufLen);
  418. int position = buffer.position();
  419. buffer.position(offset);
  420. size = Math.min(size, buffer.remaining());
  421. for (int i = 0; i < size; i++) {
  422. byte b = buffer.get();
  423. byte h = (byte) (b & 0xF0);
  424. h = (byte) (h >>> 4);
  425. h = (byte) (h & 0x0F);
  426. rtn.append(HEX_CHARS[h]);
  427. h = (byte) (b & 0x0F);
  428. rtn.append(HEX_CHARS[h]);
  429. int next = (i + 1);
  430. if(formatted && (next < size))
  431. {
  432. if((next % NUM_BYTES_PER_LINE) == 0) {
  433. rtn.append("\n");
  434. } else {
  435. rtn.append(" ");
  436. if ((next % NUM_BYTES_PER_BLOCK) == 0) {
  437. rtn.append(" ");
  438. }
  439. }
  440. }
  441. }
  442. buffer.position(position);
  443. return rtn.toString();
  444. }
  445. /**
  446. * Convert the given number of bytes from the given database page to a
  447. * hexidecimal string for display.
  448. */
  449. public static String toHexString(DatabaseImpl db, int pageNumber, int size)
  450. throws IOException
  451. {
  452. ByteBuffer buffer = db.getPageChannel().createPageBuffer();
  453. db.getPageChannel().readPage(buffer, pageNumber);
  454. return toHexString(buffer, size);
  455. }
  456. /**
  457. * Writes a sequence of hexidecimal values into the given buffer, where
  458. * every two characters represent one byte value.
  459. */
  460. public static void writeHexString(ByteBuffer buffer,
  461. String hexStr)
  462. throws IOException
  463. {
  464. char[] hexChars = hexStr.toCharArray();
  465. if((hexChars.length % 2) != 0) {
  466. throw new IOException("Hex string length must be even");
  467. }
  468. for(int i = 0; i < hexChars.length; i += 2) {
  469. String tmpStr = new String(hexChars, i, 2);
  470. buffer.put((byte)Integer.parseInt(tmpStr, 16));
  471. }
  472. }
  473. /**
  474. * Writes a chunk of data to a file in pretty printed hexidecimal.
  475. */
  476. public static void toHexFile(
  477. String fileName,
  478. ByteBuffer buffer,
  479. int offset, int size)
  480. throws IOException
  481. {
  482. PrintWriter writer = new PrintWriter(
  483. new FileWriter(fileName));
  484. try {
  485. writer.println(toHexString(buffer, offset, size));
  486. } finally {
  487. writer.close();
  488. }
  489. }
  490. /**
  491. * @return the byte value converted to an unsigned int value
  492. */
  493. public static int asUnsignedByte(byte b) {
  494. return b & 0xFF;
  495. }
  496. /**
  497. * @return the short value converted to an unsigned int value
  498. */
  499. public static int asUnsignedShort(short s) {
  500. return s & 0xFFFF;
  501. }
  502. /**
  503. * Swaps the 8 bytes (changes endianness) of the bytes at the given offset.
  504. *
  505. * @param bytes buffer containing bytes to swap
  506. * @param offset offset of the first byte of the bytes to swap
  507. */
  508. public static void swap8Bytes(byte[] bytes, int offset)
  509. {
  510. swapBytesAt(bytes, offset + 0, offset + 7);
  511. swapBytesAt(bytes, offset + 1, offset + 6);
  512. swapBytesAt(bytes, offset + 2, offset + 5);
  513. swapBytesAt(bytes, offset + 3, offset + 4);
  514. }
  515. /**
  516. * Swaps the 4 bytes (changes endianness) of the bytes at the given offset.
  517. *
  518. * @param bytes buffer containing bytes to swap
  519. * @param offset offset of the first byte of the bytes to swap
  520. */
  521. public static void swap4Bytes(byte[] bytes, int offset)
  522. {
  523. swapBytesAt(bytes, offset + 0, offset + 3);
  524. swapBytesAt(bytes, offset + 1, offset + 2);
  525. }
  526. /**
  527. * Swaps the 2 bytes (changes endianness) of the bytes at the given offset.
  528. *
  529. * @param bytes buffer containing bytes to swap
  530. * @param offset offset of the first byte of the bytes to swap
  531. */
  532. public static void swap2Bytes(byte[] bytes, int offset)
  533. {
  534. swapBytesAt(bytes, offset + 0, offset + 1);
  535. }
  536. /**
  537. * Swaps the bytes at the given positions.
  538. */
  539. private static void swapBytesAt(byte[] bytes, int p1, int p2)
  540. {
  541. byte b = bytes[p1];
  542. bytes[p1] = bytes[p2];
  543. bytes[p2] = b;
  544. }
  545. /**
  546. * Moves the position of the given buffer the given count from the current
  547. * position.
  548. * @return the new buffer position
  549. */
  550. public static int forward(ByteBuffer buffer, int count)
  551. {
  552. int newPos = buffer.position() + count;
  553. buffer.position(newPos);
  554. return newPos;
  555. }
  556. /**
  557. * Returns a copy of the given array of the given length.
  558. */
  559. public static byte[] copyOf(byte[] arr, int newLength)
  560. {
  561. return copyOf(arr, 0, newLength, 0);
  562. }
  563. /**
  564. * Returns a copy of the given array of the given length starting at the
  565. * given position.
  566. */
  567. public static byte[] copyOf(byte[] arr, int offset, int newLength)
  568. {
  569. return copyOf(arr, offset, newLength, 0);
  570. }
  571. /**
  572. * Returns a copy of the given array of the given length starting at the
  573. * given position.
  574. */
  575. public static byte[] copyOf(byte[] arr, int offset, int newLength,
  576. int dstOffset)
  577. {
  578. byte[] newArr = new byte[newLength];
  579. int srcLen = arr.length - offset;
  580. int dstLen = newLength - dstOffset;
  581. System.arraycopy(arr, offset, newArr, dstOffset, Math.min(srcLen, dstLen));
  582. return newArr;
  583. }
  584. /**
  585. * Copies the given InputStream to the given OutputStream.
  586. */
  587. public static void copy(InputStream in, OutputStream out) throws IOException {
  588. byte[] buf = new byte[8 * 1024];
  589. int read = 0;
  590. while((read = in.read(buf)) > -1) {
  591. out.write(buf, 0, read);
  592. }
  593. }
  594. /**
  595. * Closes the given Closeable if non-null, swallows any IOExceptions.
  596. */
  597. public static void closeQuietly(Closeable c) {
  598. if(c != null) {
  599. try {
  600. c.close();
  601. } catch(IOException ignored) {}
  602. }
  603. }
  604. /**
  605. * Skips the given number of bytes in the given stream
  606. */
  607. public static void skipFully(DataInputStream din, int len)
  608. throws IOException
  609. {
  610. do {
  611. int skipped = din.skipBytes(len);
  612. len -= skipped;
  613. } while(len > 0);
  614. }
  615. /**
  616. * Utility byte stream similar to ByteArrayOutputStream but with extended
  617. * accessibility to the bytes.
  618. */
  619. public static class ByteStream extends OutputStream
  620. {
  621. private byte[] _bytes;
  622. private int _length;
  623. private int _lastLength;
  624. public ByteStream() {
  625. this(32);
  626. }
  627. public ByteStream(int capacity) {
  628. _bytes = new byte[capacity];
  629. }
  630. public int getLength() {
  631. return _length;
  632. }
  633. public byte[] getBytes() {
  634. return _bytes;
  635. }
  636. protected void ensureNewCapacity(int numBytes) {
  637. ensureCapacity(_length + numBytes);
  638. }
  639. protected void ensureCapacity(int newLength) {
  640. if(newLength > _bytes.length) {
  641. byte[] temp = new byte[newLength * 2];
  642. System.arraycopy(_bytes, 0, temp, 0, _length);
  643. _bytes = temp;
  644. }
  645. }
  646. @Override
  647. public void write(int b) {
  648. ensureNewCapacity(1);
  649. _bytes[_length++] = (byte)b;
  650. }
  651. @Override
  652. public void write(byte[] b) {
  653. write(b, 0, b.length);
  654. }
  655. @Override
  656. public void write(byte[] b, int offset, int length) {
  657. ensureNewCapacity(length);
  658. System.arraycopy(b, offset, _bytes, _length, length);
  659. _length += length;
  660. }
  661. public byte get(int offset) {
  662. return _bytes[offset];
  663. }
  664. public void set(int offset, byte b) {
  665. _bytes[offset] = b;
  666. }
  667. public void setBits(int offset, byte b) {
  668. _bytes[offset] |= b;
  669. }
  670. public void writeFill(int length, byte b) {
  671. ensureNewCapacity(length);
  672. int oldLength = _length;
  673. _length += length;
  674. Arrays.fill(_bytes, oldLength, _length, b);
  675. }
  676. public void skip(int n) {
  677. ensureNewCapacity(n);
  678. _length += n;
  679. }
  680. public void writeTo(ByteStream out) {
  681. out.write(_bytes, 0, _length);
  682. }
  683. public byte[] toByteArray() {
  684. byte[] result = null;
  685. if(_length == _bytes.length) {
  686. result = _bytes;
  687. _bytes = null;
  688. } else {
  689. result = copyOf(_bytes, _length);
  690. if(_lastLength == _length) {
  691. // if we get the same result length bytes twice in a row, clear the
  692. // _bytes so that the next _bytes will be _lastLength
  693. _bytes = null;
  694. }
  695. }
  696. // save result length so we can potentially get the right length of the
  697. // next byte[] in reset()
  698. _lastLength = _length;
  699. return result;
  700. }
  701. public void reset() {
  702. _length = 0;
  703. if(_bytes == null) {
  704. _bytes = new byte[_lastLength];
  705. }
  706. }
  707. public void trimTrailing(byte minTrimCode, byte maxTrimCode)
  708. {
  709. int minTrim = ByteUtil.asUnsignedByte(minTrimCode);
  710. int maxTrim = ByteUtil.asUnsignedByte(maxTrimCode);
  711. int idx = _length - 1;
  712. while(idx >= 0) {
  713. int val = asUnsignedByte(get(idx));
  714. if((val >= minTrim) && (val <= maxTrim)) {
  715. --idx;
  716. } else {
  717. break;
  718. }
  719. }
  720. _length = idx + 1;
  721. }
  722. }
  723. }