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

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