rust - 在 Rust 中,将文件读取的数据保持在范围内的正确方法是什么?
问题描述
- 我是 Rust 的新手。
- 我正在从文件中读取 SHA1-as-hex-strings - 其中很多,大约。3000万。
- 在文本文件中,它们按数字升序排列。
- 我希望能够尽可能快地搜索列表。
- 我(想我)想将它们读入(排序的)
Vec<
primitive_type::U256>
以便快速搜索。
所以,我试过:
log("Loading haystack.");
// total_lines read earlier
let mut the_stack = Vec::<primitive_types::U256>::with_capacity(total_lines);
if let Ok(hay) = read_lines(haystack) { // Get BufRead
for line in hay { // Iterate over lines
if let Ok(hash) = line {
the_stack.push(U256::from(hash));
}
}
}
log(format!("Read {} hashes.", the_stack.len()));
错误是:
$ cargo build
Compiling nsrl v0.1.0 (/my_app)
error[E0277]: the trait bound `primitive_types::U256: std::convert::From<std::string::String>` is not satisfied
--> src/main.rs:55:24
|
55 | the_stack.push(U256::from(hash));
| ^^^^^^^^^^ the trait `std::convert::From<std::string::String>` is not implemented for `primitive_types::U256`
|
= help: the following implementations were found:
<primitive_types::U256 as std::convert::From<&'a [u8; 32]>>
<primitive_types::U256 as std::convert::From<&'a [u8]>>
<primitive_types::U256 as std::convert::From<&'a primitive_types::U256>>
<primitive_types::U256 as std::convert::From<&'static str>>
and 14 others
= note: required by `std::convert::From::from`
hash
如果我有一个字符串文字而不是变量,则此代码有效,例如"123abc"
.
我想我应该能够使用 implementation std::convert::From<&'static str>
,但我不明白我是如何保持hash
在范围内的?
我觉得我想要实现的是一个非常正常的用例:
- 遍历文件中的行。
- 将线添加到向量。
我错过了什么?
解决方案
你几乎想要类似的东西,
U256::from_str(&hash)?
&str
在FromStr
trait中有一个转换,称为from_str
. 它返回一个Result<T, E>
值,因为解析字符串可能会失败。
我想我应该能够使用 implementation
std::convert::From<&'static str>
,但我不明白我是如何将 hash 保持在范围内的?
您不能将哈希值保持在'static
生命周期的范围内。看起来这是一种允许您在程序中使用字符串常量的便捷方法——但实际上它只不过是U256::from_str(&hash).unwrap()
.
然而……</h2>
如果你想要一个 SHA-1,最好的类型可能是[u8; 20]
或者可能是[u32; 5]
.
你想要一个 base 16 解码器,比如base16::decode_slice。以下是实际效果:
/// Error if the hash cannot be parsed.
struct InvalidHash;
/// Type for SHA-1 hashes.
type SHA1 = [u8; 20];
fn read_hash(s: &str) -> Result<SHA1, InvalidHash> {
let mut hash = [0; 20];
match base16::decode_slice(s, &mut hash[..]) {
Ok(20) => Ok(hash),
_ => Err(InvalidHash),
}
}
推荐阅读
- ibm-infosphere - 我们如何以 MUMPS 格式存储数据?
- attributes - 如何通过 Web 服务在服务订单上创建属性
- mysql - 如何在MYSQL中选择两种组合情况的结果?
- java - 从 ArrayList 检索数据时出现逻辑错误
- node.js - 如何通过换行符在 Node.js 中拆分缓冲区
- javascript - 如何包装 React 组件?
- angular - 提高地图绘制和过滤的性能 - Angular 8,LeafletJS
- python - 使用 df.rolling() 获取整卷
- postgresql - 使用谓词进行日期过滤的条件查询
- reactjs - 使用反应路由器在组件中未呈现数据