aapt字符串池

背景

Android資源對字符串的索引使用字符串池, 爲什麼要建立字符串索引呢? 目的有兩個:

  1. 壓縮空間
  2. 加快查找速度

        怎麼壓縮空間呢?對於Android資源的字符串索引其實就是將重複的字符串合併。
        怎麼理解加快查找速度呢? 首先Android開發者不會將所有的字符串都硬編碼到代碼裏, 將字符串硬編碼在代碼裏,一方面不適合國際化, 另一方面代碼體積會增大。 所以需要進行簡化。 Android提供的方式是通過資源id去查找字符串. 在查過程的底層,對應的字符串id會被轉換成一個索引值,其實就是一個數字, 可以通過這這數字找到字符串。怎樣使這個查找過程更快呢,這就是索引的目的,加快查找速度。

        所以Android使用StringPool來索引的字符串。 對於Android索引的字符串又分爲兩類, 普通字符串和帶樣式的字符串。什麼叫帶樣式的字符串的,舉個例子

你好<b>郭德綱<b/>你喜歡<i>聽相聲嗎?<i/>

        這就是一個樣式字符串, 被b標籤和i標籤包裹起來的地方叫作span, 當TextView對字符串渲染的時候會對b包裹的部分加粗, 對i標籤包裹起來的部分則會被渲染爲斜體.

        其實樣式字符串也是字符串,爲什麼要區分樣式字符串和普通字符串呢, 這不過是爲了更好的壓縮. 比如有三個字符串,分別是

  1. 你好郭德綱你喜歡聽相聲嗎?
  2. 你好<b>郭德綱<b/>你喜歡<i>聽相聲嗎?<i/>
  3. 哈哈哈<b>123<\b>

        如果不加以區分,這就是三個字符串. 將樣式信息提取出來, 字符串1和2 其實是一樣的,所以就可以進行合併. 提取樣式信息如下

	str = 你好郭德綱你喜歡聽相聲嗎?
	span1.name = b
	span1.firstChar = 2
	span1.lastChar = 4
	
	span2.name = i
	span2.firtChar = 5
	span2.lastChar = 7

這樣來描述字符串2 , 將span信息和原始字符串分離開,就可以對1,2 兩個字符串進行合併存儲,以減少了存儲空間。但是這種情況並不多見, 其實這又引出另外一個原因, 對於2,3 兩個字符串都使用了b標籤。 在真實情況下,可能還有更多字符串使用了b標籤. 所以如果能對多個b標籤進行合併,不是更好嗎? 怎麼合併呢, 其實標籤也是一個字符串, 所以也將標籤和普通字符串一視同仁,將標籤的名字進行索引就達到了對樣式標籤內容進行合併的目的。
 
 

索引文件格式

        介紹了背景,我們具體來看下StringPool 索引後的文件格式
字符串索引結構
        字符串池最終生成的索引文件主要包括5部分, 分別是頭部區域,字符串索引區域, 樣式索引區域,字符串內容區域, 樣式內容區域.。對於字符串頭部區域主要描述了字符串池的整體結構.。字符串內容區域存儲的就是去重後的字符串內容。樣式區域存儲的是字符串的樣式信息。 字符串索引區域存儲的是32位整數偏移值,使用這個值就能在字符串內容區域中找到具體的字符串。樣式索引區域也是存儲的32位整數偏移值,使用這個值就能在樣式內容區域中找到具體的樣式信息。

下面介紹字符串池索引文件各個區域的詳細信息

 

1 頭部

首先第一部分是頭部信息,數據結構爲ResStringPool_header, 代碼定義如下

struct ResChunk_header
{
    // Type identifier for this chunk.  The meaning of this value depends
    // on the containing chunk.
    uint16_t type;

    // Size of the chunk header (in bytes).  Adding this value to
    // the address of the chunk allows you to find its associated data
    // (if any).
    uint16_t headerSize;

    // Total size of this chunk (in bytes).  This is the chunkSize plus
    // the size of any data associated with the chunk.  Adding this value
    // to the chunk allows you to completely skip its contents (including
    // any child chunks).  If this value is the same as chunkSize, there is
    // no data associated with the chunk.
    uint32_t size;
};

truct ResStringPool_header
{
    struct ResChunk_header header;

    // Number of strings in this pool (number of uint32_t indices that follow
    // in the data).
    uint32_t stringCount;

    // Number of style span arrays in the pool (number of uint32_t indices
    // follow the string indices).
    uint32_t styleCount;

    // Flags.
    enum {
        // If set, the string index is sorted by the string values (based
        // on strcmp16()).
        SORTED_FLAG = 1<<0,

        // String pool is encoded in UTF-8
        UTF8_FLAG = 1<<8
    };
    uint32_t flags;

    // Index from header of the string data.
    uint32_t stringsStart;

    // Index from header of the style data.
    uint32_t stylesStart;
};

首先ResStringPool_header的第一部分是ResChunk_header:

  • type 爲 0x0001 代表字符串池。
  • headerSize 大小爲sizeof(ResStringPool_header), 用於跳過字符串池頭,找到後面的數據。
  • size 表示整個字符池大小(包括header部分)。

下面是ResStringPool_header自己擴展的字段。

  • stringCount: 表示有多少個字符串索引。
  • styleCount: 表示有多少個樣式索引, 注意這個值和 stringCount是相等的,後面我會說明爲什麼。
  • flags
  • stringsStart: 字符串內容的偏移,從header結尾開始計算的偏移, 指向圖中字符串內容區域。
  • stylesStart :樣式內容的偏移, 從header結尾開始計算的偏移, 指向圖中樣式內容區域。

 

2 字符串索引區

        在頭部下面緊接着的部分是字符串索引區域, 這裏面每一項是一個4字節的整數,爲一個偏移值,這個值其實就是相對於 header裏面的stringsStart指向的字符串內容區域的偏移,用於指向真正字符串所在的位置。我們在Android編程中通過字符串id找到的字符串索引值其實就是字符串索引區域的偏移, 比如我們的索引值是2,則表示字符串索引區域的第二項,這裏存儲的內容是一個偏移值,使用這個偏移值就能在字符串內容區域找到對應的字符串。

 

3 樣式索引區

        緊跟在字符串索引區後面的部分是字符串樣式索引區。這個區域裏面的每一項也是4字節整數,爲一個偏移值, 這個值其實是相對於header裏面的styleStart指向的樣式內容區域的偏移, 指向字符串的樣式信息。 和字符串索引區一樣, Android編程中通過字符串id找到的字符串索引值, 該值不但是字符串索引區域的偏移, 同樣也是樣式字索引區的偏移, 這樣樣式信息就和字符串信息關聯了起.。通過這個索引值不但能找到字符串的信息,還能找到樣式信息。 所以這裏有一個隱含信息: 字符串索引區和樣式索引區的項數是一樣的, 對於沒有樣式信息的字符串,指向一個特殊的樣式項。

 

4 字符串內容區

        這部分存放的就是真正的字符串內容, 無論是UTF8,還是UTF16的字符串編碼,每一個字符串的前面都有2個字節表示其長度,而且後面以一個NULL字符結束。對於UTF8編碼的字符串來說,NULL字符使用一個字節的0x00來表示,而對於UTF16編碼的字符串來說,NULL字符使用兩個字節的0x0000來表示。
如果一個字符串的長度超過32767,那麼就會使用更多的字節來表示。假設字符串的長度超過32767,那麼前兩個字節的最高位就會等於0,表示接下來的兩個字節仍然是用來表示字符串長度的,並且前兩個字表示高16位,而後兩個字節表示低16位。

5 樣式內容區

        對於樣式信息,我們前邊已經舉了一個例子

   str = 你好郭德綱你喜歡聽相聲嗎?
   span1.name = b
   span1.firstChar = 2
   span1.lastChar = 4
   
   span2.name = i
   span2.firtChar = 5
   span2.lastChar = 7

        對於字符串 你好<b>郭德綱<b/>你喜歡<i>聽相聲嗎?<i/> 抽取出兩個span, 對於span.name已經進行了字符串索引, 所以在樣式內容區只需要保存span.name的索引值就可以了(也就是所在字符串索引區的偏移)。另外對於一個字符串存在多個span的情況, 在一個字符串多個span信息結尾處寫入0x00000000 表示結尾一個字符串的樣式結束。 對於沒有樣式信息的字符串,樣式索引區的對應內容就是0x00000000。

 
 

代碼分析

        先來看看StringPool類的數據結構

/**
 * The StringPool class is used as an intermediate representation for
 * generating the string pool resource data structure that can be parsed with
 * ResStringPool in include/utils/ResourceTypes.h.
 */
class StringPool
{
public:
    struct entry {  //表示一個字符串項
        String16 value;  //字符串的值
        size_t offset; // 偏移值,寫字符串池的時候確定在字符串內容區的位置後生成
        bool hasStyles; //是否有樣式信息
        Vector<size_t> indices; //索引值(樣式字符串和普通字符串對應同一個字符串的情況需要多個索引值,用於找到對應的字符串樣式)
    };

    struct entry_style_span { // span
        String16 name;  //樣式的名字
        ResStringPool_span span; // 樣式的內容(其實就是firstchar,lastchar 以及span.name的偏移)
    };

    struct entry_style { // 樣式項
        size_t offset; // 樣式內容區的偏移
        Vector<entry_style_span> spans; //包含多個span
    };
    //添加新的字符串
    ssize_t add(const String16& value, bool mergeDuplicates = false,
            const String8* configTypeName = NULL, const ResTable_config* config = NULL);
    //添加新的樣式字符串
    ssize_t add(const String16& value, const Vector<entry_style_span>& spans,
            const String8* configTypeName = NULL, const ResTable_config* config = NULL);
    // 添加span
    status_t addStyleSpan(size_t idx, const String16& name,
                          uint32_t start, uint32_t end);
    // 添加多個span
    status_t addStyleSpans(size_t idx, const Vector<entry_style_span>& spans);
     // 添加多個span
    status_t addStyleSpan(size_t idx, const entry_style_span& span);
 
    // 寫索引
    status_t writeStringBlock(const sp<AaptFile>& pool);
private:

    //是否使用utf8編碼存儲字符串
    const bool                              mUTF8;

    // The following data structures represent the actual structures
    // that will be generated for the final string pool.

    // Raw array of unique strings, in some arbitrary order.  This is the
    // actual strings that appear in the final string pool, in the order
    // that they will be written.
    // 字符串內容項
    Vector<entry>                           mEntries;
    // Array of indices into mEntries, in the order they were
    // added to the pool.  This can be different than mEntries
    // if the same string was added multiple times (it will appear
    // once in mEntries, with multiple occurrences in this array).
    // This is the lookup array that will be written for finding
    // the string for each offset/position in the string pool.
    // 字符串索引值(用於生成字符串索引區)
    Vector<size_t>                          mEntryArray;
    // Optional style span information associated with each index of
    // mEntryArray.
    // 字符串樣式索引值(用於生成仰視索引區)
    Vector<entry_style>                     mEntryStyleArray;

    // The following data structures are used for book-keeping as the
    // string pool is constructed.

    // Unique set of all the strings added to the pool, mapped to
    // the first index of mEntryArray where the value was added.
    // 用於存儲字符串和第一次添加的位置
    DefaultKeyedVector<String16, ssize_t>   mValues;
};

        對於數據結構都通過註釋標註在代碼中了, 這裏對數據結構的設計再補充說明一下。
        struct entry 數據結構中有個vector類型的indices變量, 這個變量描述了字符串對應的索引值。爲什麼一個字符串會有多個索引值(就是字符串索引在字符串索引區的偏移)呢? 前面我們說過, 字符串池通過保證樣式索引項和字符串索引索引值數相同來關聯字符串和樣式信息。 也就是一個索引值同時是字符串索引區的偏移和樣式索引區的偏移。所以對於不同樣式且有相同內容的字符串, 需要有多個索引,以找到不同的樣式。 舉個例子:

 1. 你好郭德綱你喜歡聽相聲嗎?
 2. 你好\<b>郭德綱\<b/>你喜歡\<i>聽相聲嗎?\<i/>
 3. 你好\<i>郭德綱\<i/>你喜歡\<b>聽相聲嗎?\<b/>

對於上面三個字符串, 字符串內容區(mEntries)對應同一項(你好郭德綱你喜歡聽相聲嗎?), 但是卻有三種樣式(分別爲是無樣式, b和i樣式, 以及i和b樣式)。 所以呢對於這個字符串就應該存在三個索引值, 這也就是indices變量爲什麼是集合類型的原因了。

        理解了這一點,對於字符串池的其他成員變量也就好理解了。 mEntries 存儲字符串項(去重後的), mEntryArray用於存儲字符串索引對應的字符串在mEntries集合中的偏移。 比如上面的例子中, mEntries只有一個元素,mEntries[0] = “你好郭德綱你喜歡聽相聲嗎?” , 而mEntryArray存儲爲mEntryArray[0]=0, mEntryArray[1] = 0, mEntryArray[2] = 0. 看明白了嗎?
mEntryStyleArray[0] = 0, mEntryStyleArray[1] = “span , span” , mEntryStyleArray[2] = “span , span

        mEntryArray的集合的索引其實就是最終的索引值。

        StringPool 還有兩個比較關鍵的函數, 分別是add函數,用於添加字符串, writeStringBlock用於最終寫出索引數據。我們先來看下add函數:

//添加樣式字符串
ssize_t StringPool::add(const String16& value, const Vector<entry_style_span>& spans,
        const String8* configTypeName, const ResTable_config* config)
{
    // 先添加字符串, 對於樣式字符串第二個參數爲false,表示不合並相同字符串,返回值就是索引值
    ssize_t res = add(value, false, configTypeName, config);  
    if (res >= 0) {
        addStyleSpans(res, spans); //再添加樣式
    }
    return res;
}

ssize_t StringPool::add(const String16& value,
        bool mergeDuplicates, const String8* configTypeName, const ResTable_config* config)
{
    ssize_t vidx = mValues.indexOfKey(value);
    ssize_t pos = vidx >= 0 ? mValues.valueAt(vidx) : -1;
    ssize_t eidx = pos >= 0 ? mEntryArray.itemAt(pos) : -1;
    if (eidx < 0) { // 如果mEntries中沒有出現過該字符串,則添加到mEntries中
        eidx = mEntries.add(entry(value));
        if (eidx < 0) {
            fprintf(stderr, "Failure adding string %s\n", String8(value).string());
            return eidx;
        }
    }

    if (configTypeName != NULL) {
        entry& ent = mEntries.editItemAt(eidx);
        if (kIsDebug) {
            printf("*** adding config type name %s, was %s\n",
                    configTypeName->string(), ent.configTypeName.string());
        }
        if (ent.configTypeName.size() <= 0) {
            ent.configTypeName = *configTypeName;
        } else if (ent.configTypeName != *configTypeName) {
            ent.configTypeName = " ";
        }
    }

    if (config != NULL) {
        // Add this to the set of configs associated with the string.
        entry& ent = mEntries.editItemAt(eidx);
        size_t addPos;
        for (addPos=0; addPos<ent.configs.size(); addPos++) {
            int cmp = ent.configs.itemAt(addPos).compareLogical(*config);
            if (cmp >= 0) {
                if (cmp > 0) {
                    if (kIsDebug) {
                        printf("*** inserting config: %s\n", config->toString().string());
                    }
                    ent.configs.insertAt(*config, addPos);
                }
                break;
            }
        }
        if (addPos >= ent.configs.size()) {
            if (kIsDebug) {
                printf("*** adding config: %s\n", config->toString().string());
            }
            ent.configs.add(*config);
        }
    }

    const bool first = vidx < 0;
    const bool styled = (pos >= 0 && (size_t)pos < mEntryStyleArray.size()) ?
        mEntryStyleArray[pos].spans.size() : 0;
    if (first || styled || !mergeDuplicates) { //對於樣式字符串或者第一次添加該字符串,或者不需要合併的情況下,未該字符串添加一個索引
        pos = mEntryArray.add(eidx);
        if (first) {
            vidx = mValues.add(value, pos);
        }
        entry& ent = mEntries.editItemAt(eidx);
        ent.indices.add(pos); // 寫入字符串項的索引值
    }

    if (kIsDebug) {
        printf("Adding string %s to pool: pos=%zd eidx=%zd vidx=%zd\n",
                String8(value).string(), SSIZE(pos), SSIZE(eidx), SSIZE(vidx));
    }

    return pos;
}

status_t StringPool::addStyleSpan(size_t idx, const entry_style_span& span)
{
    // Place blank entries in the span array up to this index.
    while (mEntryStyleArray.size() <= idx) {
        mEntryStyleArray.add();
    }

    entry_style& style = mEntryStyleArray.editItemAt(idx);
    style.spans.add(span);
    mEntries.editItemAt(mEntryArray[idx]).hasStyles = true;
    return NO_ERROR;
}

        add函數比較簡單, 對它的解釋,通過註釋的方式寫在了代碼中。另外addStyleSpans 函數首先會對小於參數索引值的位置填充0, 也就是對於那些沒有樣式的字符串樣式索引項寫0。

        下面在來看下writeStringBlock函數

status_t StringPool::writeStringBlock(const sp<AaptFile>& pool)
{
    // Allow appending.  Sorry this is a little wacky.
    if (pool->getSize() > 0) {
        sp<AaptFile> block = createStringBlock();
        if (block == NULL) {
            return UNKNOWN_ERROR;
        }
        ssize_t res = pool->writeData(block->getData(), block->getSize());
        return (res >= 0) ? (status_t)NO_ERROR : res;
    }

    // First we need to add all style span names to the string pool.
    // We do this now (instead of when the span is added) so that these
    // will appear at the end of the pool, not disrupting the order
    // our client placed their own strings in it.
    
    const size_t STYLES = mEntryStyleArray.size();
    size_t i;

    for (i=0; i<STYLES; i++) { //對樣式信息span.name進行索引
        entry_style& style = mEntryStyleArray.editItemAt(i);
        const size_t N = style.spans.size();
        for (size_t i=0; i<N; i++) {
            entry_style_span& span = style.spans.editItemAt(i);
            ssize_t idx = add(span.name, true);
            if (idx < 0) {
                fprintf(stderr, "Error adding span for style tag '%s'\n",
                        String8(span.name).string());
                return idx;
            }
            span.span.name.index = (uint32_t)idx;
        }
    }

    const size_t ENTRIES = mEntryArray.size();

    // Now build the pool of unique strings.

    const size_t STRINGS = mEntries.size();
    const size_t preSize = sizeof(ResStringPool_header)
                         + (sizeof(uint32_t)*ENTRIES)
                         + (sizeof(uint32_t)*STYLES);
    if (pool->editData(preSize) == NULL) {
        fprintf(stderr, "ERROR: Out of memory for string pool\n");
        return NO_MEMORY;
    }

    const size_t charSize = mUTF8 ? sizeof(uint8_t) : sizeof(uint16_t);

    size_t strPos = 0;
    for (i=0; i<STRINGS; i++) { // 寫字符串內容區
        entry& ent = mEntries.editItemAt(i);
        const size_t strSize = (ent.value.size());
        const size_t lenSize = strSize > (size_t)(1<<((charSize*8)-1))-1 ?
            charSize*2 : charSize;

        String8 encStr;
        if (mUTF8) {
            encStr = String8(ent.value);
        }

        const size_t encSize = mUTF8 ? encStr.size() : 0;
        const size_t encLenSize = mUTF8 ?
            (encSize > (size_t)(1<<((charSize*8)-1))-1 ?
                charSize*2 : charSize) : 0;

        ent.offset = strPos;

        const size_t totalSize = lenSize + encLenSize +
            ((mUTF8 ? encSize : strSize)+1)*charSize;

        void* dat = (void*)pool->editData(preSize + strPos + totalSize);
        if (dat == NULL) {
            fprintf(stderr, "ERROR: Out of memory for string pool\n");
            return NO_MEMORY;
        }
        dat = (uint8_t*)dat + preSize + strPos;
        if (mUTF8) {
            uint8_t* strings = (uint8_t*)dat;

            ENCODE_LENGTH(strings, sizeof(uint8_t), strSize)

            ENCODE_LENGTH(strings, sizeof(uint8_t), encSize)

            strncpy((char*)strings, encStr, encSize+1);
        } else {
            char16_t* strings = (char16_t*)dat;

            ENCODE_LENGTH(strings, sizeof(char16_t), strSize)

            strcpy16_htod(strings, ent.value);
        }

        strPos += totalSize;
    }

    // Pad ending string position up to a uint32_t boundary.

    if (strPos&0x3) { // 4字節對齊
        size_t padPos = ((strPos+3)&~0x3);
        uint8_t* dat = (uint8_t*)pool->editData(preSize + padPos);
        if (dat == NULL) {
            fprintf(stderr, "ERROR: Out of memory padding string pool\n");
            return NO_MEMORY;
        }
        memset(dat+preSize+strPos, 0, padPos-strPos);
        strPos = padPos;
    }

    // Build the pool of style spans.

    size_t styPos = strPos;
    for (i=0; i<STYLES; i++) { // 寫樣式內容區
        entry_style& ent = mEntryStyleArray.editItemAt(i);
        const size_t N = ent.spans.size();
        const size_t totalSize = (N*sizeof(ResStringPool_span))
                               + sizeof(ResStringPool_ref);

        ent.offset = styPos-strPos;
        uint8_t* dat = (uint8_t*)pool->editData(preSize + styPos + totalSize);
        if (dat == NULL) {
            fprintf(stderr, "ERROR: Out of memory for string styles\n");
            return NO_MEMORY;
        }
        ResStringPool_span* span = (ResStringPool_span*)(dat+preSize+styPos);
        for (size_t i=0; i<N; i++) {
            span->name.index = htodl(ent.spans[i].span.name.index);
            span->firstChar = htodl(ent.spans[i].span.firstChar);
            span->lastChar = htodl(ent.spans[i].span.lastChar);
            span++;
        }
        span->name.index = htodl(ResStringPool_span::END);

        styPos += totalSize;
    }

    if (STYLES > 0) {
        // Add full terminator at the end (when reading we validate that
        // the end of the pool is fully terminated to simplify error
        // checking).
        size_t extra = sizeof(ResStringPool_span)-sizeof(ResStringPool_ref);
        uint8_t* dat = (uint8_t*)pool->editData(preSize + styPos + extra);
        if (dat == NULL) {
            fprintf(stderr, "ERROR: Out of memory for string styles\n");
            return NO_MEMORY;
        }
        uint32_t* p = (uint32_t*)(dat+preSize+styPos);
        while (extra > 0) {
            *p++ = htodl(ResStringPool_span::END);
            extra -= sizeof(uint32_t);
        }
        styPos += extra;
    }

    // Write header.
    // 寫字符串池頭部
    ResStringPool_header* header =
        (ResStringPool_header*)pool->padData(sizeof(uint32_t));
    if (header == NULL) {
        fprintf(stderr, "ERROR: Out of memory for string pool\n");
        return NO_MEMORY;
    }
    memset(header, 0, sizeof(*header));
    header->header.type = htods(RES_STRING_POOL_TYPE);
    header->header.headerSize = htods(sizeof(*header));
    header->header.size = htodl(pool->getSize());
    header->stringCount = htodl(ENTRIES);
    header->styleCount = htodl(STYLES);
    if (mUTF8) {
        header->flags |= htodl(ResStringPool_header::UTF8_FLAG);
    }
    header->stringsStart = htodl(preSize);
    header->stylesStart = htodl(STYLES > 0 ? (preSize+strPos) : 0);

    // Write string index array.

    uint32_t* index = (uint32_t*)(header+1);
    for (i=0; i<ENTRIES; i++) {  // 寫字符串索引區
        entry& ent = mEntries.editItemAt(mEntryArray[i]);
        *index++ = htodl(ent.offset);
        if (kIsDebug) {
            printf("Writing entry #%zu: \"%s\" ent=%zu off=%zu\n",
                    i,
                    String8(ent.value).string(),
                    mEntryArray[i],
                    ent.offset);
        }
    }

    // Write style index array.

    for (i=0; i<STYLES; i++) {  // 寫樣式索引區
        *index++ = htodl(mEntryStyleArray[i].offset);
    }

    return NO_ERROR;
}

        對代碼的解析通過註釋的形式寫到代碼中了.

 
 

結尾

最後我們來總結下字符串的查找過程:

1. 根據索引值在字符串索引區找到字符串在字符串內容區的偏移。
2. 根據頭部中的stringsStart找到字符串內容區, 再根據字符串偏移找到對應字符串. 根據字符串長度讀取字符串內容。
3. 根據索引值在樣式索引區找到樣式信息在樣式內容區的偏移。
4. 根據頭部中的styleStart找到樣式串內容區, 再根據樣式偏移找到對應字樣式。
5. 合併字符串內容和樣式信息,返回字符串。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章