cyfs_base/crypto/
hash_util.rs1use crate::{BuckyError, BuckyResult, HashValue};
2use async_std::io::{ErrorKind, ReadExt};
3use sha2::Digest;
4use std::path::Path;
5
6pub fn hash_data(data: &[u8]) -> HashValue {
7 let mut sha256 = sha2::Sha256::new();
8 sha256.input(data);
9 sha256.result().into()
10}
11
12pub async fn hash_stream(reader: &mut (impl ReadExt + Unpin)) -> BuckyResult<(HashValue, u64)> {
13 let mut sha256 = sha2::Sha256::new();
14 let mut buf = Vec::with_capacity(1024 * 64);
15 unsafe {
16 buf.set_len(1024 * 64);
17 }
18 let mut file_len = 0;
19 loop {
20 match reader.read(&mut buf).await {
21 Ok(size) => {
22 if size == 0 {
23 break;
24 }
25 sha256.input(&buf[0..size]);
26 file_len = file_len + size;
27 }
28 Err(e) => {
29 if let ErrorKind::Interrupted = e.kind() {
30 continue; }
32 return Err(BuckyError::from(e));
33 }
34 }
35 }
36
37 Ok((sha256.result().into(), file_len as u64))
38}
39
40#[cfg(not(target_arch = "wasm32"))]
41pub async fn hash_file(path: &Path) -> BuckyResult<(HashValue, u64)> {
42 let mut file = async_std::fs::File::open(path).await?;
43
44 let mut sha256 = sha2::Sha256::new();
45 let mut buf = Vec::with_capacity(1024 * 64);
46 unsafe {
47 buf.set_len(1024 * 64);
48 }
49 let mut file_len = 0;
50 loop {
51 match file.read(&mut buf).await {
52 Ok(size) => {
53 if size == 0 {
54 break;
55 }
56 sha256.input(&buf[0..size]);
57 file_len = file_len + size;
58 }
59 Err(e) => {
60 if let ErrorKind::Interrupted = e.kind() {
61 continue; }
63 return Err(BuckyError::from(e));
64 }
65 }
66 }
67
68 Ok((sha256.result().into(), file_len as u64))
69}
70
71#[cfg(not(target_arch = "wasm32"))]
72pub fn hash_file_sync(path: &Path) -> BuckyResult<(HashValue, u64)> {
73 use std::io::Read;
74
75 let mut file = std::fs::File::open(path)?;
76
77 let mut sha256 = sha2::Sha256::new();
78 let mut buf = Vec::with_capacity(1024 * 64);
79 unsafe {
80 buf.set_len(1024 * 64);
81 }
82 let mut file_len = 0;
83 loop {
84 match file.read(&mut buf) {
85 Ok(size) => {
86 if size == 0 {
87 break;
88 }
89 sha256.input(&buf[0..size]);
90 file_len = file_len + size;
91 }
92 Err(e) => {
93 if let ErrorKind::Interrupted = e.kind() {
94 continue; }
96 return Err(BuckyError::from(e));
97 }
98 }
99 }
100
101 Ok((sha256.result().into(), file_len as u64))
102}