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. 合并字符串内容和样式信息,返回字符串。

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