gpt4 book ai didi

rust - 在Rust中,什么是保持范围内文件中数据读取的正确方法?

转载 作者:行者123 更新时间:2023-12-03 11:48:02 26 4
gpt4 key购买 nike

  • 我是Rust的新手。
  • 我正在从文件中读取SHA1-as-hex字符串-很多,大约。 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"
    我想我应该可以使用 std::convert::From<&'static str>实现,但是我不明白如何将 hash保留在范围内?
    我觉得我想要实现的是一个非常正常的用例:
  • 遍历文件中的各行。
  • 将行添加到向量中。

  • 我想念什么?

    最佳答案

    你几乎想要这样的东西,

    U256::from_str(&hash)?
    &str特性中的 FromStr有一个转换,称为 from_str。它返回 Result<T, E>值,因为解析字符串可能会失败。

    I think I should be able to use the implementation std::convert::From<&'static str>, but I don't understand how I'm meant to keep hash in scope?


    您无法将哈希值保留在 'static生命周期的范围内。看起来这是一种方便的方法,可让您在程序中使用字符串常量,但实际上只不过是 U256::from_str(&hash).unwrap()而已。
    然而…
    如果要使用SHA-1,最好的类型可能是 [u8; 20][u32; 5]
    您需要一个基数为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),
    }
    }

    关于rust - 在Rust中,什么是保持范围内文件中数据读取的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63226062/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com