diff options
10 files changed, 318 insertions, 180 deletions
diff --git a/java/src/com/android/inputmethod/latin/makedict/BinaryDictEncoderUtils.java b/java/src/com/android/inputmethod/latin/makedict/BinaryDictEncoderUtils.java index 79f5ad8bd..019e30b2e 100644 --- a/java/src/com/android/inputmethod/latin/makedict/BinaryDictEncoderUtils.java +++ b/java/src/com/android/inputmethod/latin/makedict/BinaryDictEncoderUtils.java @@ -912,23 +912,15 @@ public class BinaryDictEncoderUtils { } /** - * Dumps a FusionDictionary to a file. + * Writes a file header to an output stream. * - * @param destination the stream to write the binary data to. + * @param destination the stream to write the file header to. * @param dict the dictionary to write. * @param formatOptions file format options. */ - /* package */ static void writeDictionaryBinary(final OutputStream destination, + /* package */ static void writeDictionaryHeader(final OutputStream destination, final FusionDictionary dict, final FormatOptions formatOptions) - throws IOException, UnsupportedFormatException { - - // Addresses are limited to 3 bytes, but since addresses can be relative to each node - // array, the structure itself is not limited to 16MB. However, if it is over 16MB deciding - // the order of the PtNode arrays becomes a quite complicated problem, because though the - // dictionary itself does not have a size limit, each node array must still be within 16MB - // of all its children and parents. As long as this is ensured, the dictionary file may - // grow to any size. - + throws IOException, UnsupportedFormatException { final int version = formatOptions.mVersion; if (version < FormatSpec.MINIMUM_SUPPORTED_VERSION || version > FormatSpec.MAXIMUM_SUPPORTED_VERSION) { @@ -975,6 +967,24 @@ public class BinaryDictEncoderUtils { destination.write(bytes); headerBuffer.close(); + } + + /** + * Dumps a FusionDictionary to a file. + * + * @param destination the stream to write the dictionary body to. + * @param dict the dictionary to write. + * @param formatOptions file format options. + */ + /* package */ static void writeDictionaryBody(final OutputStream destination, + final FusionDictionary dict, final FormatOptions formatOptions) throws IOException { + + // Addresses are limited to 3 bytes, but since addresses can be relative to each node + // array, the structure itself is not limited to 16MB. However, if it is over 16MB deciding + // the order of the PtNode arrays becomes a quite complicated problem, because though the + // dictionary itself does not have a size limit, each node array must still be within 16MB + // of all its children and parents. As long as this is ensured, the dictionary file may + // grow to any size. // Leave the choice of the optimal node order to the flattenTree function. MakedictLog.i("Flattening the tree..."); diff --git a/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java b/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java index b8ef57696..bf35f6a8a 100644 --- a/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java +++ b/java/src/com/android/inputmethod/latin/makedict/FormatSpec.java @@ -112,8 +112,10 @@ public final class FormatSpec { * e | 1 byte = bbbbbbbb match * n | case 1xxxxxxx => -((0xxxxxxx << 16) + (next byte << 8) + next byte) * t | otherwise => (bbbbbbbb << 16) + (next byte << 8) + next byte - * a | - * ddress + * a | This address is relative to the head of the PtNode. + * d | If the node doesn't have a parent, this field is set to 0. + * d | + * ress * * c | IF FLAG_HAS_MULTIPLE_CHARS * h | char, char, char, char n * (1 or 3 bytes) : use PtNodeInfo for i/o helpers @@ -132,17 +134,18 @@ public final class FormatSpec { * i | 1 byte = bbbbbbbb match * l | case 1xxxxxxx => -((0xxxxxxx << 16) + (next byte << 8) + next byte) * d | otherwise => (bbbbbbbb<<16) + (next byte << 8) + next byte - * r | ELSIF 00 = FLAG_CHILDREN_ADDRESS_TYPE_NOADDRESS == addressType - * e | // nothing - * n | ELSIF 01 = FLAG_CHILDREN_ADDRESS_TYPE_ONEBYTE == addressType - * A | children address, 1 byte - * d | ELSIF 10 = FLAG_CHILDREN_ADDRESS_TYPE_TWOBYTES == addressType - * d | children address, 2 bytes - * r | ELSE // 11 = FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES = addressType - * e | children address, 3 bytes - * s | END - * s - * ress + * r | if this node doesn't have children, this field is set to 0. + * e | (see BinaryDictEncoderUtils#writeVariableSignedAddress) + * n | ELSIF 00 = FLAG_CHILDREN_ADDRESS_TYPE_NOADDRESS == addressType + * a | // nothing + * d | ELSIF 01 = FLAG_CHILDREN_ADDRESS_TYPE_ONEBYTE == addressType + * d | children address, 1 byte + * r | ELSIF 10 = FLAG_CHILDREN_ADDRESS_TYPE_TWOBYTES == addressType + * e | children address, 2 bytes + * s | ELSE // 11 = FLAG_CHILDREN_ADDRESS_TYPE_THREEBYTES = addressType + * s | children address, 3 bytes + * | END + * | This address is relative to the position of this field. * * | IF FLAG_IS_TERMINAL && FLAG_HAS_SHORTCUT_TARGETS * | shortcut string list diff --git a/java/src/com/android/inputmethod/latin/makedict/Ver3DictEncoder.java b/java/src/com/android/inputmethod/latin/makedict/Ver3DictEncoder.java index e81fd4514..4e28feac8 100644 --- a/java/src/com/android/inputmethod/latin/makedict/Ver3DictEncoder.java +++ b/java/src/com/android/inputmethod/latin/makedict/Ver3DictEncoder.java @@ -62,7 +62,8 @@ public class Ver3DictEncoder implements DictEncoder { if (mOutStream == null) { openStream(); } - BinaryDictEncoderUtils.writeDictionaryBinary(mOutStream, dict, formatOptions); + BinaryDictEncoderUtils.writeDictionaryHeader(mOutStream, dict, formatOptions); + BinaryDictEncoderUtils.writeDictionaryBody(mOutStream, dict, formatOptions); close(); } } diff --git a/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.cpp b/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.cpp index eb828b58c..196da5c97 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.cpp +++ b/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.cpp @@ -16,24 +16,115 @@ #include "suggest/policyimpl/dictionary/header/header_policy.h" +#include <cstddef> + namespace latinime { -const char *const HeaderPolicy::MULTIPLE_WORDS_DEMOTION_RATE_KEY = - "MULTIPLE_WORDS_DEMOTION_RATE"; -const float HeaderPolicy::DEFAULT_MULTI_WORD_COST_MULTIPLIER = 1.0f; -const float HeaderPolicy::MULTI_WORD_COST_MULTIPLIER_SCALE = 100.0f; +const char *const HeaderPolicy::MULTIPLE_WORDS_DEMOTION_RATE_KEY = "MULTIPLE_WORDS_DEMOTION_RATE"; +const char *const HeaderPolicy::USES_FORGETTING_CURVE_KEY = "USES_FORGETTING_CURVE"; +const char *const HeaderPolicy::LAST_UPDATED_TIME_KEY = "date"; +const float HeaderPolicy::DEFAULT_MULTIPLE_WORD_COST_MULTIPLIER = 1.0f; +const float HeaderPolicy::MULTIPLE_WORD_COST_MULTIPLIER_SCALE = 100.0f; + +// Used for logging. Question mark is used to indicate that the key is not found. +void HeaderPolicy::readHeaderValueOrQuestionMark(const char *const key, int *outValue, + int outValueSize) const { + if (outValueSize <= 0) return; + if (outValueSize == 1) { + outValue[0] = '\0'; + return; + } + std::vector<int> keyCodePointVector; + insertCharactersIntoVector(key, &keyCodePointVector); + HeaderReadingUtils::AttributeMap::const_iterator it = mAttributeMap.find(keyCodePointVector); + if (it == mAttributeMap.end()) { + // The key was not found. + outValue[0] = '?'; + outValue[1] = '\0'; + return; + } + const int terminalIndex = min(static_cast<int>(it->second.size()), outValueSize - 1); + for (int i = 0; i < terminalIndex; ++i) { + outValue[i] = it->second[i]; + } + outValue[terminalIndex] = '\0'; +} + +float HeaderPolicy::readMultipleWordCostMultiplier() const { + int attributeValue = 0; + if (getAttributeValueAsInt(MULTIPLE_WORDS_DEMOTION_RATE_KEY, &attributeValue)) { + if (attributeValue <= 0) { + return static_cast<float>(MAX_VALUE_FOR_WEIGHTING); + } + return MULTIPLE_WORD_COST_MULTIPLIER_SCALE / static_cast<float>(attributeValue); + } else { + return DEFAULT_MULTIPLE_WORD_COST_MULTIPLIER; + } +} + +bool HeaderPolicy::readUsesForgettingCurveFlag() const { + int attributeValue = 0; + if (getAttributeValueAsInt(USES_FORGETTING_CURVE_KEY, &attributeValue)) { + return attributeValue != 0; + } else { + return false; + } +} + +// Returns S_INT_MIN when the key is not found or the value is invalid. +int HeaderPolicy::readLastUpdatedTime() const { + int attributeValue = 0; + if (getAttributeValueAsInt(LAST_UPDATED_TIME_KEY, &attributeValue)) { + return attributeValue; + } else { + return S_INT_MIN; + } +} -float HeaderPolicy::readMultiWordCostMultiplier() const { - const int headerValue = HeaderReadingUtils::readHeaderValueInt( - mDictBuf, MULTIPLE_WORDS_DEMOTION_RATE_KEY); - if (headerValue == S_INT_MIN) { - // not found - return DEFAULT_MULTI_WORD_COST_MULTIPLIER; +// Returns whether the key is found or not and stores the found value into outValue. +bool HeaderPolicy::getAttributeValueAsInt(const char *const key, int *const outValue) const { + std::vector<int> keyVector; + insertCharactersIntoVector(key, &keyVector); + HeaderReadingUtils::AttributeMap::const_iterator it = mAttributeMap.find(keyVector); + if (it == mAttributeMap.end()) { + // The key was not found. + return false; } - if (headerValue <= 0) { - return static_cast<float>(MAX_VALUE_FOR_WEIGHTING); + *outValue = parseIntAttributeValue(&(it->second)); + return true; +} + +/* static */ HeaderReadingUtils::AttributeMap HeaderPolicy::createAttributeMapAndReadAllAttributes( + const uint8_t *const dictBuf) { + HeaderReadingUtils::AttributeMap attributeMap; + HeaderReadingUtils::fetchAllHeaderAttributes(dictBuf, &attributeMap); + return attributeMap; +} + +/* static */ int HeaderPolicy::parseIntAttributeValue( + const std::vector<int> *const attributeValue) { + int value = 0; + bool isNegative = false; + for (size_t i = 0; i < attributeValue->size(); ++i) { + if (i == 0 && attributeValue->at(i) == '-') { + isNegative = true; + } else { + if (!isdigit(attributeValue->at(i))) { + // If not a number, return S_INT_MIN + return S_INT_MIN; + } + value *= 10; + value += attributeValue->at(i) - '0'; + } + } + return isNegative ? -value : value; +} + +/* static */ void HeaderPolicy::insertCharactersIntoVector(const char *const characters, + std::vector<int> *const vector) { + for (int i = 0; characters[i]; ++i) { + vector->push_back(characters[i]); } - return MULTI_WORD_COST_MULTIPLIER_SCALE / static_cast<float>(headerValue); } } // namespace latinime diff --git a/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.h b/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.h index e3e6fc077..930b475c7 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.h +++ b/native/jni/src/suggest/policyimpl/dictionary/header/header_policy.h @@ -17,6 +17,7 @@ #ifndef LATINIME_HEADER_POLICY_H #define LATINIME_HEADER_POLICY_H +#include <cctype> #include <stdint.h> #include "defines.h" @@ -30,7 +31,10 @@ class HeaderPolicy : public DictionaryHeaderStructurePolicy { explicit HeaderPolicy(const uint8_t *const dictBuf) : mDictBuf(dictBuf), mDictionaryFlags(HeaderReadingUtils::getFlags(dictBuf)), mSize(HeaderReadingUtils::getHeaderSize(dictBuf)), - mMultiWordCostMultiplier(readMultiWordCostMultiplier()) {} + mAttributeMap(createAttributeMapAndReadAllAttributes(mDictBuf)), + mMultiWordCostMultiplier(readMultipleWordCostMultiplier()), + mUsesForgettingCurve(readUsesForgettingCurveFlag()), + mLastUpdatedTime(readLastUpdatedTime()) {} ~HeaderPolicy() {} @@ -55,34 +59,49 @@ class HeaderPolicy : public DictionaryHeaderStructurePolicy { return mMultiWordCostMultiplier; } - AK_FORCE_INLINE void readHeaderValueOrQuestionMark(const char *const key, - int *outValue, int outValueSize) const { - if (outValueSize <= 0) return; - if (outValueSize == 1) { - outValue[0] = '\0'; - return; - } - if (!HeaderReadingUtils::readHeaderValue(mDictBuf, - key, outValue, outValueSize)) { - outValue[0] = '?'; - outValue[1] = '\0'; - } + AK_FORCE_INLINE bool usesForgettingCurve() const { + return mUsesForgettingCurve; } + AK_FORCE_INLINE int getLastUpdatedTime() const { + return mLastUpdatedTime; + } + + void readHeaderValueOrQuestionMark(const char *const key, + int *outValue, int outValueSize) const; + private: DISALLOW_IMPLICIT_CONSTRUCTORS(HeaderPolicy); static const char *const MULTIPLE_WORDS_DEMOTION_RATE_KEY; - static const float DEFAULT_MULTI_WORD_COST_MULTIPLIER; - static const float MULTI_WORD_COST_MULTIPLIER_SCALE; + static const char *const USES_FORGETTING_CURVE_KEY; + static const char *const LAST_UPDATED_TIME_KEY; + static const float DEFAULT_MULTIPLE_WORD_COST_MULTIPLIER; + static const float MULTIPLE_WORD_COST_MULTIPLIER_SCALE; const uint8_t *const mDictBuf; const HeaderReadingUtils::DictionaryFlags mDictionaryFlags; const int mSize; + HeaderReadingUtils::AttributeMap mAttributeMap; const float mMultiWordCostMultiplier; + const bool mUsesForgettingCurve; + const int mLastUpdatedTime; - float readMultiWordCostMultiplier() const; -}; + float readMultipleWordCostMultiplier() const; + + bool readUsesForgettingCurveFlag() const; + int readLastUpdatedTime() const; + + bool getAttributeValueAsInt(const char *const key, int *const outValue) const; + + static HeaderReadingUtils::AttributeMap createAttributeMapAndReadAllAttributes( + const uint8_t *const dictBuf); + + static int parseIntAttributeValue(const std::vector<int> *const attributeValue); + + static void insertCharactersIntoVector( + const char *const characters, std::vector<int> *const vector); +}; } // namespace latinime #endif /* LATINIME_HEADER_POLICY_H */ diff --git a/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.cpp b/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.cpp index f323876c4..186c043c1 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.cpp +++ b/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.cpp @@ -16,23 +16,22 @@ #include "suggest/policyimpl/dictionary/header/header_reading_utils.h" -#include <cctype> -#include <cstdlib> +#include <vector> #include "defines.h" #include "suggest/policyimpl/dictionary/utils/byte_array_utils.h" namespace latinime { -const int HeaderReadingUtils::MAX_OPTION_KEY_LENGTH = 256; +const int HeaderReadingUtils::MAX_ATTRIBUTE_KEY_LENGTH = 256; +const int HeaderReadingUtils::MAX_ATTRIBUTE_VALUE_LENGTH = 256; const int HeaderReadingUtils::HEADER_MAGIC_NUMBER_SIZE = 4; const int HeaderReadingUtils::HEADER_DICTIONARY_VERSION_SIZE = 2; const int HeaderReadingUtils::HEADER_FLAG_SIZE = 2; const int HeaderReadingUtils::HEADER_SIZE_FIELD_SIZE = 4; -const HeaderReadingUtils::DictionaryFlags - HeaderReadingUtils::NO_FLAGS = 0; +const HeaderReadingUtils::DictionaryFlags HeaderReadingUtils::NO_FLAGS = 0; // Flags for special processing // Those *must* match the flags in makedict (FormatSpec#*_PROCESSING_FLAG) or // something very bad (like, the apocalypse) will happen. Please update both at the same time. @@ -56,53 +55,27 @@ const HeaderReadingUtils::DictionaryFlags HEADER_MAGIC_NUMBER_SIZE + HEADER_DICTIONARY_VERSION_SIZE); } -// Returns if the key is found or not and reads the found value into outValue. -/* static */ bool HeaderReadingUtils::readHeaderValue(const uint8_t *const dictBuf, - const char *const key, int *outValue, const int outValueSize) { - if (outValueSize <= 0) { - return false; - } +/* static */ void HeaderReadingUtils::fetchAllHeaderAttributes(const uint8_t *const dictBuf, + AttributeMap *const headerAttributes) { const int headerSize = getHeaderSize(dictBuf); int pos = getHeaderOptionsPosition(); if (pos == NOT_A_DICT_POS) { // The header doesn't have header options. - return false; + return; } + int keyBuffer[MAX_ATTRIBUTE_KEY_LENGTH]; + int valueBuffer[MAX_ATTRIBUTE_VALUE_LENGTH]; while (pos < headerSize) { - if(ByteArrayUtils::compareStringInBufferWithCharArray( - dictBuf, key, headerSize - pos, &pos) == 0) { - // The key was found. - const int length = ByteArrayUtils::readStringAndAdvancePosition(dictBuf, outValueSize, - outValue, &pos); - // Add a 0 terminator to the string. - outValue[length < outValueSize ? length : outValueSize - 1] = '\0'; - return true; - } - ByteArrayUtils::advancePositionToBehindString(dictBuf, headerSize - pos, &pos); - } - // The key was not found. - return false; -} - -/* static */ int HeaderReadingUtils::readHeaderValueInt( - const uint8_t *const dictBuf, const char *const key) { - const int bufferSize = LARGEST_INT_DIGIT_COUNT; - int intBuffer[bufferSize]; - char charBuffer[bufferSize]; - if (!readHeaderValue(dictBuf, key, intBuffer, bufferSize)) { - return S_INT_MIN; - } - for (int i = 0; i < bufferSize; ++i) { - charBuffer[i] = intBuffer[i]; - if (charBuffer[i] == '0') { - break; - } - if (!isdigit(charBuffer[i])) { - // If not a number, return S_INT_MIN - return S_INT_MIN; - } + const int keyLength = ByteArrayUtils::readStringAndAdvancePosition(dictBuf, + MAX_ATTRIBUTE_KEY_LENGTH, keyBuffer, &pos); + std::vector<int> key; + key.insert(key.end(), keyBuffer, keyBuffer + keyLength); + const int valueLength = ByteArrayUtils::readStringAndAdvancePosition(dictBuf, + MAX_ATTRIBUTE_VALUE_LENGTH, valueBuffer, &pos); + std::vector<int> value; + value.insert(value.end(), valueBuffer, valueBuffer + valueLength); + headerAttributes->insert(AttributeMap::value_type(key, value)); } - return atoi(charBuffer); } } // namespace latinime diff --git a/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.h b/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.h index c94919640..5716198fb 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.h +++ b/native/jni/src/suggest/policyimpl/dictionary/header/header_reading_utils.h @@ -17,7 +17,9 @@ #ifndef LATINIME_HEADER_READING_UTILS_H #define LATINIME_HEADER_READING_UTILS_H +#include <map> #include <stdint.h> +#include <vector> #include "defines.h" @@ -26,8 +28,7 @@ namespace latinime { class HeaderReadingUtils { public: typedef uint16_t DictionaryFlags; - - static const int MAX_OPTION_KEY_LENGTH; + typedef std::map<std::vector<int>, std::vector<int> > AttributeMap; static int getHeaderSize(const uint8_t *const dictBuf); @@ -50,14 +51,15 @@ class HeaderReadingUtils { + HEADER_SIZE_FIELD_SIZE; } - static bool readHeaderValue(const uint8_t *const dictBuf, - const char *const key, int *outValue, const int outValueSize); - - static int readHeaderValueInt(const uint8_t *const dictBuf, const char *const key); + static void fetchAllHeaderAttributes(const uint8_t *const dictBuf, + AttributeMap *const headerAttributes); private: DISALLOW_IMPLICIT_CONSTRUCTORS(HeaderReadingUtils); + static const int MAX_ATTRIBUTE_KEY_LENGTH; + static const int MAX_ATTRIBUTE_VALUE_LENGTH; + static const int HEADER_MAGIC_NUMBER_SIZE; static const int HEADER_DICTIONARY_VERSION_SIZE; static const int HEADER_FLAG_SIZE; diff --git a/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.cpp b/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.cpp index 8582c4b81..6326754c2 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.cpp +++ b/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.cpp @@ -22,4 +22,70 @@ const size_t BufferWithExtendableBuffer::INITIAL_ADDITIONAL_BUFFER_SIZE = 16 * 1 const size_t BufferWithExtendableBuffer::MAX_ADDITIONAL_BUFFER_SIZE = 1024 * 1024; const size_t BufferWithExtendableBuffer::EXTEND_ADDITIONAL_BUFFER_SIZE_STEP = 16 * 1024; +bool BufferWithExtendableBuffer::writeUintAndAdvancePosition(const uint32_t data, const int size, + int *const pos) { + if (!(size >= 1 && size <= 4)) { + AKLOGI("writeUintAndAdvancePosition() is called with invalid size: %d", size); + ASSERT(false); + return false; + } + if (!checkAndPrepareWriting(*pos, size)) { + return false; + } + const bool usesAdditionalBuffer = isInAdditionalBuffer(*pos); + uint8_t *const buffer = usesAdditionalBuffer ? &mAdditionalBuffer[0] : mOriginalBuffer; + if (usesAdditionalBuffer) { + *pos -= mOriginalBufferSize; + } + ByteArrayUtils::writeUintAndAdvancePosition(buffer, data, size, pos); + if (usesAdditionalBuffer) { + *pos += mOriginalBufferSize; + } + return true; +} + +bool BufferWithExtendableBuffer::writeCodePointsAndAdvancePosition(const int *const codePoints, + const int codePointCount, const bool writesTerminator ,int *const pos) { + const size_t size = ByteArrayUtils::calculateRequiredByteCountToStoreCodePoints( + codePoints, codePointCount, writesTerminator); + if (!checkAndPrepareWriting(*pos, size)) { + return false; + } + const bool usesAdditionalBuffer = isInAdditionalBuffer(*pos); + uint8_t *const buffer = usesAdditionalBuffer ? &mAdditionalBuffer[0] : mOriginalBuffer; + if (usesAdditionalBuffer) { + *pos -= mOriginalBufferSize; + } + ByteArrayUtils::writeCodePointsAndAdvancePosition(buffer, codePoints, codePointCount, + writesTerminator, pos); + if (usesAdditionalBuffer) { + *pos += mOriginalBufferSize; + } + return true; +} + +bool BufferWithExtendableBuffer::checkAndPrepareWriting(const int pos, const int size) { + if (isInAdditionalBuffer(pos)) { + if (pos == mUsedAdditionalBufferSize) { + // Append data to the tail. + if (pos + size > static_cast<int>(mAdditionalBuffer.size())) { + // Need to extend buffer. + if (!extendBuffer()) { + return false; + } + } + mUsedAdditionalBufferSize += size; + } else if (pos + size >= mUsedAdditionalBufferSize) { + // The access will beyond the tail of used region. + return false; + } + } else { + if (pos < 0 || mOriginalBufferSize < pos + size) { + // Invalid position or violate the boundary. + return false; + } + } + return true; +} + } diff --git a/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.h b/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.h index ec871ec85..b35b47d7a 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.h +++ b/native/jni/src/suggest/policyimpl/dictionary/utils/buffer_with_extendable_buffer.h @@ -66,27 +66,10 @@ class BufferWithExtendableBuffer { * Writing is allowed for original buffer, already written region of additional buffer and the * tail of additional buffer. */ - AK_FORCE_INLINE bool writeUintAndAdvancePosition(const uint32_t data, const int size, - int *const pos) { - if (!(size >= 1 && size <= 4)) { - AKLOGI("writeUintAndAdvancePosition() is called with invalid size: %d", size); - ASSERT(false); - return false; - } - if (!checkAndPrepareWriting(*pos, size)) { - return false; - } - const bool usesAdditionalBuffer = isInAdditionalBuffer(*pos); - uint8_t *const buffer = usesAdditionalBuffer ? &mAdditionalBuffer[0] : mOriginalBuffer; - if (usesAdditionalBuffer) { - *pos -= mOriginalBufferSize; - } - ByteArrayUtils::writeUintAndAdvancePosition(buffer, data, size, pos); - if (usesAdditionalBuffer) { - *pos += mOriginalBufferSize; - } - return true; - } + bool writeUintAndAdvancePosition(const uint32_t data, const int size, int *const pos); + + bool writeCodePointsAndAdvancePosition(const int *const codePoints, const int codePointCount, + const bool writesTerminator, int *const pos); private: DISALLOW_COPY_AND_ASSIGN(BufferWithExtendableBuffer); @@ -112,29 +95,7 @@ class BufferWithExtendableBuffer { // Returns if it is possible to write size-bytes from pos. When pos is at the tail position of // the additional buffer, try extending the buffer. - AK_FORCE_INLINE bool checkAndPrepareWriting(const int pos, const int size) { - if (isInAdditionalBuffer(pos)) { - if (pos == mUsedAdditionalBufferSize) { - // Append data to the tail. - if (pos + size > static_cast<int>(mAdditionalBuffer.size())) { - // Need to extend buffer. - if (!extendBuffer()) { - return false; - } - } - mUsedAdditionalBufferSize += size; - } else if (pos + size >= mUsedAdditionalBufferSize) { - // The access will beyond the tail of used region. - return false; - } - } else { - if (pos < 0 || mOriginalBufferSize < pos + size) { - // Invalid position or violate the boundary. - return false; - } - } - return true; - } + AK_FORCE_INLINE bool checkAndPrepareWriting(const int pos, const int size); }; } #endif /* LATINIME_BUFFER_WITH_EXTENDABLE_BUFFER_H */ diff --git a/native/jni/src/suggest/policyimpl/dictionary/utils/byte_array_utils.h b/native/jni/src/suggest/policyimpl/dictionary/utils/byte_array_utils.h index 1d14929c7..f727ecf8e 100644 --- a/native/jni/src/suggest/policyimpl/dictionary/utils/byte_array_utils.h +++ b/native/jni/src/suggest/policyimpl/dictionary/utils/byte_array_utils.h @@ -115,7 +115,7 @@ class ByteArrayUtils { } /** - * Code Point + * Code Point Reading * * 1 byte = bbbbbbbb match * case 000xxxxx: xxxxx << 16 + next byte << 8 + next byte @@ -149,7 +149,7 @@ class ByteArrayUtils { } /** - * String (array of code points) + * String (array of code points) Reading * * Reads code points until the terminator is found. */ @@ -176,37 +176,49 @@ class ByteArrayUtils { return length; } - // Returns an integer less than, equal to, or greater than zero when string starting from pos - // in buffer is less than, match, or is greater than charArray. - static AK_FORCE_INLINE int compareStringInBufferWithCharArray(const uint8_t *const buffer, - const char *const charArray, const int maxLength, int *const pos) { - int index = 0; - int codePoint = readCodePointAndAdvancePosition(buffer, pos); - const uint8_t *const uint8CharArrayForComparison = - reinterpret_cast<const uint8_t *>(charArray); - while (NOT_A_CODE_POINT != codePoint - && '\0' != uint8CharArrayForComparison[index] && index < maxLength) { - if (codePoint != uint8CharArrayForComparison[index]) { - // Different character is found. - // Skip the rest of the string in the buffer. - advancePositionToBehindString(buffer, maxLength - index, pos); - return codePoint - uint8CharArrayForComparison[index]; + /** + * String (array of code points) Writing + */ + static void writeCodePointsAndAdvancePosition(uint8_t *const buffer, + const int *const codePoints, const int codePointCount, const bool writesTerminator, + int *const pos) { + for (int i = 0; i < codePointCount; ++i) { + const int codePoint = codePoints[i]; + if (codePoint == NOT_A_CODE_POINT || codePoint == CHARACTER_ARRAY_TERMINATOR) { + break; + } else if (codePoint < MINIMAL_ONE_BYTE_CHARACTER_VALUE) { + // three bytes character. + writeUint24AndAdvancePosition(buffer, codePoint, pos); + } else { + // one byte character. + writeUint8AndAdvancePosition(buffer, codePoint, pos); } - // Advance - codePoint = readCodePointAndAdvancePosition(buffer, pos); - ++index; } - if (NOT_A_CODE_POINT != codePoint && index < maxLength) { - // Skip the rest of the string in the buffer. - advancePositionToBehindString(buffer, maxLength - index, pos); + if (writesTerminator) { + writeUint8AndAdvancePosition(buffer, CHARACTER_ARRAY_TERMINATOR, pos); } - if (NOT_A_CODE_POINT == codePoint && '\0' == uint8CharArrayForComparison[index]) { - // When both of the last characters are terminals, we consider the string in the buffer - // matches the given char array - return 0; - } else { - return codePoint - uint8CharArrayForComparison[index]; + } + + static int calculateRequiredByteCountToStoreCodePoints(const int *const codePoints, + const int codePointCount, const bool writesTerminator) { + int byteCount = 0; + for (int i = 0; i < codePointCount; ++i) { + const int codePoint = codePoints[i]; + if (codePoint == NOT_A_CODE_POINT || codePoint == CHARACTER_ARRAY_TERMINATOR) { + break; + } else if (codePoint < MINIMAL_ONE_BYTE_CHARACTER_VALUE) { + // three bytes character. + byteCount += 3; + } else { + // one byte character. + byteCount += 1; + } + } + if (writesTerminator) { + // The terminator is one byte. + byteCount += 1; } + return byteCount; } private: |