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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.FileWriter;
  24. import java.io.IOException;
  25. import java.io.PrintWriter;
  26. import java.nio.ByteBuffer;
  27. import java.nio.ByteOrder;
  28. import java.util.Arrays;
  29. /**
  30. * Byte manipulation and display utilities
  31. * @author Tim McCune
  32. */
  33. public final class ByteUtil {
  34. private static final String[] HEX_CHARS = new String[] {
  35. "0", "1", "2", "3", "4", "5", "6", "7",
  36. "8", "9", "A", "B", "C", "D", "E", "F"};
  37. private static final int NUM_BYTES_PER_BLOCK = 4;
  38. private static final int NUM_BYTES_PER_LINE = 24;
  39. private ByteUtil() {}
  40. /**
  41. * Put an integer into the given buffer at the given offset as a 3-byte
  42. * integer.
  43. * @param buffer buffer into which to insert the int
  44. * @param val Int to convert
  45. */
  46. public static void put3ByteInt(ByteBuffer buffer, int val)
  47. {
  48. put3ByteInt(buffer, val, buffer.order());
  49. }
  50. /**
  51. * Put an integer into the given buffer at the given offset as a 3-byte
  52. * integer.
  53. * @param buffer buffer into which to insert the int
  54. * @param val Int to convert
  55. * @param order the order to insert the bytes of the int
  56. */
  57. public static void put3ByteInt(ByteBuffer buffer, int val, ByteOrder order)
  58. {
  59. int pos = buffer.position();
  60. put3ByteInt(buffer, val, pos, order);
  61. buffer.position(pos + 3);
  62. }
  63. /**
  64. * Put an integer into the given buffer at the given offset as a 3-byte
  65. * integer.
  66. * @param buffer buffer into which to insert the int
  67. * @param val Int to convert
  68. * @param offset offset at which to insert the int
  69. * @param order the order to insert the bytes of the int
  70. */
  71. public static void put3ByteInt(ByteBuffer buffer, int val, int offset,
  72. ByteOrder order) {
  73. int offInc = 1;
  74. if(order == ByteOrder.BIG_ENDIAN) {
  75. offInc = -1;
  76. offset += 2;
  77. }
  78. buffer.put(offset, (byte) (val & 0xFF));
  79. buffer.put(offset + (1 * offInc), (byte) ((val >>> 8) & 0xFF));
  80. buffer.put(offset + (2 * offInc), (byte) ((val >>> 16) & 0xFF));
  81. }
  82. /**
  83. * Read a 3 byte int from a buffer
  84. * @param buffer Buffer containing the bytes
  85. * @return The int
  86. */
  87. public static int get3ByteInt(ByteBuffer buffer) {
  88. return get3ByteInt(buffer, buffer.order());
  89. }
  90. /**
  91. * Read a 3 byte int from a buffer
  92. * @param buffer Buffer containing the bytes
  93. * @param order the order of the bytes of the int
  94. * @return The int
  95. */
  96. public static int get3ByteInt(ByteBuffer buffer, ByteOrder order) {
  97. int pos = buffer.position();
  98. int rtn = get3ByteInt(buffer, pos, order);
  99. buffer.position(pos + 3);
  100. return rtn;
  101. }
  102. /**
  103. * Read a 3 byte int from a buffer
  104. * @param buffer Buffer containing the bytes
  105. * @param offset Offset at which to start reading the int
  106. * @return The int
  107. */
  108. public static int get3ByteInt(ByteBuffer buffer, int offset) {
  109. return get3ByteInt(buffer, offset, buffer.order());
  110. }
  111. /**
  112. * Read a 3 byte int from a buffer
  113. * @param buffer Buffer containing the bytes
  114. * @param offset Offset at which to start reading the int
  115. * @param order the order of the bytes of the int
  116. * @return The int
  117. */
  118. public static int get3ByteInt(ByteBuffer buffer, int offset,
  119. ByteOrder order) {
  120. int offInc = 1;
  121. if(order == ByteOrder.BIG_ENDIAN) {
  122. offInc = -1;
  123. offset += 2;
  124. }
  125. int rtn = getUnsignedByte(buffer, offset);
  126. rtn += (getUnsignedByte(buffer, offset + (1 * offInc)) << 8);
  127. rtn += (getUnsignedByte(buffer, offset + (2 * offInc)) << 16);
  128. return rtn;
  129. }
  130. /**
  131. * Read an unsigned byte from a buffer
  132. * @param buffer Buffer containing the bytes
  133. * @return The unsigned byte as an int
  134. */
  135. public static int getUnsignedByte(ByteBuffer buffer) {
  136. int pos = buffer.position();
  137. int rtn = getUnsignedByte(buffer, pos);
  138. buffer.position(pos + 1);
  139. return rtn;
  140. }
  141. /**
  142. * Read an unsigned byte from a buffer
  143. * @param buffer Buffer containing the bytes
  144. * @param offset Offset at which to read the byte
  145. * @return The unsigned byte as an int
  146. */
  147. public static int getUnsignedByte(ByteBuffer buffer, int offset) {
  148. return asUnsignedByte(buffer.get(offset));
  149. }
  150. /**
  151. * Read an unsigned short from a buffer
  152. * @param buffer Buffer containing the short
  153. * @return The unsigned short as an int
  154. */
  155. public static int getUnsignedShort(ByteBuffer buffer) {
  156. int pos = buffer.position();
  157. int rtn = getUnsignedShort(buffer, pos);
  158. buffer.position(pos + 2);
  159. return rtn;
  160. }
  161. /**
  162. * Read an unsigned short from a buffer
  163. * @param buffer Buffer containing the short
  164. * @param offset Offset at which to read the short
  165. * @return The unsigned short as an int
  166. */
  167. public static int getUnsignedShort(ByteBuffer buffer, int offset) {
  168. return asUnsignedShort(buffer.getShort(offset));
  169. }
  170. /**
  171. * @param buffer Buffer containing the bytes
  172. * @param order the order of the bytes of the int
  173. * @return an int from the current position in the given buffer, read using
  174. * the given ByteOrder
  175. */
  176. public static int getInt(ByteBuffer buffer, ByteOrder order) {
  177. int offset = buffer.position();
  178. int rtn = getInt(buffer, offset, order);
  179. buffer.position(offset + 4);
  180. return rtn;
  181. }
  182. /**
  183. * @param buffer Buffer containing the bytes
  184. * @param offset Offset at which to start reading the int
  185. * @param order the order of the bytes of the int
  186. * @return an int from the given position in the given buffer, read using
  187. * the given ByteOrder
  188. */
  189. public static int getInt(ByteBuffer buffer, int offset, ByteOrder order) {
  190. ByteOrder origOrder = buffer.order();
  191. try {
  192. return buffer.order(order).getInt(offset);
  193. } finally {
  194. buffer.order(origOrder);
  195. }
  196. }
  197. /**
  198. * Writes an int at the current position in the given buffer, using the
  199. * given ByteOrder
  200. * @param buffer buffer into which to insert the int
  201. * @param val Int to insert
  202. * @param order the order to insert the bytes of the int
  203. */
  204. public static void putInt(ByteBuffer buffer, int val, ByteOrder order) {
  205. int offset = buffer.position();
  206. putInt(buffer, val, offset, order);
  207. buffer.position(offset + 4);
  208. }
  209. /**
  210. * Writes an int at the given position in the given buffer, using the
  211. * given ByteOrder
  212. * @param buffer buffer into which to insert the int
  213. * @param val Int to insert
  214. * @param offset offset at which to insert the int
  215. * @param order the order to insert the bytes of the int
  216. */
  217. public static void putInt(ByteBuffer buffer, int val, int offset,
  218. ByteOrder order)
  219. {
  220. ByteOrder origOrder = buffer.order();
  221. try {
  222. buffer.order(order).putInt(offset, val);
  223. } finally {
  224. buffer.order(origOrder);
  225. }
  226. }
  227. /**
  228. * Read an unsigned variable length int from a buffer
  229. * @param buffer Buffer containing the variable length int
  230. * @return The unsigned int
  231. */
  232. public static int getUnsignedVarInt(ByteBuffer buffer, int numBytes) {
  233. int pos = buffer.position();
  234. int rtn = getUnsignedVarInt(buffer, pos, numBytes);
  235. buffer.position(pos + numBytes);
  236. return rtn;
  237. }
  238. /**
  239. * Read an unsigned variable length int from a buffer
  240. * @param buffer Buffer containing the variable length int
  241. * @param offset Offset at which to read the value
  242. * @return The unsigned int
  243. */
  244. public static int getUnsignedVarInt(ByteBuffer buffer, int offset,
  245. int numBytes) {
  246. switch(numBytes) {
  247. case 1:
  248. return getUnsignedByte(buffer, offset);
  249. case 2:
  250. return getUnsignedShort(buffer, offset);
  251. case 3:
  252. return get3ByteInt(buffer, offset);
  253. case 4:
  254. return buffer.getInt(offset);
  255. default:
  256. throw new IllegalArgumentException("Invalid num bytes " + numBytes);
  257. }
  258. }
  259. /**
  260. * Sets all bits in the given remaining byte range to 0.
  261. */
  262. public static void clearRemaining(ByteBuffer buffer)
  263. {
  264. if(!buffer.hasRemaining()) {
  265. return;
  266. }
  267. int pos = buffer.position();
  268. clearRange(buffer, pos, pos + buffer.remaining());
  269. }
  270. /**
  271. * Sets all bits in the given byte range to 0.
  272. */
  273. public static void clearRange(ByteBuffer buffer, int start,
  274. int end)
  275. {
  276. putRange(buffer, start, end, (byte)0x00);
  277. }
  278. /**
  279. * Sets all bits in the given byte range to 1.
  280. */
  281. public static void fillRange(ByteBuffer buffer, int start,
  282. int end)
  283. {
  284. putRange(buffer, start, end, (byte)0xff);
  285. }
  286. /**
  287. * Sets all bytes in the given byte range to the given byte value.
  288. */
  289. public static void putRange(ByteBuffer buffer, int start,
  290. int end, byte b)
  291. {
  292. for(int i = start; i < end; ++i) {
  293. buffer.put(i, b);
  294. }
  295. }
  296. /**
  297. * Matches a pattern of bytes against the given buffer starting at the given
  298. * offset.
  299. */
  300. public static boolean matchesRange(ByteBuffer buffer, int start,
  301. byte[] pattern)
  302. {
  303. for(int i = 0; i < pattern.length; ++i) {
  304. if(pattern[i] != buffer.get(start + i)) {
  305. return false;
  306. }
  307. }
  308. return true;
  309. }
  310. /**
  311. * Searches for a pattern of bytes in the given buffer starting at the
  312. * given offset.
  313. * @return the offset of the pattern if a match is found, -1 otherwise
  314. */
  315. public static int findRange(ByteBuffer buffer, int start, byte[] pattern)
  316. {
  317. byte firstByte = pattern[0];
  318. int limit = buffer.limit() - pattern.length;
  319. for(int i = start; i < limit; ++i) {
  320. if((firstByte == buffer.get(i)) && matchesRange(buffer, i, pattern)) {
  321. return i;
  322. }
  323. }
  324. return -1;
  325. }
  326. /**
  327. * Convert a byte buffer to a hexadecimal string for display
  328. * @param buffer Buffer to display, starting at offset 0
  329. * @param size Number of bytes to read from the buffer
  330. * @return The display String
  331. */
  332. public static String toHexString(ByteBuffer buffer, int size) {
  333. return toHexString(buffer, 0, size);
  334. }
  335. /**
  336. * Convert a byte array to a hexadecimal string for display
  337. * @param array byte array to display, starting at offset 0
  338. * @return The display String
  339. */
  340. public static String toHexString(byte[] array) {
  341. return toHexString(ByteBuffer.wrap(array), 0, array.length);
  342. }
  343. /**
  344. * Convert a byte buffer to a hexadecimal string for display
  345. * @param buffer Buffer to display, starting at offset 0
  346. * @param offset Offset at which to start reading the buffer
  347. * @param size Number of bytes to read from the buffer
  348. * @return The display String
  349. */
  350. public static String toHexString(ByteBuffer buffer, int offset, int size) {
  351. return toHexString(buffer, offset, size, true);
  352. }
  353. /**
  354. * Convert a byte buffer to a hexadecimal string for display
  355. * @param buffer Buffer to display, starting at offset 0
  356. * @param offset Offset at which to start reading the buffer
  357. * @param size Number of bytes to read from the buffer
  358. * @param formatted flag indicating if formatting is required
  359. * @return The display String
  360. */
  361. public static String toHexString(ByteBuffer buffer,
  362. int offset, int size, boolean formatted) {
  363. StringBuilder rtn = new StringBuilder();
  364. int position = buffer.position();
  365. buffer.position(offset);
  366. for (int i = 0; i < size; i++) {
  367. byte b = buffer.get();
  368. byte h = (byte) (b & 0xF0);
  369. h = (byte) (h >>> 4);
  370. h = (byte) (h & 0x0F);
  371. rtn.append(HEX_CHARS[h]);
  372. h = (byte) (b & 0x0F);
  373. rtn.append(HEX_CHARS[h]);
  374. int next = (i + 1);
  375. if(formatted && (next < size))
  376. {
  377. if((next % NUM_BYTES_PER_LINE) == 0) {
  378. rtn.append("\n");
  379. } else {
  380. rtn.append(" ");
  381. if ((next % NUM_BYTES_PER_BLOCK) == 0) {
  382. rtn.append(" ");
  383. }
  384. }
  385. }
  386. }
  387. buffer.position(position);
  388. return rtn.toString();
  389. }
  390. /**
  391. * Writes a sequence of hexidecimal values into the given buffer, where
  392. * every two characters represent one byte value.
  393. */
  394. public static void writeHexString(ByteBuffer buffer,
  395. String hexStr)
  396. throws IOException
  397. {
  398. char[] hexChars = hexStr.toCharArray();
  399. if((hexChars.length % 2) != 0) {
  400. throw new IOException("Hex string length must be even");
  401. }
  402. for(int i = 0; i < hexChars.length; i += 2) {
  403. String tmpStr = new String(hexChars, i, 2);
  404. buffer.put((byte)Long.parseLong(tmpStr, 16));
  405. }
  406. }
  407. /**
  408. * Writes a chunk of data to a file in pretty printed hexidecimal.
  409. */
  410. public static void toHexFile(
  411. String fileName,
  412. ByteBuffer buffer,
  413. int offset, int size)
  414. throws IOException
  415. {
  416. PrintWriter writer = new PrintWriter(
  417. new FileWriter(fileName));
  418. try {
  419. writer.println(toHexString(buffer, offset, size));
  420. } finally {
  421. writer.close();
  422. }
  423. }
  424. /**
  425. * @return the byte value converted to an unsigned int value
  426. */
  427. public static int asUnsignedByte(byte b) {
  428. return b & 0xFF;
  429. }
  430. /**
  431. * @return the short value converted to an unsigned int value
  432. */
  433. public static int asUnsignedShort(short s) {
  434. return s & 0xFFFF;
  435. }
  436. /**
  437. * Swaps the 4 bytes (changes endianness) of the bytes at the given offset.
  438. *
  439. * @param bytes buffer containing bytes to swap
  440. * @param offset offset of the first byte of the bytes to swap
  441. */
  442. public static void swap4Bytes(byte[] bytes, int offset)
  443. {
  444. byte b = bytes[offset + 0];
  445. bytes[offset + 0] = bytes[offset + 3];
  446. bytes[offset + 3] = b;
  447. b = bytes[offset + 1];
  448. bytes[offset + 1] = bytes[offset + 2];
  449. bytes[offset + 2] = b;
  450. }
  451. /**
  452. * Swaps the 2 bytes (changes endianness) of the bytes at the given offset.
  453. *
  454. * @param bytes buffer containing bytes to swap
  455. * @param offset offset of the first byte of the bytes to swap
  456. */
  457. public static void swap2Bytes(byte[] bytes, int offset)
  458. {
  459. byte b = bytes[offset + 0];
  460. bytes[offset + 0] = bytes[offset + 1];
  461. bytes[offset + 1] = b;
  462. }
  463. /**
  464. * Moves the position of the given buffer the given count from the current
  465. * position.
  466. * @return the new buffer position
  467. */
  468. public static int forward(ByteBuffer buffer, int count)
  469. {
  470. int newPos = buffer.position() + count;
  471. buffer.position(newPos);
  472. return newPos;
  473. }
  474. /**
  475. * Utility byte stream similar to ByteArrayOutputStream but with extended
  476. * accessibility to the bytes.
  477. */
  478. public static class ByteStream
  479. {
  480. private byte[] _bytes;
  481. private int _length;
  482. private int _lastLength;
  483. public ByteStream() {
  484. this(32);
  485. }
  486. public ByteStream(int capacity) {
  487. _bytes = new byte[capacity];
  488. }
  489. public int getLength() {
  490. return _length;
  491. }
  492. public byte[] getBytes() {
  493. return _bytes;
  494. }
  495. protected void ensureNewCapacity(int numBytes) {
  496. int newLength = _length + numBytes;
  497. if(newLength > _bytes.length) {
  498. byte[] temp = new byte[newLength * 2];
  499. System.arraycopy(_bytes, 0, temp, 0, _length);
  500. _bytes = temp;
  501. }
  502. }
  503. public void write(int b) {
  504. ensureNewCapacity(1);
  505. _bytes[_length++] = (byte)b;
  506. }
  507. public void write(byte[] b) {
  508. write(b, 0, b.length);
  509. }
  510. public void write(byte[] b, int offset, int length) {
  511. ensureNewCapacity(length);
  512. System.arraycopy(b, offset, _bytes, _length, length);
  513. _length += length;
  514. }
  515. public byte get(int offset) {
  516. return _bytes[offset];
  517. }
  518. public void set(int offset, byte b) {
  519. _bytes[offset] = b;
  520. }
  521. public void writeFill(int length, byte b) {
  522. ensureNewCapacity(length);
  523. int oldLength = _length;
  524. _length += length;
  525. Arrays.fill(_bytes, oldLength, _length, b);
  526. }
  527. public void writeTo(ByteStream out) {
  528. out.write(_bytes, 0, _length);
  529. }
  530. public byte[] toByteArray() {
  531. byte[] result = null;
  532. if(_length == _bytes.length) {
  533. result = _bytes;
  534. _bytes = null;
  535. } else {
  536. result = new byte[_length];
  537. System.arraycopy(_bytes, 0, result, 0, _length);
  538. if(_lastLength == _length) {
  539. // if we get the same result length bytes twice in a row, clear the
  540. // _bytes so that the next _bytes will be _lastLength
  541. _bytes = null;
  542. }
  543. }
  544. // save result length so we can potentially get the right length of the
  545. // next byte[] in reset()
  546. _lastLength = _length;
  547. return result;
  548. }
  549. public void reset() {
  550. _length = 0;
  551. if(_bytes == null) {
  552. _bytes = new byte[_lastLength];
  553. }
  554. }
  555. public void trimTrailing(byte minTrimCode, byte maxTrimCode)
  556. {
  557. int minTrim = ByteUtil.asUnsignedByte(minTrimCode);
  558. int maxTrim = ByteUtil.asUnsignedByte(maxTrimCode);
  559. int idx = _length - 1;
  560. while(idx >= 0) {
  561. int val = asUnsignedByte(get(idx));
  562. if((val >= minTrim) && (val <= maxTrim)) {
  563. --idx;
  564. } else {
  565. break;
  566. }
  567. }
  568. _length = idx + 1;
  569. }
  570. }
  571. }