nu_command/hash/
sha256.rs1use super::generic_digest::{GenericDigest, HashDigest};
2use nu_protocol::{Example, Span, Value};
3use sha2::Sha256;
4
5pub type HashSha256 = GenericDigest<Sha256>;
6
7impl HashDigest for Sha256 {
8 fn name() -> &'static str {
9 "sha256"
10 }
11
12 fn examples() -> Vec<Example<'static>> {
13 vec![
14 Example {
15 description: "Return the sha256 hash of a string, hex-encoded",
16 example: "'abcdefghijklmnopqrstuvwxyz' | hash sha256",
17 result: Some(Value::string(
18 "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73".to_owned(),
19 Span::test_data(),
20 )),
21 },
22 Example {
23 description: "Return the sha256 hash of a string, as binary",
24 example: "'abcdefghijklmnopqrstuvwxyz' | hash sha256 --binary",
25 result: Some(Value::binary(
26 vec![
27 0x71, 0xc4, 0x80, 0xdf, 0x93, 0xd6, 0xae, 0x2f, 0x1e, 0xfa, 0xd1, 0x44,
28 0x7c, 0x66, 0xc9, 0x52, 0x5e, 0x31, 0x62, 0x18, 0xcf, 0x51, 0xfc, 0x8d,
29 0x9e, 0xd8, 0x32, 0xf2, 0xda, 0xf1, 0x8b, 0x73,
30 ],
31 Span::test_data(),
32 )),
33 },
34 Example {
35 description: "Return the sha256 hash of binary data",
36 example: "0x[deadbeef] | hash sha256",
37 result: None,
38 },
39 Example {
40 description: "Return the sha256 hash of a file's contents",
41 example: "open ./nu_0_24_1_windows.zip | hash sha256",
42 result: None,
43 },
44 ]
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51 use crate::hash::generic_digest::{self, Arguments};
52
53 #[test]
54 fn test_examples() -> nu_test_support::Result {
55 nu_test_support::test().examples(HashSha256::default())
56 }
57
58 #[test]
59 fn hash_string() {
60 let binary = Value::string("abcdefghijklmnopqrstuvwxyz".to_owned(), Span::test_data());
61 let expected = Value::string(
62 "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73".to_owned(),
63 Span::test_data(),
64 );
65 let actual = generic_digest::action::<Sha256>(
66 &binary,
67 &Arguments {
68 cell_paths: None,
69 binary: false,
70 },
71 Span::test_data(),
72 );
73 assert_eq!(actual, expected);
74 }
75
76 #[test]
77 fn hash_bytes() {
78 let binary = Value::binary(vec![0xC0, 0xFF, 0xEE], Span::test_data());
79 let expected = Value::string(
80 "c47a10dc272b1221f0380a2ae0f7d7fa830b3e378f2f5309bbf13f61ad211913".to_owned(),
81 Span::test_data(),
82 );
83 let actual = generic_digest::action::<Sha256>(
84 &binary,
85 &Arguments {
86 cell_paths: None,
87 binary: false,
88 },
89 Span::test_data(),
90 );
91 assert_eq!(actual, expected);
92 }
93}