关于fbstring initsmall()方法的问题



我正在阅读愚蠢的源代码。当我阅读fbstring实现时,我对initsmall函数的实现感到困惑
如果字节大小是17,字大小字节大小+字宽度-1(/wordWidth为3。是否relpret_cast<const size_t>(data([2]访问数据的第17个char元素和以下7个元素?这不是越界了吗
下面是实现代码,完整的代码位于https://github.com/facebook/folly/blame/master/folly/FBString.h

// Small strings are bitblitted
template <class Char>
inline void fbstring_core<Char>::initSmall(
const Char* const data, const size_t size) {
// Layout is: Char* data_, size_t size_, size_t capacity_
static_assert(
sizeof(*this) == sizeof(Char*) + 2 * sizeof(size_t),
"fbstring has unexpected size");
static_assert(
sizeof(Char*) == sizeof(size_t), "fbstring size assumption violation");
// sizeof(size_t) must be a power of 2
static_assert(
(sizeof(size_t) & (sizeof(size_t) - 1)) == 0,
"fbstring size assumption violation");
// If data is aligned, use fast word-wise copying. Otherwise,
// use conservative memcpy.
// The word-wise path reads bytes which are outside the range of
// the string, and makes ASan unhappy, so we disable it when
// compiling with ASan.
#ifndef FOLLY_SANITIZE_ADDRESS
if ((reinterpret_cast<size_t>(data) & (sizeof(size_t) - 1)) == 0) {
const size_t byteSize = size * sizeof(Char);
constexpr size_t wordWidth = sizeof(size_t);
switch ((byteSize + wordWidth - 1) / wordWidth) { // Number of words.
case 3:
ml_.capacity_ = reinterpret_cast<const size_t*>(data)[2];
FOLLY_FALLTHROUGH;
case 2:
ml_.size_ = reinterpret_cast<const size_t*>(data)[1];
FOLLY_FALLTHROUGH;
case 1:
ml_.data_ = *reinterpret_cast<Char**>(const_cast<Char*>(data));
FOLLY_FALLTHROUGH;
case 0:
break;
}
} else
#endif
{
if (size != 0) {
fbstring_detail::podCopy(data, data + size, small_);
}
}
setSmallSize(size);
}

是的,它会超出范围。这就是为什么它在编译器抱怨的情况下使用FOLLY_ANITIZE_ADDRESS。如果编译器对此没有意见,那么它会复制单词,尽管它复制的大小超过了您需要的大小。但是,由于setSmallSize((可以告诉您字符串的大小,因此额外复制的字节可以放入字符串缓冲区,但不能读取。

最新更新