You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ByteUtil.java 21KB

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