天天看点

leveldb学习笔记之七——util/coding.h

coding.h中主要是与编码相关的内容,主要选取以下几个函数进行分析:

  • EncodeFixed32
void EncodeFixed32(char* buf, uint32_t value) {
  if (port::kLittleEndian) {  //小端次序直接使用memcpy
    memcpy(buf, &value, sizeof(value));
  } else {            //大端次序则按字节处理
    buf[0] = value & 0xff;
    buf[1] = (value >> 8) & 0xff;
    buf[2] = (value >> 16) & 0xff;
    buf[3] = (value >> 24) & 0xff;
  }
}      
  • PutFixed32
void PutFixed32(std::string* dst, uint32_t value) {
    char buf[sizeof(value)];
    EncodeFixed32(buf, value);
    dst->append(buf, sizeof(buf)); //对数据编码后再将长度放入
}      
  • EncodeVarint32

    varint编码是一种变长编码,用来减少数据的存储空间。在varint的每个字节中,如果最高位bit为1,表示后续的字节也是该数字的一部分,如果该位是0,则结束。其它的7个比特都用来表示数据。因此小于128的数字都可以用一个字节来表示。

char* EncodeVarint32(char* dst, uint32_t v) {
    unsigned char* ptr = reinterpret_cast<unsigned char*>(dst);
    static const int B = 128;
    if (v < (1<<7)) {  //小于128的一个字节就能搞定
      *(ptr++) = v;
    } else if (v < (1<<14)) {//两个字节
      *(ptr++) = v | B;
      *(ptr++) = v>>7;
    } else if (v < (1<<21)) {
      *(ptr++) = v | B;
      *(ptr++) = (v>>7) | B;
      *(ptr++) = v>>14;
    } else if (v < (1<<28)) {
      *(ptr++) = v | B;
      *(ptr++) = (v>>7) | B;
      *(ptr++) = (v>>14) | B;
      *(ptr++) = v>>21;
    } else {
      *(ptr++) = v | B;
      *(ptr++) = (v>>7) | B;
      *(ptr++) = (v>>14) | B;
      *(ptr++) = (v>>21) | B;
      *(ptr++) = v>>28;
    }
    return reinterpret_cast<char*>(ptr);
}      
  • PutVarint32
//将编码后的数据追加到dst中
void PutVarint32(std::string* dst, uint32_t v) {
    char buf[5];
    char* ptr = EncodeVarint32(buf, v);
    dst->append(buf, ptr - buf);
}      
  • PutLengthPrefixedSlice
void PutLengthPrefixedSlice(std::string* dst, const Slice& value) {
  PutVarint32(dst, value.size());
  dst->append(value.data(), value.size());  //将value编码到dst中
}