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.

GeneralLegacyIndexCodes.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. /*
  2. Copyright (c) 2008 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.BufferedReader;
  15. import java.io.IOException;
  16. import java.io.InputStreamReader;
  17. import java.util.Arrays;
  18. import java.util.HashMap;
  19. import java.util.Map;
  20. import static com.healthmarketscience.jackcess.impl.ByteUtil.ByteStream;
  21. /**
  22. * Various constants used for creating "general legacy" (access 2000-2007)
  23. * sort order text index entries.
  24. *
  25. * @author James Ahlborn
  26. */
  27. public class GeneralLegacyIndexCodes {
  28. static final int MAX_TEXT_INDEX_CHAR_LENGTH =
  29. (JetFormat.TEXT_FIELD_MAX_LENGTH / JetFormat.TEXT_FIELD_UNIT_SIZE);
  30. static final byte END_TEXT = (byte)0x01;
  31. static final byte END_EXTRA_TEXT = (byte)0x00;
  32. // unprintable char is removed from normal text.
  33. // pattern for unprintable chars in the extra bytes:
  34. // 01 01 01 <pos> 06 <code> )
  35. // <pos> = 7 + (4 * char_pos) | 0x8000 (as short)
  36. // <code> = char code
  37. static final int UNPRINTABLE_COUNT_START = 7;
  38. static final int UNPRINTABLE_COUNT_MULTIPLIER = 4;
  39. static final int UNPRINTABLE_OFFSET_FLAGS = 0x8000;
  40. static final byte UNPRINTABLE_MIDFIX = (byte)0x06;
  41. // international char is replaced with ascii char.
  42. // pattern for international chars in the extra bytes:
  43. // [ 02 (for each normal char) ] [ <symbol_code> (for each inat char) ]
  44. static final byte INTERNATIONAL_EXTRA_PLACEHOLDER = (byte)0x02;
  45. // see Index.writeCrazyCodes for details on writing crazy codes
  46. static final byte CRAZY_CODE_START = (byte)0x80;
  47. static final byte CRAZY_CODE_1 = (byte)0x02;
  48. static final byte CRAZY_CODE_2 = (byte)0x03;
  49. static final byte[] CRAZY_CODES_SUFFIX =
  50. new byte[]{(byte)0xFF, (byte)0x02, (byte)0x80, (byte)0xFF, (byte)0x80};
  51. static final byte CRAZY_CODES_UNPRINT_SUFFIX = (byte)0xFF;
  52. // stash the codes in some resource files
  53. private static final String CODES_FILE =
  54. DatabaseImpl.RESOURCE_PATH + "index_codes_genleg.txt";
  55. private static final String EXT_CODES_FILE =
  56. DatabaseImpl.RESOURCE_PATH + "index_codes_ext_genleg.txt";
  57. /**
  58. * Enum which classifies the types of char encoding strategies used when
  59. * creating text index entries.
  60. */
  61. enum Type {
  62. SIMPLE("S") {
  63. @Override public CharHandler parseCodes(String[] codeStrings) {
  64. return parseSimpleCodes(codeStrings);
  65. }
  66. },
  67. INTERNATIONAL("I") {
  68. @Override public CharHandler parseCodes(String[] codeStrings) {
  69. return parseInternationalCodes(codeStrings);
  70. }
  71. },
  72. UNPRINTABLE("U") {
  73. @Override public CharHandler parseCodes(String[] codeStrings) {
  74. return parseUnprintableCodes(codeStrings);
  75. }
  76. },
  77. UNPRINTABLE_EXT("P") {
  78. @Override public CharHandler parseCodes(String[] codeStrings) {
  79. return parseUnprintableExtCodes(codeStrings);
  80. }
  81. },
  82. INTERNATIONAL_EXT("Z") {
  83. @Override public CharHandler parseCodes(String[] codeStrings) {
  84. return parseInternationalExtCodes(codeStrings);
  85. }
  86. },
  87. IGNORED("X") {
  88. @Override public CharHandler parseCodes(String[] codeStrings) {
  89. return IGNORED_CHAR_HANDLER;
  90. }
  91. };
  92. private final String _prefixCode;
  93. private Type(String prefixCode) {
  94. _prefixCode = prefixCode;
  95. }
  96. public String getPrefixCode() {
  97. return _prefixCode;
  98. }
  99. public abstract CharHandler parseCodes(String[] codeStrings);
  100. }
  101. /**
  102. * Base class for the handlers which hold the text index character encoding
  103. * information.
  104. */
  105. abstract static class CharHandler {
  106. public abstract Type getType();
  107. public byte[] getInlineBytes() {
  108. return null;
  109. }
  110. public byte[] getExtraBytes() {
  111. return null;
  112. }
  113. public byte[] getUnprintableBytes() {
  114. return null;
  115. }
  116. public byte getExtraByteModifier() {
  117. return 0;
  118. }
  119. public byte getCrazyFlag() {
  120. return 0;
  121. }
  122. }
  123. /**
  124. * CharHandler for Type.SIMPLE
  125. */
  126. private static final class SimpleCharHandler extends CharHandler {
  127. private byte[] _bytes;
  128. private SimpleCharHandler(byte[] bytes) {
  129. _bytes = bytes;
  130. }
  131. @Override public Type getType() {
  132. return Type.SIMPLE;
  133. }
  134. @Override public byte[] getInlineBytes() {
  135. return _bytes;
  136. }
  137. }
  138. /**
  139. * CharHandler for Type.INTERNATIONAL
  140. */
  141. private static final class InternationalCharHandler extends CharHandler {
  142. private byte[] _bytes;
  143. private byte[] _extraBytes;
  144. private InternationalCharHandler(byte[] bytes, byte[] extraBytes) {
  145. _bytes = bytes;
  146. _extraBytes = extraBytes;
  147. }
  148. @Override public Type getType() {
  149. return Type.INTERNATIONAL;
  150. }
  151. @Override public byte[] getInlineBytes() {
  152. return _bytes;
  153. }
  154. @Override public byte[] getExtraBytes() {
  155. return _extraBytes;
  156. }
  157. }
  158. /**
  159. * CharHandler for Type.UNPRINTABLE
  160. */
  161. private static final class UnprintableCharHandler extends CharHandler {
  162. private byte[] _unprintBytes;
  163. private UnprintableCharHandler(byte[] unprintBytes) {
  164. _unprintBytes = unprintBytes;
  165. }
  166. @Override public Type getType() {
  167. return Type.UNPRINTABLE;
  168. }
  169. @Override public byte[] getUnprintableBytes() {
  170. return _unprintBytes;
  171. }
  172. }
  173. /**
  174. * CharHandler for Type.UNPRINTABLE_EXT
  175. */
  176. private static final class UnprintableExtCharHandler extends CharHandler {
  177. private byte _extraByteMod;
  178. private UnprintableExtCharHandler(Byte extraByteMod) {
  179. _extraByteMod = extraByteMod;
  180. }
  181. @Override public Type getType() {
  182. return Type.UNPRINTABLE_EXT;
  183. }
  184. @Override public byte getExtraByteModifier() {
  185. return _extraByteMod;
  186. }
  187. }
  188. /**
  189. * CharHandler for Type.INTERNATIONAL_EXT
  190. */
  191. private static final class InternationalExtCharHandler extends CharHandler {
  192. private byte[] _bytes;
  193. private byte[] _extraBytes;
  194. private byte _crazyFlag;
  195. private InternationalExtCharHandler(byte[] bytes, byte[] extraBytes,
  196. byte crazyFlag) {
  197. _bytes = bytes;
  198. _extraBytes = extraBytes;
  199. _crazyFlag = crazyFlag;
  200. }
  201. @Override public Type getType() {
  202. return Type.INTERNATIONAL_EXT;
  203. }
  204. @Override public byte[] getInlineBytes() {
  205. return _bytes;
  206. }
  207. @Override public byte[] getExtraBytes() {
  208. return _extraBytes;
  209. }
  210. @Override public byte getCrazyFlag() {
  211. return _crazyFlag;
  212. }
  213. }
  214. /** shared CharHandler instance for Type.IGNORED */
  215. static final CharHandler IGNORED_CHAR_HANDLER = new CharHandler() {
  216. @Override public Type getType() {
  217. return Type.IGNORED;
  218. }
  219. };
  220. /** alternate shared CharHandler instance for "surrogate" chars (which we do
  221. not handle) */
  222. static final CharHandler SURROGATE_CHAR_HANDLER = new CharHandler() {
  223. @Override public Type getType() {
  224. return Type.IGNORED;
  225. }
  226. @Override public byte[] getInlineBytes() {
  227. throw new IllegalStateException(
  228. "Surrogate pair chars are not handled");
  229. }
  230. };
  231. static final char FIRST_CHAR = (char)0x0000;
  232. static final char LAST_CHAR = (char)0x00FF;
  233. static final char FIRST_EXT_CHAR = LAST_CHAR + 1;
  234. static final char LAST_EXT_CHAR = (char)0xFFFF;
  235. private static final class Codes
  236. {
  237. /** handlers for the first 256 chars. use nested class to lazy load the
  238. handlers */
  239. private static final CharHandler[] _values = loadCodes(
  240. CODES_FILE, FIRST_CHAR, LAST_CHAR);
  241. }
  242. private static final class ExtCodes
  243. {
  244. /** handlers for the rest of the chars in BMP 0. use nested class to
  245. lazy load the handlers */
  246. private static final CharHandler[] _values = loadCodes(
  247. EXT_CODES_FILE, FIRST_EXT_CHAR, LAST_EXT_CHAR);
  248. }
  249. static final GeneralLegacyIndexCodes GEN_LEG_INSTANCE =
  250. new GeneralLegacyIndexCodes();
  251. GeneralLegacyIndexCodes() {
  252. }
  253. /**
  254. * Returns the CharHandler for the given character.
  255. */
  256. CharHandler getCharHandler(char c)
  257. {
  258. if(c <= LAST_CHAR) {
  259. return Codes._values[c];
  260. }
  261. int extOffset = asUnsignedChar(c) - asUnsignedChar(FIRST_EXT_CHAR);
  262. return ExtCodes._values[extOffset];
  263. }
  264. /**
  265. * Loads the CharHandlers for the given range of characters from the
  266. * resource file with the given name.
  267. */
  268. static CharHandler[] loadCodes(String codesFilePath,
  269. char firstChar, char lastChar)
  270. {
  271. int numCodes = (asUnsignedChar(lastChar) - asUnsignedChar(firstChar)) + 1;
  272. CharHandler[] values = new CharHandler[numCodes];
  273. Map<String,Type> prefixMap = new HashMap<String,Type>();
  274. for(Type type : Type.values()) {
  275. prefixMap.put(type.getPrefixCode(), type);
  276. }
  277. BufferedReader reader = null;
  278. try {
  279. reader = new BufferedReader(
  280. new InputStreamReader(
  281. DatabaseImpl.getResourceAsStream(codesFilePath), "US-ASCII"));
  282. int start = asUnsignedChar(firstChar);
  283. int end = asUnsignedChar(lastChar);
  284. for(int i = start; i <= end; ++i) {
  285. char c = (char)i;
  286. CharHandler ch = null;
  287. if(Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) {
  288. // surrogate chars are not included in the codes files
  289. ch = SURROGATE_CHAR_HANDLER;
  290. } else {
  291. String codeLine = reader.readLine();
  292. ch = parseCodes(prefixMap, codeLine);
  293. }
  294. values[(i - start)] = ch;
  295. }
  296. } catch(IOException e) {
  297. throw new RuntimeException("failed loading index codes file " +
  298. codesFilePath, e);
  299. } finally {
  300. ByteUtil.closeQuietly(reader);
  301. }
  302. return values;
  303. }
  304. /**
  305. * Returns a CharHandler parsed from the given line from an index codes
  306. * file.
  307. */
  308. private static CharHandler parseCodes(Map<String,Type> prefixMap,
  309. String codeLine)
  310. {
  311. String prefix = codeLine.substring(0, 1);
  312. String suffix = ((codeLine.length() > 1) ? codeLine.substring(1) : "");
  313. return prefixMap.get(prefix).parseCodes(suffix.split(",", -1));
  314. }
  315. /**
  316. * Returns a SimpleCharHandler parsed from the given index code strings.
  317. */
  318. private static CharHandler parseSimpleCodes(String[] codeStrings)
  319. {
  320. if(codeStrings.length != 1) {
  321. throw new IllegalStateException("Unexpected code strings " +
  322. Arrays.asList(codeStrings));
  323. }
  324. return new SimpleCharHandler(codesToBytes(codeStrings[0], true));
  325. }
  326. /**
  327. * Returns an InternationalCharHandler parsed from the given index code
  328. * strings.
  329. */
  330. private static CharHandler parseInternationalCodes(String[] codeStrings)
  331. {
  332. if(codeStrings.length != 2) {
  333. throw new IllegalStateException("Unexpected code strings " +
  334. Arrays.asList(codeStrings));
  335. }
  336. return new InternationalCharHandler(codesToBytes(codeStrings[0], true),
  337. codesToBytes(codeStrings[1], true));
  338. }
  339. /**
  340. * Returns a UnprintableCharHandler parsed from the given index code
  341. * strings.
  342. */
  343. private static CharHandler parseUnprintableCodes(String[] codeStrings)
  344. {
  345. if(codeStrings.length != 1) {
  346. throw new IllegalStateException("Unexpected code strings " +
  347. Arrays.asList(codeStrings));
  348. }
  349. return new UnprintableCharHandler(codesToBytes(codeStrings[0], true));
  350. }
  351. /**
  352. * Returns a UnprintableExtCharHandler parsed from the given index code
  353. * strings.
  354. */
  355. private static CharHandler parseUnprintableExtCodes(String[] codeStrings)
  356. {
  357. if(codeStrings.length != 1) {
  358. throw new IllegalStateException("Unexpected code strings " +
  359. Arrays.asList(codeStrings));
  360. }
  361. byte[] bytes = codesToBytes(codeStrings[0], true);
  362. if(bytes.length != 1) {
  363. throw new IllegalStateException("Unexpected code strings " +
  364. Arrays.asList(codeStrings));
  365. }
  366. return new UnprintableExtCharHandler(bytes[0]);
  367. }
  368. /**
  369. * Returns a InternationalExtCharHandler parsed from the given index code
  370. * strings.
  371. */
  372. private static CharHandler parseInternationalExtCodes(String[] codeStrings)
  373. {
  374. if(codeStrings.length != 3) {
  375. throw new IllegalStateException("Unexpected code strings " +
  376. Arrays.asList(codeStrings));
  377. }
  378. byte crazyFlag = ("1".equals(codeStrings[2]) ?
  379. CRAZY_CODE_1 : CRAZY_CODE_2);
  380. return new InternationalExtCharHandler(codesToBytes(codeStrings[0], true),
  381. codesToBytes(codeStrings[1], false),
  382. crazyFlag);
  383. }
  384. /**
  385. * Converts a string of hex encoded bytes to a byte[], optionally throwing
  386. * an exception if no codes are given.
  387. */
  388. private static byte[] codesToBytes(String codes, boolean required)
  389. {
  390. if(codes.length() == 0) {
  391. if(required) {
  392. throw new IllegalStateException("empty code bytes");
  393. }
  394. return null;
  395. }
  396. if((codes.length() % 2) != 0) {
  397. // stripped a leading 0
  398. codes = "0" + codes;
  399. }
  400. byte[] bytes = new byte[codes.length() / 2];
  401. for(int i = 0; i < bytes.length; ++i) {
  402. int charIdx = i*2;
  403. bytes[i] = (byte)(Integer.parseInt(codes.substring(charIdx, charIdx + 2),
  404. 16));
  405. }
  406. return bytes;
  407. }
  408. /**
  409. * Returns an the char value converted to an unsigned char value. Note, I
  410. * think this is unnecessary (I think java treats chars as unsigned), but I
  411. * did this just to be on the safe side.
  412. */
  413. static int asUnsignedChar(char c)
  414. {
  415. return c & 0xFFFF;
  416. }
  417. /**
  418. * Converts an index value for a text column into the entry value (which
  419. * is based on a variety of nifty codes).
  420. */
  421. void writeNonNullIndexTextValue(
  422. Object value, ByteStream bout, boolean isAscending)
  423. throws IOException
  424. {
  425. // first, convert to string
  426. String str = ColumnImpl.toCharSequence(value).toString();
  427. // all text columns (including memos) are only indexed up to the max
  428. // number of chars in a VARCHAR column
  429. if(str.length() > MAX_TEXT_INDEX_CHAR_LENGTH) {
  430. str = str.substring(0, MAX_TEXT_INDEX_CHAR_LENGTH);
  431. }
  432. // record pprevious entry length so we can do any post-processing
  433. // necessary for this entry (handling descending)
  434. int prevLength = bout.getLength();
  435. // now, convert each character to a "code" of one or more bytes
  436. ExtraCodesStream extraCodes = null;
  437. ByteStream unprintableCodes = null;
  438. ByteStream crazyCodes = null;
  439. int charOffset = 0;
  440. for(int i = 0; i < str.length(); ++i) {
  441. char c = str.charAt(i);
  442. CharHandler ch = getCharHandler(c);
  443. int curCharOffset = charOffset;
  444. byte[] bytes = ch.getInlineBytes();
  445. if(bytes != null) {
  446. // write the "inline" codes immediately
  447. bout.write(bytes);
  448. // only increment the charOffset for chars with inline codes
  449. ++charOffset;
  450. }
  451. if(ch.getType() == Type.SIMPLE) {
  452. // common case, skip further code handling
  453. continue;
  454. }
  455. bytes = ch.getExtraBytes();
  456. byte extraCodeModifier = ch.getExtraByteModifier();
  457. if((bytes != null) || (extraCodeModifier != 0)) {
  458. if(extraCodes == null) {
  459. extraCodes = new ExtraCodesStream(str.length());
  460. }
  461. // keep track of the extra codes for later
  462. writeExtraCodes(curCharOffset, bytes, extraCodeModifier, extraCodes);
  463. }
  464. bytes = ch.getUnprintableBytes();
  465. if(bytes != null) {
  466. if(unprintableCodes == null) {
  467. unprintableCodes = new ByteStream();
  468. }
  469. // keep track of the unprintable codes for later
  470. writeUnprintableCodes(curCharOffset, bytes, unprintableCodes,
  471. extraCodes);
  472. }
  473. byte crazyFlag = ch.getCrazyFlag();
  474. if(crazyFlag != 0) {
  475. if(crazyCodes == null) {
  476. crazyCodes = new ByteStream();
  477. }
  478. // keep track of the crazy flags for later
  479. crazyCodes.write(crazyFlag);
  480. }
  481. }
  482. // write end text flag
  483. bout.write(END_TEXT);
  484. boolean hasExtraCodes = trimExtraCodes(
  485. extraCodes, (byte)0, INTERNATIONAL_EXTRA_PLACEHOLDER);
  486. boolean hasUnprintableCodes = (unprintableCodes != null);
  487. boolean hasCrazyCodes = (crazyCodes != null);
  488. if(hasExtraCodes || hasUnprintableCodes || hasCrazyCodes) {
  489. // we write all the international extra bytes first
  490. if(hasExtraCodes) {
  491. extraCodes.writeTo(bout);
  492. }
  493. if(hasCrazyCodes || hasUnprintableCodes) {
  494. // write 2 more end flags
  495. bout.write(END_TEXT);
  496. bout.write(END_TEXT);
  497. // next come the crazy flags
  498. if(hasCrazyCodes) {
  499. writeCrazyCodes(crazyCodes, bout);
  500. // if we are writing unprintable codes after this, tack on another
  501. // code
  502. if(hasUnprintableCodes) {
  503. bout.write(CRAZY_CODES_UNPRINT_SUFFIX);
  504. }
  505. }
  506. // then we write all the unprintable extra bytes
  507. if(hasUnprintableCodes) {
  508. // write another end flag
  509. bout.write(END_TEXT);
  510. unprintableCodes.writeTo(bout);
  511. }
  512. }
  513. }
  514. // handle descending order by inverting the bytes
  515. if(!isAscending) {
  516. // we actually write the end byte before flipping the bytes, and write
  517. // another one after flipping
  518. bout.write(END_EXTRA_TEXT);
  519. // flip the bytes that we have written thus far for this text value
  520. IndexData.flipBytes(bout.getBytes(), prevLength,
  521. (bout.getLength() - prevLength));
  522. }
  523. // write end extra text
  524. bout.write(END_EXTRA_TEXT);
  525. }
  526. /**
  527. * Encodes the given extra code info in the given stream.
  528. */
  529. private static void writeExtraCodes(
  530. int charOffset, byte[] bytes, byte extraCodeModifier,
  531. ExtraCodesStream extraCodes)
  532. throws IOException
  533. {
  534. // we fill in a placeholder value for any chars w/out extra codes
  535. int numChars = extraCodes.getNumChars();
  536. if(numChars < charOffset) {
  537. int fillChars = charOffset - numChars;
  538. extraCodes.writeFill(fillChars, INTERNATIONAL_EXTRA_PLACEHOLDER);
  539. extraCodes.incrementNumChars(fillChars);
  540. }
  541. if(bytes != null) {
  542. // write the actual extra codes and update the number of chars
  543. extraCodes.write(bytes);
  544. extraCodes.incrementNumChars(1);
  545. } else {
  546. // extra code modifiers modify the existing extra code bytes and do not
  547. // count as additional extra code chars
  548. int lastIdx = extraCodes.getLength() - 1;
  549. if(lastIdx >= 0) {
  550. // the extra code modifier is added to the last extra code written
  551. byte lastByte = extraCodes.get(lastIdx);
  552. lastByte += extraCodeModifier;
  553. extraCodes.set(lastIdx, lastByte);
  554. } else {
  555. // there is no previous extra code, add a new code (but keep track of
  556. // this "unprintable code" prefix)
  557. extraCodes.write(extraCodeModifier);
  558. extraCodes.setUnprintablePrefixLen(1);
  559. }
  560. }
  561. }
  562. /**
  563. * Trims any bytes in the given range off of the end of the given stream,
  564. * returning whether or not there are any bytes left in the given stream
  565. * after trimming.
  566. */
  567. private static boolean trimExtraCodes(ByteStream extraCodes,
  568. byte minTrimCode, byte maxTrimCode)
  569. throws IOException
  570. {
  571. if(extraCodes == null) {
  572. return false;
  573. }
  574. extraCodes.trimTrailing(minTrimCode, maxTrimCode);
  575. // anything left?
  576. return (extraCodes.getLength() > 0);
  577. }
  578. /**
  579. * Encodes the given unprintable char codes in the given stream.
  580. */
  581. private static void writeUnprintableCodes(
  582. int charOffset, byte[] bytes, ByteStream unprintableCodes,
  583. ExtraCodesStream extraCodes)
  584. throws IOException
  585. {
  586. // the offset seems to be calculated based on the number of bytes in the
  587. // "extra codes" part of the entry (even if there are no extra codes bytes
  588. // actually written in the final entry).
  589. int unprintCharOffset = charOffset;
  590. if(extraCodes != null) {
  591. // we need to account for some extra codes which have not been written
  592. // yet. additionally, any unprintable bytes added to the beginning of
  593. // the extra codes are ignored.
  594. unprintCharOffset = extraCodes.getLength() +
  595. (charOffset - extraCodes.getNumChars()) -
  596. extraCodes.getUnprintablePrefixLen();
  597. }
  598. // we write a whacky combo of bytes for each unprintable char which
  599. // includes a funky offset and extra char itself
  600. int offset =
  601. (UNPRINTABLE_COUNT_START +
  602. (UNPRINTABLE_COUNT_MULTIPLIER * unprintCharOffset))
  603. | UNPRINTABLE_OFFSET_FLAGS;
  604. // write offset as big-endian short
  605. unprintableCodes.write((offset >> 8) & 0xFF);
  606. unprintableCodes.write(offset & 0xFF);
  607. unprintableCodes.write(UNPRINTABLE_MIDFIX);
  608. unprintableCodes.write(bytes);
  609. }
  610. /**
  611. * Encode the given crazy code bytes into the given byte stream.
  612. */
  613. private static void writeCrazyCodes(ByteStream crazyCodes, ByteStream bout)
  614. throws IOException
  615. {
  616. // CRAZY_CODE_2 flags at the end are ignored, so ditch them
  617. trimExtraCodes(crazyCodes, CRAZY_CODE_2, CRAZY_CODE_2);
  618. if(crazyCodes.getLength() > 0) {
  619. // the crazy codes get encoded into 6 bit sequences where each code is 2
  620. // bits (where the first 2 bits in the byte are a common prefix).
  621. byte curByte = CRAZY_CODE_START;
  622. int idx = 0;
  623. for(int i = 0; i < crazyCodes.getLength(); ++i) {
  624. byte nextByte = crazyCodes.get(i);
  625. nextByte <<= ((2 - idx) * 2);
  626. curByte |= nextByte;
  627. ++idx;
  628. if(idx == 3) {
  629. // write current byte and reset
  630. bout.write(curByte);
  631. curByte = CRAZY_CODE_START;
  632. idx = 0;
  633. }
  634. }
  635. // write last byte
  636. if(idx > 0) {
  637. bout.write(curByte);
  638. }
  639. }
  640. // write crazy code suffix (note, we write this even if all the codes are
  641. // trimmed
  642. bout.write(CRAZY_CODES_SUFFIX);
  643. }
  644. /**
  645. * Extension of ByteStream which keeps track of an additional char count and
  646. * the length of any "unprintable" code prefix.
  647. */
  648. private static final class ExtraCodesStream extends ByteStream
  649. {
  650. private int _numChars;
  651. private int _unprintablePrefixLen;
  652. private ExtraCodesStream(int length) {
  653. super(length);
  654. }
  655. public int getNumChars() {
  656. return _numChars;
  657. }
  658. public void incrementNumChars(int inc) {
  659. _numChars += inc;
  660. }
  661. public int getUnprintablePrefixLen() {
  662. return _unprintablePrefixLen;
  663. }
  664. public void setUnprintablePrefixLen(int len) {
  665. _unprintablePrefixLen = len;
  666. }
  667. }
  668. }