[英]What is a modern analog to the deprecated std::raw::Repr?
我正在查看一些舊的(~2014)Rust代碼,我看到這個代碼塊:
fn compile(self, func:&UncompiledFunction<'a>) -> &'a Val {
unsafe {
use std::raw::Repr;
use std::mem::transmute as cast;
let slice = self.repr();
let ty = <&'a str as Compile<'a>>::get_type();
let structure = Val::new(func, &ty);
let offset_data = cast::<_, usize>(&slice.data) - cast::<_, usize>(&slice);
let offset_len = cast::<_, usize>(&slice.len) - cast::<_, usize>(&slice);
func.insn_store_relative(structure, offset_data, func.insn_of(mem::transmute::<_, isize>(slice.data)));
func.insn_store_relative(structure, offset_len, func.insn_of(slice.len));
structure
}
}
根據文檔和這個GitHub的討論, std::raw::Repr
和std::raw::Slice
已被棄用,轉而使用std::slice
函數 。
作為只有初學者對std庫的理解的人,我不確定如何從上面的塊中翻譯這些特定的行:
let slice = self.repr(); // `self` here is a `static str`
let offset_data = cast::<_, usize>(&slice.data) - cast::<_, usize>(&slice);
let offset_len = cast::<_, usize>(&slice.len) - cast::<_, usize>(&slice);
我正在查看Repr
的文檔,希望能在std::slice
系列中對某些函數進行類比,但我沒有立即知道。
我希望有人可以向我解釋Repr
究竟做了什么(用不同的語言)以及更新的方法。
對於類型&[T]
或&str
x
:
x.repr().data
的替換是x.as_ptr()
。 x.repr().len
的替換是x.len()
。 std::raw::Slice
回&[T]
或&str
的替換是std::slice::from_raw_parts
(以及可選的std::str::from_utf8_unchecked
)。 然而,這段代碼不只是訪問指針和長度,而是采用這些字段的地址來計算它們的偏移量,可能是為了稍后進行一些不安全/未經檢查的內存讀取或寫入。
無益的答案是不要這樣做 。 std::raw::Slice
被刪除正是因為我們不想穩定&[T]
和&str
的確切內存布局。 如果這是可能的,請考慮重構代碼以不執行這些未經檢查的內存訪問,而是例如用std::str::from_utf8_unchecked(std::slice::from_raw_parts(new_pointer, new_len))
替換整個字符串。
實際的答案是內存布局不太可能改變,如果你硬編碼,你可能會好的:
let offset_data = 0;
let offset_len = std::mem::size_of::<usize>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.