Home | History | Annotate | Download | only in utils
      1 /*
      2  * Copyright (C) 2013 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of 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,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include "suggest/policyimpl/dictionary/utils/format_utils.h"
     18 
     19 #include "suggest/policyimpl/dictionary/utils/byte_array_utils.h"
     20 
     21 namespace latinime {
     22 
     23 const uint32_t FormatUtils::MAGIC_NUMBER = 0x9BC13AFE;
     24 
     25 // Magic number (4 bytes), version (2 bytes), flags (2 bytes), header size (4 bytes) = 12
     26 const int FormatUtils::DICTIONARY_MINIMUM_SIZE = 12;
     27 
     28 /* static */ FormatUtils::FORMAT_VERSION FormatUtils::detectFormatVersion(
     29         const uint8_t *const dict, const int dictSize) {
     30     // The magic number is stored big-endian.
     31     // If the dictionary is less than 4 bytes, we can't even read the magic number, so we don't
     32     // understand this format.
     33     if (dictSize < DICTIONARY_MINIMUM_SIZE) {
     34         return UNKNOWN_VERSION;
     35     }
     36     const uint32_t magicNumber = ByteArrayUtils::readUint32(dict, 0);
     37     switch (magicNumber) {
     38         case MAGIC_NUMBER:
     39             // Version 2 header is as follows:
     40             // Magic number (4 bytes) 0x9B 0xC1 0x3A 0xFE
     41             // Dictionary format version number (2 bytes)
     42             // Options (2 bytes)
     43             // Header size (4 bytes) : integer, big endian
     44             if (ByteArrayUtils::readUint16(dict, 4) == 2) {
     45                 return VERSION_2;
     46             } else if (ByteArrayUtils::readUint16(dict, 4) == 3) {
     47                 return VERSION_3;
     48             } else {
     49                 return UNKNOWN_VERSION;
     50             }
     51         default:
     52             return UNKNOWN_VERSION;
     53     }
     54 }
     55 
     56 } // namespace latinime
     57