Skip to content

Instantly share code, notes, and snippets.

@davich
Created February 6, 2020 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davich/3add2a596971b05cf3efa28c1308a507 to your computer and use it in GitHub Desktop.
Save davich/3add2a596971b05cf3efa28c1308a507 to your computer and use it in GitHub Desktop.
use sha2::{Digest, Sha256};
use std::fmt::Write;
fn main() {
println!("Answer is {:?}", rust_mine("hello"));
}
pub fn rust_mine(text: &str) -> String {
let mut hasher = Sha256::new();
let mut text = text.to_string();
(0..std::usize::MAX)
.find_map(|nonce| {
text.split_off(5);
write!(&mut text, "{}", nonce).unwrap();
hasher.input(&text);
let result = hasher.result_reset();
if &result[0..2] == &[0, 0] && result[2] >> 4 == 0 {
Some(format!("{:x}", result))
} else {
None
}
})
.expect("unable to find answer")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(
rust_mine("hello"),
"0000037660ee0e22df67a053537e000325bbfad2cce9b8b7c795f6aa961d5cb7".to_string()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment