BinaryDictInputOutput.java revision 4455fe2c894f8aabaf2b3105b72f9193226d4aba
1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17package com.android.inputmethod.latin.makedict; 18 19import com.android.inputmethod.latin.makedict.FusionDictionary.CharGroup; 20import com.android.inputmethod.latin.makedict.FusionDictionary.DictionaryOptions; 21import com.android.inputmethod.latin.makedict.FusionDictionary.Node; 22import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString; 23 24import java.io.ByteArrayOutputStream; 25import java.io.FileNotFoundException; 26import java.io.IOException; 27import java.io.OutputStream; 28import java.io.RandomAccessFile; 29import java.util.ArrayList; 30import java.util.Arrays; 31import java.util.HashMap; 32import java.util.Iterator; 33import java.util.Map; 34import java.util.TreeMap; 35 36/** 37 * Reads and writes XML files for a FusionDictionary. 38 * 39 * All the methods in this class are static. 40 */ 41public class BinaryDictInputOutput { 42 43 /* Node layout is as follows: 44 * | addressType xx : mask with MASK_GROUP_ADDRESS_TYPE 45 * 2 bits, 00 = no children : FLAG_GROUP_ADDRESS_TYPE_NOADDRESS 46 * f | 01 = 1 byte : FLAG_GROUP_ADDRESS_TYPE_ONEBYTE 47 * l | 10 = 2 bytes : FLAG_GROUP_ADDRESS_TYPE_TWOBYTES 48 * a | 11 = 3 bytes : FLAG_GROUP_ADDRESS_TYPE_THREEBYTES 49 * g | has several chars ? 1 bit, 1 = yes, 0 = no : FLAG_HAS_MULTIPLE_CHARS 50 * s | has a terminal ? 1 bit, 1 = yes, 0 = no : FLAG_IS_TERMINAL 51 * | has shortcut targets ? 1 bit, 1 = yes, 0 = no : FLAG_HAS_SHORTCUT_TARGETS 52 * | has bigrams ? 1 bit, 1 = yes, 0 = no : FLAG_HAS_BIGRAMS 53 * 54 * c | IF FLAG_HAS_MULTIPLE_CHARS 55 * h | char, char, char, char n * (1 or 3 bytes) : use CharGroupInfo for i/o helpers 56 * a | end 1 byte, = 0 57 * r | ELSE 58 * s | char 1 or 3 bytes 59 * | END 60 * 61 * f | 62 * r | IF FLAG_IS_TERMINAL 63 * e | frequency 1 byte 64 * q | 65 * 66 * c | IF 00 = FLAG_GROUP_ADDRESS_TYPE_NOADDRESS = addressType 67 * h | // nothing 68 * i | ELSIF 01 = FLAG_GROUP_ADDRESS_TYPE_ONEBYTE == addressType 69 * l | children address, 1 byte 70 * d | ELSIF 10 = FLAG_GROUP_ADDRESS_TYPE_TWOBYTES == addressType 71 * r | children address, 2 bytes 72 * e | ELSE // 11 = FLAG_GROUP_ADDRESS_TYPE_THREEBYTES = addressType 73 * n | children address, 3 bytes 74 * A | END 75 * d 76 * dress 77 * 78 * | IF FLAG_IS_TERMINAL && FLAG_HAS_SHORTCUT_TARGETS 79 * | shortcut string list 80 * | IF FLAG_IS_TERMINAL && FLAG_HAS_BIGRAMS 81 * | bigrams address list 82 * 83 * Char format is: 84 * 1 byte = bbbbbbbb match 85 * case 000xxxxx: xxxxx << 16 + next byte << 8 + next byte 86 * else: if 00011111 (= 0x1F) : this is the terminator. This is a relevant choice because 87 * unicode code points range from 0 to 0x10FFFF, so any 3-byte value starting with 88 * 00011111 would be outside unicode. 89 * else: iso-latin-1 code 90 * This allows for the whole unicode range to be encoded, including chars outside of 91 * the BMP. Also everything in the iso-latin-1 charset is only 1 byte, except control 92 * characters which should never happen anyway (and still work, but take 3 bytes). 93 * 94 * bigram address list is: 95 * <flags> = | hasNext = 1 bit, 1 = yes, 0 = no : FLAG_ATTRIBUTE_HAS_NEXT 96 * | addressSign = 1 bit, : FLAG_ATTRIBUTE_OFFSET_NEGATIVE 97 * | 1 = must take -address, 0 = must take +address 98 * | xx : mask with MASK_ATTRIBUTE_ADDRESS_TYPE 99 * | addressFormat = 2 bits, 00 = unused : FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE 100 * | 01 = 1 byte : FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE 101 * | 10 = 2 bytes : FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES 102 * | 11 = 3 bytes : FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES 103 * | 4 bits : frequency : mask with FLAG_ATTRIBUTE_FREQUENCY 104 * <address> | IF (01 == FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE == addressFormat) 105 * | read 1 byte, add top 4 bits 106 * | ELSIF (10 == FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES == addressFormat) 107 * | read 2 bytes, add top 4 bits 108 * | ELSE // 11 == FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES == addressFormat 109 * | read 3 bytes, add top 4 bits 110 * | END 111 * | if (FLAG_ATTRIBUTE_OFFSET_NEGATIVE) then address = -address 112 * if (FLAG_ATTRIBUTE_HAS_NEXT) goto bigram_and_shortcut_address_list_is 113 * 114 * shortcut string list is: 115 * <byte size> = GROUP_SHORTCUT_LIST_SIZE_SIZE bytes, big-endian: size of the list, in bytes. 116 * <flags> = | hasNext = 1 bit, 1 = yes, 0 = no : FLAG_ATTRIBUTE_HAS_NEXT 117 * | reserved = 3 bits, must be 0 118 * | 4 bits : frequency : mask with FLAG_ATTRIBUTE_FREQUENCY 119 * <shortcut> = | string of characters at the char format described above, with the terminator 120 * | used to signal the end of the string. 121 * if (FLAG_ATTRIBUTE_HAS_NEXT goto flags 122 */ 123 124 private static final int VERSION_1_MAGIC_NUMBER = 0x78B1; 125 private static final int VERSION_2_MAGIC_NUMBER = 0x9BC13AFE; 126 private static final int MINIMUM_SUPPORTED_VERSION = 1; 127 private static final int MAXIMUM_SUPPORTED_VERSION = 2; 128 private static final int NOT_A_VERSION_NUMBER = -1; 129 private static final int FIRST_VERSION_WITH_HEADER_SIZE = 2; 130 131 // These options need to be the same numeric values as the one in the native reading code. 132 private static final int GERMAN_UMLAUT_PROCESSING_FLAG = 0x1; 133 private static final int FRENCH_LIGATURE_PROCESSING_FLAG = 0x4; 134 private static final int CONTAINS_BIGRAMS_FLAG = 0x8; 135 136 // TODO: Make this value adaptative to content data, store it in the header, and 137 // use it in the reading code. 138 private static final int MAX_WORD_LENGTH = 48; 139 140 private static final int MASK_GROUP_ADDRESS_TYPE = 0xC0; 141 private static final int FLAG_GROUP_ADDRESS_TYPE_NOADDRESS = 0x00; 142 private static final int FLAG_GROUP_ADDRESS_TYPE_ONEBYTE = 0x40; 143 private static final int FLAG_GROUP_ADDRESS_TYPE_TWOBYTES = 0x80; 144 private static final int FLAG_GROUP_ADDRESS_TYPE_THREEBYTES = 0xC0; 145 146 private static final int FLAG_HAS_MULTIPLE_CHARS = 0x20; 147 148 private static final int FLAG_IS_TERMINAL = 0x10; 149 private static final int FLAG_HAS_SHORTCUT_TARGETS = 0x08; 150 private static final int FLAG_HAS_BIGRAMS = 0x04; 151 152 private static final int FLAG_ATTRIBUTE_HAS_NEXT = 0x80; 153 private static final int FLAG_ATTRIBUTE_OFFSET_NEGATIVE = 0x40; 154 private static final int MASK_ATTRIBUTE_ADDRESS_TYPE = 0x30; 155 private static final int FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE = 0x10; 156 private static final int FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES = 0x20; 157 private static final int FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES = 0x30; 158 private static final int FLAG_ATTRIBUTE_FREQUENCY = 0x0F; 159 160 private static final int GROUP_CHARACTERS_TERMINATOR = 0x1F; 161 162 private static final int GROUP_TERMINATOR_SIZE = 1; 163 private static final int GROUP_FLAGS_SIZE = 1; 164 private static final int GROUP_FREQUENCY_SIZE = 1; 165 private static final int GROUP_MAX_ADDRESS_SIZE = 3; 166 private static final int GROUP_ATTRIBUTE_FLAGS_SIZE = 1; 167 private static final int GROUP_ATTRIBUTE_MAX_ADDRESS_SIZE = 3; 168 private static final int GROUP_SHORTCUT_LIST_SIZE_SIZE = 2; 169 170 private static final int NO_CHILDREN_ADDRESS = Integer.MIN_VALUE; 171 private static final int INVALID_CHARACTER = -1; 172 173 private static final int MAX_CHARGROUPS_FOR_ONE_BYTE_CHARGROUP_COUNT = 0x7F; // 127 174 private static final int MAX_CHARGROUPS_IN_A_NODE = 0x7FFF; // 32767 175 176 private static final int MAX_TERMINAL_FREQUENCY = 255; 177 178 // Arbitrary limit to how much passes we consider address size compression should 179 // terminate in. At the time of this writing, our largest dictionary completes 180 // compression in five passes. 181 // If the number of passes exceeds this number, makedict bails with an exception on 182 // suspicion that a bug might be causing an infinite loop. 183 private static final int MAX_PASSES = 24; 184 185 /** 186 * A class grouping utility function for our specific character encoding. 187 */ 188 private static class CharEncoding { 189 190 private static final int MINIMAL_ONE_BYTE_CHARACTER_VALUE = 0x20; 191 private static final int MAXIMAL_ONE_BYTE_CHARACTER_VALUE = 0xFF; 192 193 /** 194 * Helper method to find out whether this code fits on one byte 195 */ 196 private static boolean fitsOnOneByte(int character) { 197 return character >= MINIMAL_ONE_BYTE_CHARACTER_VALUE 198 && character <= MAXIMAL_ONE_BYTE_CHARACTER_VALUE; 199 } 200 201 /** 202 * Compute the size of a character given its character code. 203 * 204 * Char format is: 205 * 1 byte = bbbbbbbb match 206 * case 000xxxxx: xxxxx << 16 + next byte << 8 + next byte 207 * else: if 00011111 (= 0x1F) : this is the terminator. This is a relevant choice because 208 * unicode code points range from 0 to 0x10FFFF, so any 3-byte value starting with 209 * 00011111 would be outside unicode. 210 * else: iso-latin-1 code 211 * This allows for the whole unicode range to be encoded, including chars outside of 212 * the BMP. Also everything in the iso-latin-1 charset is only 1 byte, except control 213 * characters which should never happen anyway (and still work, but take 3 bytes). 214 * 215 * @param character the character code. 216 * @return the size in binary encoded-form, either 1 or 3 bytes. 217 */ 218 private static int getCharSize(int character) { 219 // See char encoding in FusionDictionary.java 220 if (fitsOnOneByte(character)) return 1; 221 if (INVALID_CHARACTER == character) return 1; 222 return 3; 223 } 224 225 /** 226 * Compute the byte size of a character array. 227 */ 228 private static int getCharArraySize(final int[] chars) { 229 int size = 0; 230 for (int character : chars) size += getCharSize(character); 231 return size; 232 } 233 234 /** 235 * Writes a char array to a byte buffer. 236 * 237 * @param codePoints the code point array to write. 238 * @param buffer the byte buffer to write to. 239 * @param index the index in buffer to write the character array to. 240 * @return the index after the last character. 241 */ 242 private static int writeCharArray(final int[] codePoints, final byte[] buffer, int index) { 243 for (int codePoint : codePoints) { 244 if (1 == getCharSize(codePoint)) { 245 buffer[index++] = (byte)codePoint; 246 } else { 247 buffer[index++] = (byte)(0xFF & (codePoint >> 16)); 248 buffer[index++] = (byte)(0xFF & (codePoint >> 8)); 249 buffer[index++] = (byte)(0xFF & codePoint); 250 } 251 } 252 return index; 253 } 254 255 /** 256 * Writes a string with our character format to a byte buffer. 257 * 258 * This will also write the terminator byte. 259 * 260 * @param buffer the byte buffer to write to. 261 * @param origin the offset to write from. 262 * @param word the string to write. 263 * @return the size written, in bytes. 264 */ 265 private static int writeString(final byte[] buffer, final int origin, 266 final String word) { 267 final int length = word.length(); 268 int index = origin; 269 for (int i = 0; i < length; i = word.offsetByCodePoints(i, 1)) { 270 final int codePoint = word.codePointAt(i); 271 if (1 == getCharSize(codePoint)) { 272 buffer[index++] = (byte)codePoint; 273 } else { 274 buffer[index++] = (byte)(0xFF & (codePoint >> 16)); 275 buffer[index++] = (byte)(0xFF & (codePoint >> 8)); 276 buffer[index++] = (byte)(0xFF & codePoint); 277 } 278 } 279 buffer[index++] = GROUP_CHARACTERS_TERMINATOR; 280 return index - origin; 281 } 282 283 /** 284 * Writes a string with our character format to a ByteArrayOutputStream. 285 * 286 * This will also write the terminator byte. 287 * 288 * @param buffer the ByteArrayOutputStream to write to. 289 * @param word the string to write. 290 */ 291 private static void writeString(ByteArrayOutputStream buffer, final String word) { 292 final int length = word.length(); 293 for (int i = 0; i < length; i = word.offsetByCodePoints(i, 1)) { 294 final int codePoint = word.codePointAt(i); 295 if (1 == getCharSize(codePoint)) { 296 buffer.write((byte) codePoint); 297 } else { 298 buffer.write((byte) (0xFF & (codePoint >> 16))); 299 buffer.write((byte) (0xFF & (codePoint >> 8))); 300 buffer.write((byte) (0xFF & codePoint)); 301 } 302 } 303 buffer.write(GROUP_CHARACTERS_TERMINATOR); 304 } 305 306 /** 307 * Reads a string from a RandomAccessFile. This is the converse of the above method. 308 */ 309 private static String readString(final RandomAccessFile source) throws IOException { 310 final StringBuilder s = new StringBuilder(); 311 int character = readChar(source); 312 while (character != INVALID_CHARACTER) { 313 s.appendCodePoint(character); 314 character = readChar(source); 315 } 316 return s.toString(); 317 } 318 319 /** 320 * Reads a character from the file. 321 * 322 * This follows the character format documented earlier in this source file. 323 * 324 * @param source the file, positioned over an encoded character. 325 * @return the character code. 326 */ 327 private static int readChar(RandomAccessFile source) throws IOException { 328 int character = source.readUnsignedByte(); 329 if (!fitsOnOneByte(character)) { 330 if (GROUP_CHARACTERS_TERMINATOR == character) 331 return INVALID_CHARACTER; 332 character <<= 16; 333 character += source.readUnsignedShort(); 334 } 335 return character; 336 } 337 } 338 339 /** 340 * Compute the binary size of the character array in a group 341 * 342 * If only one character, this is the size of this character. If many, it's the sum of their 343 * sizes + 1 byte for the terminator. 344 * 345 * @param group the group 346 * @return the size of the char array, including the terminator if any 347 */ 348 private static int getGroupCharactersSize(CharGroup group) { 349 int size = CharEncoding.getCharArraySize(group.mChars); 350 if (group.hasSeveralChars()) size += GROUP_TERMINATOR_SIZE; 351 return size; 352 } 353 354 /** 355 * Compute the binary size of the group count 356 * @param count the group count 357 * @return the size of the group count, either 1 or 2 bytes. 358 */ 359 private static int getGroupCountSize(final int count) { 360 if (MAX_CHARGROUPS_FOR_ONE_BYTE_CHARGROUP_COUNT >= count) { 361 return 1; 362 } else if (MAX_CHARGROUPS_IN_A_NODE >= count) { 363 return 2; 364 } else { 365 throw new RuntimeException("Can't have more than " + MAX_CHARGROUPS_IN_A_NODE 366 + " groups in a node (found " + count +")"); 367 } 368 } 369 370 /** 371 * Compute the binary size of the group count for a node 372 * @param node the node 373 * @return the size of the group count, either 1 or 2 bytes. 374 */ 375 private static int getGroupCountSize(final Node node) { 376 return getGroupCountSize(node.mData.size()); 377 } 378 379 /** 380 * Compute the size of a shortcut in bytes. 381 */ 382 private static int getShortcutSize(final WeightedString shortcut) { 383 int size = GROUP_ATTRIBUTE_FLAGS_SIZE; 384 final String word = shortcut.mWord; 385 final int length = word.length(); 386 for (int i = 0; i < length; i = word.offsetByCodePoints(i, 1)) { 387 final int codePoint = word.codePointAt(i); 388 size += CharEncoding.getCharSize(codePoint); 389 } 390 size += GROUP_TERMINATOR_SIZE; 391 return size; 392 } 393 394 /** 395 * Compute the size of a shortcut list in bytes. 396 * 397 * This is known in advance and does not change according to position in the file 398 * like address lists do. 399 */ 400 private static int getShortcutListSize(final ArrayList<WeightedString> shortcutList) { 401 if (null == shortcutList) return 0; 402 int size = GROUP_SHORTCUT_LIST_SIZE_SIZE; 403 for (final WeightedString shortcut : shortcutList) { 404 size += getShortcutSize(shortcut); 405 } 406 return size; 407 } 408 409 /** 410 * Compute the maximum size of a CharGroup, assuming 3-byte addresses for everything. 411 * 412 * @param group the CharGroup to compute the size of. 413 * @return the maximum size of the group. 414 */ 415 private static int getCharGroupMaximumSize(CharGroup group) { 416 int size = getGroupCharactersSize(group) + GROUP_FLAGS_SIZE; 417 // If terminal, one byte for the frequency 418 if (group.isTerminal()) size += GROUP_FREQUENCY_SIZE; 419 size += GROUP_MAX_ADDRESS_SIZE; // For children address 420 size += getShortcutListSize(group.mShortcutTargets); 421 if (null != group.mBigrams) { 422 size += (GROUP_ATTRIBUTE_FLAGS_SIZE + GROUP_ATTRIBUTE_MAX_ADDRESS_SIZE) 423 * group.mBigrams.size(); 424 } 425 return size; 426 } 427 428 /** 429 * Compute the maximum size of a node, assuming 3-byte addresses for everything, and caches 430 * it in the 'actualSize' member of the node. 431 * 432 * @param node the node to compute the maximum size of. 433 */ 434 private static void setNodeMaximumSize(Node node) { 435 int size = getGroupCountSize(node); 436 for (CharGroup g : node.mData) { 437 final int groupSize = getCharGroupMaximumSize(g); 438 g.mCachedSize = groupSize; 439 size += groupSize; 440 } 441 node.mCachedSize = size; 442 } 443 444 /** 445 * Helper method to hide the actual value of the no children address. 446 */ 447 private static boolean hasChildrenAddress(int address) { 448 return NO_CHILDREN_ADDRESS != address; 449 } 450 451 /** 452 * Compute the size, in bytes, that an address will occupy. 453 * 454 * This can be used either for children addresses (which are always positive) or for 455 * attribute, which may be positive or negative but 456 * store their sign bit separately. 457 * 458 * @param address the address 459 * @return the byte size. 460 */ 461 private static int getByteSize(int address) { 462 assert(address < 0x1000000); 463 if (!hasChildrenAddress(address)) { 464 return 0; 465 } else if (Math.abs(address) < 0x100) { 466 return 1; 467 } else if (Math.abs(address) < 0x10000) { 468 return 2; 469 } else { 470 return 3; 471 } 472 } 473 // End utility methods. 474 475 // This method is responsible for finding a nice ordering of the nodes that favors run-time 476 // cache performance and dictionary size. 477 /* package for tests */ static ArrayList<Node> flattenTree(Node root) { 478 final int treeSize = FusionDictionary.countCharGroups(root); 479 MakedictLog.i("Counted nodes : " + treeSize); 480 final ArrayList<Node> flatTree = new ArrayList<Node>(treeSize); 481 return flattenTreeInner(flatTree, root); 482 } 483 484 private static ArrayList<Node> flattenTreeInner(ArrayList<Node> list, Node node) { 485 // Removing the node is necessary if the tails are merged, because we would then 486 // add the same node several times when we only want it once. A number of places in 487 // the code also depends on any node being only once in the list. 488 // Merging tails can only be done if there are no attributes. Searching for attributes 489 // in LatinIME code depends on a total breadth-first ordering, which merging tails 490 // breaks. If there are no attributes, it should be fine (and reduce the file size) 491 // to merge tails, and the following step would be necessary. 492 // If eventually the code runs on Android, searching through the whole array each time 493 // may be a performance concern. 494 list.remove(node); 495 list.add(node); 496 final ArrayList<CharGroup> branches = node.mData; 497 final int nodeSize = branches.size(); 498 for (CharGroup group : branches) { 499 if (null != group.mChildren) flattenTreeInner(list, group.mChildren); 500 } 501 return list; 502 } 503 504 /** 505 * Finds the absolute address of a word in the dictionary. 506 * 507 * @param dict the dictionary in which to search. 508 * @param word the word we are searching for. 509 * @return the word address. If it is not found, an exception is thrown. 510 */ 511 private static int findAddressOfWord(final FusionDictionary dict, final String word) { 512 return FusionDictionary.findWordInTree(dict.mRoot, word).mCachedAddress; 513 } 514 515 /** 516 * Computes the actual node size, based on the cached addresses of the children nodes. 517 * 518 * Each node stores its tentative address. During dictionary address computing, these 519 * are not final, but they can be used to compute the node size (the node size depends 520 * on the address of the children because the number of bytes necessary to store an 521 * address depends on its numeric value. The return value indicates whether the node 522 * contents (as in, any of the addresses stored in the cache fields) have changed with 523 * respect to their previous value. 524 * 525 * @param node the node to compute the size of. 526 * @param dict the dictionary in which the word/attributes are to be found. 527 * @return false if none of the cached addresses inside the node changed, true otherwise. 528 */ 529 private static boolean computeActualNodeSize(Node node, FusionDictionary dict) { 530 boolean changed = false; 531 int size = getGroupCountSize(node); 532 for (CharGroup group : node.mData) { 533 if (group.mCachedAddress != node.mCachedAddress + size) { 534 changed = true; 535 group.mCachedAddress = node.mCachedAddress + size; 536 } 537 int groupSize = GROUP_FLAGS_SIZE + getGroupCharactersSize(group); 538 if (group.isTerminal()) groupSize += GROUP_FREQUENCY_SIZE; 539 if (null != group.mChildren) { 540 final int offsetBasePoint= groupSize + node.mCachedAddress + size; 541 final int offset = group.mChildren.mCachedAddress - offsetBasePoint; 542 groupSize += getByteSize(offset); 543 } 544 groupSize += getShortcutListSize(group.mShortcutTargets); 545 if (null != group.mBigrams) { 546 for (WeightedString bigram : group.mBigrams) { 547 final int offsetBasePoint = groupSize + node.mCachedAddress + size 548 + GROUP_FLAGS_SIZE; 549 final int addressOfBigram = findAddressOfWord(dict, bigram.mWord); 550 final int offset = addressOfBigram - offsetBasePoint; 551 groupSize += getByteSize(offset) + GROUP_FLAGS_SIZE; 552 } 553 } 554 group.mCachedSize = groupSize; 555 size += groupSize; 556 } 557 if (node.mCachedSize != size) { 558 node.mCachedSize = size; 559 changed = true; 560 } 561 return changed; 562 } 563 564 /** 565 * Computes the byte size of a list of nodes and updates each node cached position. 566 * 567 * @param flatNodes the array of nodes. 568 * @return the byte size of the entire stack. 569 */ 570 private static int stackNodes(ArrayList<Node> flatNodes) { 571 int nodeOffset = 0; 572 for (Node n : flatNodes) { 573 n.mCachedAddress = nodeOffset; 574 int groupCountSize = getGroupCountSize(n); 575 int groupOffset = 0; 576 for (CharGroup g : n.mData) { 577 g.mCachedAddress = groupCountSize + nodeOffset + groupOffset; 578 groupOffset += g.mCachedSize; 579 } 580 if (groupOffset + groupCountSize != n.mCachedSize) { 581 throw new RuntimeException("Bug : Stored and computed node size differ"); 582 } 583 nodeOffset += n.mCachedSize; 584 } 585 return nodeOffset; 586 } 587 588 /** 589 * Compute the addresses and sizes of an ordered node array. 590 * 591 * This method takes a node array and will update its cached address and size values 592 * so that they can be written into a file. It determines the smallest size each of the 593 * nodes can be given the addresses of its children and attributes, and store that into 594 * each node. 595 * The order of the node is given by the order of the array. This method makes no effort 596 * to find a good order; it only mechanically computes the size this order results in. 597 * 598 * @param dict the dictionary 599 * @param flatNodes the ordered array of nodes 600 * @return the same array it was passed. The nodes have been updated for address and size. 601 */ 602 private static ArrayList<Node> computeAddresses(FusionDictionary dict, 603 ArrayList<Node> flatNodes) { 604 // First get the worst sizes and offsets 605 for (Node n : flatNodes) setNodeMaximumSize(n); 606 final int offset = stackNodes(flatNodes); 607 608 MakedictLog.i("Compressing the array addresses. Original size : " + offset); 609 MakedictLog.i("(Recursively seen size : " + offset + ")"); 610 611 int passes = 0; 612 boolean changesDone = false; 613 do { 614 changesDone = false; 615 for (Node n : flatNodes) { 616 final int oldNodeSize = n.mCachedSize; 617 final boolean changed = computeActualNodeSize(n, dict); 618 final int newNodeSize = n.mCachedSize; 619 if (oldNodeSize < newNodeSize) throw new RuntimeException("Increased size ?!"); 620 changesDone |= changed; 621 } 622 stackNodes(flatNodes); 623 ++passes; 624 if (passes > MAX_PASSES) throw new RuntimeException("Too many passes - probably a bug"); 625 } while (changesDone); 626 627 final Node lastNode = flatNodes.get(flatNodes.size() - 1); 628 MakedictLog.i("Compression complete in " + passes + " passes."); 629 MakedictLog.i("After address compression : " 630 + (lastNode.mCachedAddress + lastNode.mCachedSize)); 631 632 return flatNodes; 633 } 634 635 /** 636 * Sanity-checking method. 637 * 638 * This method checks an array of node for juxtaposition, that is, it will do 639 * nothing if each node's cached address is actually the previous node's address 640 * plus the previous node's size. 641 * If this is not the case, it will throw an exception. 642 * 643 * @param array the array node to check 644 */ 645 private static void checkFlatNodeArray(ArrayList<Node> array) { 646 int offset = 0; 647 int index = 0; 648 for (Node n : array) { 649 if (n.mCachedAddress != offset) { 650 throw new RuntimeException("Wrong address for node " + index 651 + " : expected " + offset + ", got " + n.mCachedAddress); 652 } 653 ++index; 654 offset += n.mCachedSize; 655 } 656 } 657 658 /** 659 * Helper method to write a variable-size address to a file. 660 * 661 * @param buffer the buffer to write to. 662 * @param index the index in the buffer to write the address to. 663 * @param address the address to write. 664 * @return the size in bytes the address actually took. 665 */ 666 private static int writeVariableAddress(final byte[] buffer, int index, final int address) { 667 switch (getByteSize(address)) { 668 case 1: 669 buffer[index++] = (byte)address; 670 return 1; 671 case 2: 672 buffer[index++] = (byte)(0xFF & (address >> 8)); 673 buffer[index++] = (byte)(0xFF & address); 674 return 2; 675 case 3: 676 buffer[index++] = (byte)(0xFF & (address >> 16)); 677 buffer[index++] = (byte)(0xFF & (address >> 8)); 678 buffer[index++] = (byte)(0xFF & address); 679 return 3; 680 case 0: 681 return 0; 682 default: 683 throw new RuntimeException("Address " + address + " has a strange size"); 684 } 685 } 686 687 private static byte makeCharGroupFlags(final CharGroup group, final int groupAddress, 688 final int childrenOffset) { 689 byte flags = 0; 690 if (group.mChars.length > 1) flags |= FLAG_HAS_MULTIPLE_CHARS; 691 if (group.mFrequency >= 0) { 692 flags |= FLAG_IS_TERMINAL; 693 } 694 if (null != group.mChildren) { 695 switch (getByteSize(childrenOffset)) { 696 case 1: 697 flags |= FLAG_GROUP_ADDRESS_TYPE_ONEBYTE; 698 break; 699 case 2: 700 flags |= FLAG_GROUP_ADDRESS_TYPE_TWOBYTES; 701 break; 702 case 3: 703 flags |= FLAG_GROUP_ADDRESS_TYPE_THREEBYTES; 704 break; 705 default: 706 throw new RuntimeException("Node with a strange address"); 707 } 708 } 709 if (null != group.mShortcutTargets) { 710 if (0 == group.mShortcutTargets.size()) { 711 throw new RuntimeException("0-sized shortcut list must be null"); 712 } 713 flags |= FLAG_HAS_SHORTCUT_TARGETS; 714 } 715 if (null != group.mBigrams) { 716 if (0 == group.mBigrams.size()) { 717 throw new RuntimeException("0-sized bigram list must be null"); 718 } 719 flags |= FLAG_HAS_BIGRAMS; 720 } 721 return flags; 722 } 723 724 /** 725 * Makes the flag value for a bigram. 726 * 727 * @param more whether there are more bigrams after this one. 728 * @param offset the offset of the bigram. 729 * @param bigramFrequency the frequency of the bigram, 0..15. 730 * @param unigramFrequency the unigram frequency of the same word. 731 * @return the flags 732 */ 733 private static final int makeBigramFlags(final boolean more, final int offset, 734 final int bigramFrequency, final int unigramFrequency) { 735 int bigramFlags = (more ? FLAG_ATTRIBUTE_HAS_NEXT : 0) 736 + (offset < 0 ? FLAG_ATTRIBUTE_OFFSET_NEGATIVE : 0); 737 switch (getByteSize(offset)) { 738 case 1: 739 bigramFlags |= FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE; 740 break; 741 case 2: 742 bigramFlags |= FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES; 743 break; 744 case 3: 745 bigramFlags |= FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES; 746 break; 747 default: 748 throw new RuntimeException("Strange offset size"); 749 } 750 bigramFlags += bigramFrequency & FLAG_ATTRIBUTE_FREQUENCY; 751 return bigramFlags; 752 } 753 754 /** 755 * Makes the 2-byte value for options flags. 756 */ 757 private static final int makeOptionsValue(final FusionDictionary dictionary) { 758 final DictionaryOptions options = dictionary.mOptions; 759 final boolean hasBigrams = dictionary.hasBigrams(); 760 return (options.mFrenchLigatureProcessing ? FRENCH_LIGATURE_PROCESSING_FLAG : 0) 761 + (options.mGermanUmlautProcessing ? GERMAN_UMLAUT_PROCESSING_FLAG : 0) 762 + (hasBigrams ? CONTAINS_BIGRAMS_FLAG : 0); 763 } 764 765 /** 766 * Makes the flag value for a shortcut. 767 * 768 * @param more whether there are more attributes after this one. 769 * @param frequency the frequency of the attribute, 0..15 770 * @return the flags 771 */ 772 private static final int makeShortcutFlags(final boolean more, final int frequency) { 773 return (more ? FLAG_ATTRIBUTE_HAS_NEXT : 0) + (frequency & FLAG_ATTRIBUTE_FREQUENCY); 774 } 775 776 /** 777 * Write a node to memory. The node is expected to have its final position cached. 778 * 779 * This can be an empty map, but the more is inside the faster the lookups will be. It can 780 * be carried on as long as nodes do not move. 781 * 782 * @param dict the dictionary the node is a part of (for relative offsets). 783 * @param buffer the memory buffer to write to. 784 * @param node the node to write. 785 * @return the address of the END of the node. 786 */ 787 private static int writePlacedNode(FusionDictionary dict, byte[] buffer, Node node) { 788 int index = node.mCachedAddress; 789 790 final int groupCount = node.mData.size(); 791 final int countSize = getGroupCountSize(node); 792 if (1 == countSize) { 793 buffer[index++] = (byte)groupCount; 794 } else if (2 == countSize) { 795 // We need to signal 2-byte size by setting the top bit of the MSB to 1, so 796 // we | 0x80 to do this. 797 buffer[index++] = (byte)((groupCount >> 8) | 0x80); 798 buffer[index++] = (byte)(groupCount & 0xFF); 799 } else { 800 throw new RuntimeException("Strange size from getGroupCountSize : " + countSize); 801 } 802 int groupAddress = index; 803 for (int i = 0; i < groupCount; ++i) { 804 CharGroup group = node.mData.get(i); 805 if (index != group.mCachedAddress) throw new RuntimeException("Bug: write index is not " 806 + "the same as the cached address of the group : " 807 + index + " <> " + group.mCachedAddress); 808 groupAddress += GROUP_FLAGS_SIZE + getGroupCharactersSize(group); 809 // Sanity checks. 810 if (group.mFrequency > MAX_TERMINAL_FREQUENCY) { 811 throw new RuntimeException("A node has a frequency > " + MAX_TERMINAL_FREQUENCY 812 + " : " + group.mFrequency); 813 } 814 if (group.mFrequency >= 0) groupAddress += GROUP_FREQUENCY_SIZE; 815 final int childrenOffset = null == group.mChildren 816 ? NO_CHILDREN_ADDRESS : group.mChildren.mCachedAddress - groupAddress; 817 byte flags = makeCharGroupFlags(group, groupAddress, childrenOffset); 818 buffer[index++] = flags; 819 index = CharEncoding.writeCharArray(group.mChars, buffer, index); 820 if (group.hasSeveralChars()) { 821 buffer[index++] = GROUP_CHARACTERS_TERMINATOR; 822 } 823 if (group.mFrequency >= 0) { 824 buffer[index++] = (byte) group.mFrequency; 825 } 826 final int shift = writeVariableAddress(buffer, index, childrenOffset); 827 index += shift; 828 groupAddress += shift; 829 830 // Write shortcuts 831 if (null != group.mShortcutTargets) { 832 final int indexOfShortcutByteSize = index; 833 index += GROUP_SHORTCUT_LIST_SIZE_SIZE; 834 groupAddress += GROUP_SHORTCUT_LIST_SIZE_SIZE; 835 final Iterator shortcutIterator = group.mShortcutTargets.iterator(); 836 while (shortcutIterator.hasNext()) { 837 final WeightedString target = (WeightedString)shortcutIterator.next(); 838 ++groupAddress; 839 int shortcutFlags = makeShortcutFlags(shortcutIterator.hasNext(), 840 target.mFrequency); 841 buffer[index++] = (byte)shortcutFlags; 842 final int shortcutShift = CharEncoding.writeString(buffer, index, target.mWord); 843 index += shortcutShift; 844 groupAddress += shortcutShift; 845 } 846 final int shortcutByteSize = index - indexOfShortcutByteSize; 847 if (shortcutByteSize > 0xFFFF) { 848 throw new RuntimeException("Shortcut list too large"); 849 } 850 buffer[indexOfShortcutByteSize] = (byte)(shortcutByteSize >> 8); 851 buffer[indexOfShortcutByteSize + 1] = (byte)(shortcutByteSize & 0xFF); 852 } 853 // Write bigrams 854 if (null != group.mBigrams) { 855 final Iterator bigramIterator = group.mBigrams.iterator(); 856 while (bigramIterator.hasNext()) { 857 final WeightedString bigram = (WeightedString)bigramIterator.next(); 858 final CharGroup target = 859 FusionDictionary.findWordInTree(dict.mRoot, bigram.mWord); 860 final int addressOfBigram = target.mCachedAddress; 861 final int unigramFrequencyForThisWord = target.mFrequency; 862 ++groupAddress; 863 final int offset = addressOfBigram - groupAddress; 864 int bigramFlags = makeBigramFlags(bigramIterator.hasNext(), offset, 865 bigram.mFrequency, unigramFrequencyForThisWord); 866 buffer[index++] = (byte)bigramFlags; 867 final int bigramShift = writeVariableAddress(buffer, index, Math.abs(offset)); 868 index += bigramShift; 869 groupAddress += bigramShift; 870 } 871 } 872 873 } 874 if (index != node.mCachedAddress + node.mCachedSize) throw new RuntimeException( 875 "Not the same size : written " 876 + (index - node.mCachedAddress) + " bytes out of a node that should have " 877 + node.mCachedSize + " bytes"); 878 return index; 879 } 880 881 /** 882 * Dumps a collection of useful statistics about a node array. 883 * 884 * This prints purely informative stuff, like the total estimated file size, the 885 * number of nodes, of character groups, the repartition of each address size, etc 886 * 887 * @param nodes the node array. 888 */ 889 private static void showStatistics(ArrayList<Node> nodes) { 890 int firstTerminalAddress = Integer.MAX_VALUE; 891 int lastTerminalAddress = Integer.MIN_VALUE; 892 int size = 0; 893 int charGroups = 0; 894 int maxGroups = 0; 895 int maxRuns = 0; 896 for (Node n : nodes) { 897 if (maxGroups < n.mData.size()) maxGroups = n.mData.size(); 898 for (CharGroup cg : n.mData) { 899 ++charGroups; 900 if (cg.mChars.length > maxRuns) maxRuns = cg.mChars.length; 901 if (cg.mFrequency >= 0) { 902 if (n.mCachedAddress < firstTerminalAddress) 903 firstTerminalAddress = n.mCachedAddress; 904 if (n.mCachedAddress > lastTerminalAddress) 905 lastTerminalAddress = n.mCachedAddress; 906 } 907 } 908 if (n.mCachedAddress + n.mCachedSize > size) size = n.mCachedAddress + n.mCachedSize; 909 } 910 final int[] groupCounts = new int[maxGroups + 1]; 911 final int[] runCounts = new int[maxRuns + 1]; 912 for (Node n : nodes) { 913 ++groupCounts[n.mData.size()]; 914 for (CharGroup cg : n.mData) { 915 ++runCounts[cg.mChars.length]; 916 } 917 } 918 919 MakedictLog.i("Statistics:\n" 920 + " total file size " + size + "\n" 921 + " " + nodes.size() + " nodes\n" 922 + " " + charGroups + " groups (" + ((float)charGroups / nodes.size()) 923 + " groups per node)\n" 924 + " first terminal at " + firstTerminalAddress + "\n" 925 + " last terminal at " + lastTerminalAddress + "\n" 926 + " Group stats : max = " + maxGroups); 927 for (int i = 0; i < groupCounts.length; ++i) { 928 MakedictLog.i(" " + i + " : " + groupCounts[i]); 929 } 930 MakedictLog.i(" Character run stats : max = " + maxRuns); 931 for (int i = 0; i < runCounts.length; ++i) { 932 MakedictLog.i(" " + i + " : " + runCounts[i]); 933 } 934 } 935 936 /** 937 * Dumps a FusionDictionary to a file. 938 * 939 * This is the public entry point to write a dictionary to a file. 940 * 941 * @param destination the stream to write the binary data to. 942 * @param dict the dictionary to write. 943 * @param version the version of the format to write, currently either 1 or 2. 944 */ 945 public static void writeDictionaryBinary(final OutputStream destination, 946 final FusionDictionary dict, final int version) 947 throws IOException, UnsupportedFormatException { 948 949 // Addresses are limited to 3 bytes, but since addresses can be relative to each node, the 950 // structure itself is not limited to 16MB. However, if it is over 16MB deciding the order 951 // of the nodes becomes a quite complicated problem, because though the dictionary itself 952 // does not have a size limit, each node must still be within 16MB of all its children and 953 // parents. As long as this is ensured, the dictionary file may grow to any size. 954 955 if (version < MINIMUM_SUPPORTED_VERSION || version > MAXIMUM_SUPPORTED_VERSION) { 956 throw new UnsupportedFormatException("Requested file format version " + version 957 + ", but this implementation only supports versions " 958 + MINIMUM_SUPPORTED_VERSION + " through " + MAXIMUM_SUPPORTED_VERSION); 959 } 960 961 ByteArrayOutputStream headerBuffer = new ByteArrayOutputStream(256); 962 963 // The magic number in big-endian order. 964 if (version >= FIRST_VERSION_WITH_HEADER_SIZE) { 965 // Magic number for version 2+. 966 headerBuffer.write((byte) (0xFF & (VERSION_2_MAGIC_NUMBER >> 24))); 967 headerBuffer.write((byte) (0xFF & (VERSION_2_MAGIC_NUMBER >> 16))); 968 headerBuffer.write((byte) (0xFF & (VERSION_2_MAGIC_NUMBER >> 8))); 969 headerBuffer.write((byte) (0xFF & VERSION_2_MAGIC_NUMBER)); 970 // Dictionary version. 971 headerBuffer.write((byte) (0xFF & (version >> 8))); 972 headerBuffer.write((byte) (0xFF & version)); 973 } else { 974 // Magic number for version 1. 975 headerBuffer.write((byte) (0xFF & (VERSION_1_MAGIC_NUMBER >> 8))); 976 headerBuffer.write((byte) (0xFF & VERSION_1_MAGIC_NUMBER)); 977 // Dictionary version. 978 headerBuffer.write((byte) (0xFF & version)); 979 } 980 // Options flags 981 final int options = makeOptionsValue(dict); 982 headerBuffer.write((byte) (0xFF & (options >> 8))); 983 headerBuffer.write((byte) (0xFF & options)); 984 if (version >= FIRST_VERSION_WITH_HEADER_SIZE) { 985 final int headerSizeOffset = headerBuffer.size(); 986 // Placeholder to be written later with header size. 987 for (int i = 0; i < 4; ++i) { 988 headerBuffer.write(0); 989 } 990 // Write out the options. 991 for (final String key : dict.mOptions.mAttributes.keySet()) { 992 final String value = dict.mOptions.mAttributes.get(key); 993 CharEncoding.writeString(headerBuffer, key); 994 CharEncoding.writeString(headerBuffer, value); 995 } 996 final int size = headerBuffer.size(); 997 final byte[] bytes = headerBuffer.toByteArray(); 998 // Write out the header size. 999 bytes[headerSizeOffset] = (byte) (0xFF & (size >> 24)); 1000 bytes[headerSizeOffset + 1] = (byte) (0xFF & (size >> 16)); 1001 bytes[headerSizeOffset + 2] = (byte) (0xFF & (size >> 8)); 1002 bytes[headerSizeOffset + 3] = (byte) (0xFF & (size >> 0)); 1003 destination.write(bytes); 1004 } else { 1005 headerBuffer.writeTo(destination); 1006 } 1007 1008 headerBuffer.close(); 1009 1010 // Leave the choice of the optimal node order to the flattenTree function. 1011 MakedictLog.i("Flattening the tree..."); 1012 ArrayList<Node> flatNodes = flattenTree(dict.mRoot); 1013 1014 MakedictLog.i("Computing addresses..."); 1015 computeAddresses(dict, flatNodes); 1016 MakedictLog.i("Checking array..."); 1017 checkFlatNodeArray(flatNodes); 1018 1019 // Create a buffer that matches the final dictionary size. 1020 final Node lastNode = flatNodes.get(flatNodes.size() - 1); 1021 final int bufferSize =(lastNode.mCachedAddress + lastNode.mCachedSize); 1022 final byte[] buffer = new byte[bufferSize]; 1023 int index = 0; 1024 1025 MakedictLog.i("Writing file..."); 1026 int dataEndOffset = 0; 1027 for (Node n : flatNodes) { 1028 dataEndOffset = writePlacedNode(dict, buffer, n); 1029 } 1030 1031 showStatistics(flatNodes); 1032 1033 destination.write(buffer, 0, dataEndOffset); 1034 1035 destination.close(); 1036 MakedictLog.i("Done"); 1037 } 1038 1039 1040 // Input methods: Read a binary dictionary to memory. 1041 // readDictionaryBinary is the public entry point for them. 1042 1043 static final int[] characterBuffer = new int[MAX_WORD_LENGTH]; 1044 private static CharGroupInfo readCharGroup(RandomAccessFile source, 1045 final int originalGroupAddress) throws IOException { 1046 int addressPointer = originalGroupAddress; 1047 final int flags = source.readUnsignedByte(); 1048 ++addressPointer; 1049 final int characters[]; 1050 if (0 != (flags & FLAG_HAS_MULTIPLE_CHARS)) { 1051 int index = 0; 1052 int character = CharEncoding.readChar(source); 1053 addressPointer += CharEncoding.getCharSize(character); 1054 while (-1 != character) { 1055 characterBuffer[index++] = character; 1056 character = CharEncoding.readChar(source); 1057 addressPointer += CharEncoding.getCharSize(character); 1058 } 1059 characters = Arrays.copyOfRange(characterBuffer, 0, index); 1060 } else { 1061 final int character = CharEncoding.readChar(source); 1062 addressPointer += CharEncoding.getCharSize(character); 1063 characters = new int[] { character }; 1064 } 1065 final int frequency; 1066 if (0 != (FLAG_IS_TERMINAL & flags)) { 1067 ++addressPointer; 1068 frequency = source.readUnsignedByte(); 1069 } else { 1070 frequency = CharGroup.NOT_A_TERMINAL; 1071 } 1072 int childrenAddress = addressPointer; 1073 switch (flags & MASK_GROUP_ADDRESS_TYPE) { 1074 case FLAG_GROUP_ADDRESS_TYPE_ONEBYTE: 1075 childrenAddress += source.readUnsignedByte(); 1076 addressPointer += 1; 1077 break; 1078 case FLAG_GROUP_ADDRESS_TYPE_TWOBYTES: 1079 childrenAddress += source.readUnsignedShort(); 1080 addressPointer += 2; 1081 break; 1082 case FLAG_GROUP_ADDRESS_TYPE_THREEBYTES: 1083 childrenAddress += (source.readUnsignedByte() << 16) + source.readUnsignedShort(); 1084 addressPointer += 3; 1085 break; 1086 case FLAG_GROUP_ADDRESS_TYPE_NOADDRESS: 1087 default: 1088 childrenAddress = NO_CHILDREN_ADDRESS; 1089 break; 1090 } 1091 ArrayList<WeightedString> shortcutTargets = null; 1092 if (0 != (flags & FLAG_HAS_SHORTCUT_TARGETS)) { 1093 final long pointerBefore = source.getFilePointer(); 1094 shortcutTargets = new ArrayList<WeightedString>(); 1095 source.readUnsignedShort(); // Skip the size 1096 while (true) { 1097 final int targetFlags = source.readUnsignedByte(); 1098 final String word = CharEncoding.readString(source); 1099 shortcutTargets.add(new WeightedString(word, 1100 targetFlags & FLAG_ATTRIBUTE_FREQUENCY)); 1101 if (0 == (targetFlags & FLAG_ATTRIBUTE_HAS_NEXT)) break; 1102 } 1103 addressPointer += (source.getFilePointer() - pointerBefore); 1104 } 1105 ArrayList<PendingAttribute> bigrams = null; 1106 if (0 != (flags & FLAG_HAS_BIGRAMS)) { 1107 bigrams = new ArrayList<PendingAttribute>(); 1108 while (true) { 1109 final int bigramFlags = source.readUnsignedByte(); 1110 ++addressPointer; 1111 final int sign = 0 == (bigramFlags & FLAG_ATTRIBUTE_OFFSET_NEGATIVE) ? 1 : -1; 1112 int bigramAddress = addressPointer; 1113 switch (bigramFlags & MASK_ATTRIBUTE_ADDRESS_TYPE) { 1114 case FLAG_ATTRIBUTE_ADDRESS_TYPE_ONEBYTE: 1115 bigramAddress += sign * source.readUnsignedByte(); 1116 addressPointer += 1; 1117 break; 1118 case FLAG_ATTRIBUTE_ADDRESS_TYPE_TWOBYTES: 1119 bigramAddress += sign * source.readUnsignedShort(); 1120 addressPointer += 2; 1121 break; 1122 case FLAG_ATTRIBUTE_ADDRESS_TYPE_THREEBYTES: 1123 final int offset = ((source.readUnsignedByte() << 16) 1124 + source.readUnsignedShort()); 1125 bigramAddress += sign * offset; 1126 addressPointer += 3; 1127 break; 1128 default: 1129 throw new RuntimeException("Has bigrams with no address"); 1130 } 1131 bigrams.add(new PendingAttribute(bigramFlags & FLAG_ATTRIBUTE_FREQUENCY, 1132 bigramAddress)); 1133 if (0 == (bigramFlags & FLAG_ATTRIBUTE_HAS_NEXT)) break; 1134 } 1135 } 1136 return new CharGroupInfo(originalGroupAddress, addressPointer, flags, characters, frequency, 1137 childrenAddress, shortcutTargets, bigrams); 1138 } 1139 1140 /** 1141 * Reads and returns the char group count out of a file and forwards the pointer. 1142 */ 1143 private static int readCharGroupCount(RandomAccessFile source) throws IOException { 1144 final int msb = source.readUnsignedByte(); 1145 if (MAX_CHARGROUPS_FOR_ONE_BYTE_CHARGROUP_COUNT >= msb) { 1146 return msb; 1147 } else { 1148 return ((MAX_CHARGROUPS_FOR_ONE_BYTE_CHARGROUP_COUNT & msb) << 8) 1149 + source.readUnsignedByte(); 1150 } 1151 } 1152 1153 // The word cache here is a stopgap bandaid to help the catastrophic performance 1154 // of this method. Since it performs direct, unbuffered random access to the file and 1155 // may be called hundreds of thousands of times, the resulting performance is not 1156 // reasonable without some kind of cache. Thus: 1157 // TODO: perform buffered I/O here and in other places in the code. 1158 private static TreeMap<Integer, String> wordCache = new TreeMap<Integer, String>(); 1159 /** 1160 * Finds, as a string, the word at the address passed as an argument. 1161 * 1162 * @param source the file to read from. 1163 * @param headerSize the size of the header. 1164 * @param address the address to seek. 1165 * @return the word, as a string. 1166 * @throws IOException if the file can't be read. 1167 */ 1168 private static String getWordAtAddress(final RandomAccessFile source, final long headerSize, 1169 int address) throws IOException { 1170 final String cachedString = wordCache.get(address); 1171 if (null != cachedString) return cachedString; 1172 final long originalPointer = source.getFilePointer(); 1173 source.seek(headerSize); 1174 final int count = readCharGroupCount(source); 1175 int groupOffset = getGroupCountSize(count); 1176 final StringBuilder builder = new StringBuilder(); 1177 String result = null; 1178 1179 CharGroupInfo last = null; 1180 for (int i = count - 1; i >= 0; --i) { 1181 CharGroupInfo info = readCharGroup(source, groupOffset); 1182 groupOffset = info.mEndAddress; 1183 if (info.mOriginalAddress == address) { 1184 builder.append(new String(info.mCharacters, 0, info.mCharacters.length)); 1185 result = builder.toString(); 1186 break; // and return 1187 } 1188 if (hasChildrenAddress(info.mChildrenAddress)) { 1189 if (info.mChildrenAddress > address) { 1190 if (null == last) continue; 1191 builder.append(new String(last.mCharacters, 0, last.mCharacters.length)); 1192 source.seek(last.mChildrenAddress + headerSize); 1193 groupOffset = last.mChildrenAddress + 1; 1194 i = source.readUnsignedByte(); 1195 last = null; 1196 continue; 1197 } 1198 last = info; 1199 } 1200 if (0 == i && hasChildrenAddress(last.mChildrenAddress)) { 1201 builder.append(new String(last.mCharacters, 0, last.mCharacters.length)); 1202 source.seek(last.mChildrenAddress + headerSize); 1203 groupOffset = last.mChildrenAddress + 1; 1204 i = source.readUnsignedByte(); 1205 last = null; 1206 continue; 1207 } 1208 } 1209 source.seek(originalPointer); 1210 wordCache.put(address, result); 1211 return result; 1212 } 1213 1214 /** 1215 * Reads a single node from a binary file. 1216 * 1217 * This methods reads the file at the current position of its file pointer. A node is 1218 * fully expected to start at the current position. 1219 * This will recursively read other nodes into the structure, populating the reverse 1220 * maps on the fly and using them to keep track of already read nodes. 1221 * 1222 * @param source the data file, correctly positioned at the start of a node. 1223 * @param headerSize the size, in bytes, of the file header. 1224 * @param reverseNodeMap a mapping from addresses to already read nodes. 1225 * @param reverseGroupMap a mapping from addresses to already read character groups. 1226 * @return the read node with all his children already read. 1227 */ 1228 private static Node readNode(RandomAccessFile source, long headerSize, 1229 Map<Integer, Node> reverseNodeMap, Map<Integer, CharGroup> reverseGroupMap) 1230 throws IOException { 1231 final int nodeOrigin = (int)(source.getFilePointer() - headerSize); 1232 final int count = readCharGroupCount(source); 1233 final ArrayList<CharGroup> nodeContents = new ArrayList<CharGroup>(); 1234 int groupOffset = nodeOrigin + getGroupCountSize(count); 1235 for (int i = count; i > 0; --i) { 1236 CharGroupInfo info = readCharGroup(source, groupOffset); 1237 ArrayList<WeightedString> shortcutTargets = info.mShortcutTargets; 1238 ArrayList<WeightedString> bigrams = null; 1239 if (null != info.mBigrams) { 1240 bigrams = new ArrayList<WeightedString>(); 1241 for (PendingAttribute bigram : info.mBigrams) { 1242 final String word = getWordAtAddress(source, headerSize, bigram.mAddress); 1243 bigrams.add(new WeightedString(word, bigram.mFrequency)); 1244 } 1245 } 1246 if (hasChildrenAddress(info.mChildrenAddress)) { 1247 Node children = reverseNodeMap.get(info.mChildrenAddress); 1248 if (null == children) { 1249 final long currentPosition = source.getFilePointer(); 1250 source.seek(info.mChildrenAddress + headerSize); 1251 children = readNode(source, headerSize, reverseNodeMap, reverseGroupMap); 1252 source.seek(currentPosition); 1253 } 1254 nodeContents.add( 1255 new CharGroup(info.mCharacters, shortcutTargets, bigrams, info.mFrequency, 1256 children)); 1257 } else { 1258 nodeContents.add( 1259 new CharGroup(info.mCharacters, shortcutTargets, bigrams, info.mFrequency)); 1260 } 1261 groupOffset = info.mEndAddress; 1262 } 1263 final Node node = new Node(nodeContents); 1264 node.mCachedAddress = nodeOrigin; 1265 reverseNodeMap.put(node.mCachedAddress, node); 1266 return node; 1267 } 1268 1269 /** 1270 * Helper function to get the binary format version from the header. 1271 */ 1272 private static int getFormatVersion(final RandomAccessFile source) throws IOException { 1273 final int magic_v1 = source.readUnsignedShort(); 1274 if (VERSION_1_MAGIC_NUMBER == magic_v1) return source.readUnsignedByte(); 1275 final int magic_v2 = (magic_v1 << 16) + source.readUnsignedShort(); 1276 if (VERSION_2_MAGIC_NUMBER == magic_v2) return source.readUnsignedShort(); 1277 return NOT_A_VERSION_NUMBER; 1278 } 1279 1280 /** 1281 * Reads a random access file and returns the memory representation of the dictionary. 1282 * 1283 * This high-level method takes a binary file and reads its contents, populating a 1284 * FusionDictionary structure. The optional dict argument is an existing dictionary to 1285 * which words from the file should be added. If it is null, a new dictionary is created. 1286 * 1287 * @param source the file to read. 1288 * @param dict an optional dictionary to add words to, or null. 1289 * @return the created (or merged) dictionary. 1290 */ 1291 public static FusionDictionary readDictionaryBinary(final RandomAccessFile source, 1292 final FusionDictionary dict) throws IOException, UnsupportedFormatException { 1293 // Check file version 1294 final int version = getFormatVersion(source); 1295 if (version < MINIMUM_SUPPORTED_VERSION || version > MAXIMUM_SUPPORTED_VERSION ) { 1296 throw new UnsupportedFormatException("This file has version " + version 1297 + ", but this implementation does not support versions above " 1298 + MAXIMUM_SUPPORTED_VERSION); 1299 } 1300 1301 // Read options 1302 final int optionsFlags = source.readUnsignedShort(); 1303 1304 final long headerSize; 1305 final HashMap<String, String> options = new HashMap<String, String>(); 1306 if (version < FIRST_VERSION_WITH_HEADER_SIZE) { 1307 headerSize = source.getFilePointer(); 1308 } else { 1309 headerSize = (source.readUnsignedByte() << 24) + (source.readUnsignedByte() << 16) 1310 + (source.readUnsignedByte() << 8) + source.readUnsignedByte(); 1311 while (source.getFilePointer() < headerSize) { 1312 final String key = CharEncoding.readString(source); 1313 final String value = CharEncoding.readString(source); 1314 options.put(key, value); 1315 } 1316 source.seek(headerSize); 1317 } 1318 1319 Map<Integer, Node> reverseNodeMapping = new TreeMap<Integer, Node>(); 1320 Map<Integer, CharGroup> reverseGroupMapping = new TreeMap<Integer, CharGroup>(); 1321 final Node root = readNode(source, headerSize, reverseNodeMapping, reverseGroupMapping); 1322 1323 FusionDictionary newDict = new FusionDictionary(root, 1324 new FusionDictionary.DictionaryOptions(options, 1325 0 != (optionsFlags & GERMAN_UMLAUT_PROCESSING_FLAG), 1326 0 != (optionsFlags & FRENCH_LIGATURE_PROCESSING_FLAG))); 1327 if (null != dict) { 1328 for (final Word w : dict) { 1329 newDict.add(w.mWord, w.mFrequency, w.mShortcutTargets); 1330 } 1331 for (final Word w : dict) { 1332 // By construction a binary dictionary may not have bigrams pointing to 1333 // words that are not also registered as unigrams so we don't have to avoid 1334 // them explicitly here. 1335 for (final WeightedString bigram : w.mBigrams) { 1336 newDict.setBigram(w.mWord, bigram.mWord, bigram.mFrequency); 1337 } 1338 } 1339 } 1340 1341 return newDict; 1342 } 1343 1344 /** 1345 * Basic test to find out whether the file is a binary dictionary or not. 1346 * 1347 * Concretely this only tests the magic number. 1348 * 1349 * @param filename The name of the file to test. 1350 * @return true if it's a binary dictionary, false otherwise 1351 */ 1352 public static boolean isBinaryDictionary(final String filename) { 1353 try { 1354 RandomAccessFile f = new RandomAccessFile(filename, "r"); 1355 final int version = getFormatVersion(f); 1356 return (version >= MINIMUM_SUPPORTED_VERSION && version <= MAXIMUM_SUPPORTED_VERSION); 1357 } catch (FileNotFoundException e) { 1358 return false; 1359 } catch (IOException e) { 1360 return false; 1361 } 1362 } 1363} 1364