1
- pub fn xor ( text : & str , key : u8 ) -> String {
2
- text. chars ( ) . map ( |c| ( ( c as u8 ) ^ key) as char ) . collect ( )
1
+ pub fn xor_bytes ( text : & [ u8 ] , key : u8 ) -> Vec < u8 > {
2
+ text. iter ( ) . map ( |c| c ^ key) . collect ( )
3
+ }
4
+
5
+ pub fn xor ( text : & str , key : u8 ) -> Vec < u8 > {
6
+ xor_bytes ( text. as_bytes ( ) , key)
3
7
}
4
8
5
9
#[ cfg( test) ]
@@ -10,13 +14,37 @@ mod tests {
10
14
fn test_simple ( ) {
11
15
let test_string = "test string" ;
12
16
let ciphered_text = xor ( test_string, 32 ) ;
13
- assert_eq ! ( test_string, xor ( & ciphered_text, 32 ) ) ;
17
+ assert_eq ! ( test_string. as_bytes ( ) , xor_bytes ( & ciphered_text, 32 ) ) ;
14
18
}
15
19
16
20
#[ test]
17
21
fn test_every_alphabet_with_space ( ) {
18
22
let test_string = "The quick brown fox jumps over the lazy dog" ;
19
23
let ciphered_text = xor ( test_string, 64 ) ;
20
- assert_eq ! ( test_string, xor( & ciphered_text, 64 ) ) ;
24
+ assert_eq ! ( test_string. as_bytes( ) , xor_bytes( & ciphered_text, 64 ) ) ;
25
+ }
26
+
27
+ #[ test]
28
+ fn test_multi_byte ( ) {
29
+ let test_string = "日本語" ;
30
+ let key = 42 ;
31
+ let ciphered_text = xor ( test_string, key) ;
32
+ assert_eq ! ( test_string. as_bytes( ) , xor_bytes( & ciphered_text, key) ) ;
33
+ }
34
+
35
+ #[ test]
36
+ fn test_zero_byte ( ) {
37
+ let test_string = "The quick brown fox jumps over the lazy dog" ;
38
+ let key = ' ' as u8 ;
39
+ let ciphered_text = xor ( test_string, key) ;
40
+ assert_eq ! ( test_string. as_bytes( ) , xor_bytes( & ciphered_text, key) ) ;
41
+ }
42
+
43
+ #[ test]
44
+ fn test_invalid_byte ( ) {
45
+ let test_string = "The quick brown fox jumps over the lazy dog" ;
46
+ let key = !0 as u8 ;
47
+ let ciphered_text = xor ( test_string, key) ;
48
+ assert_eq ! ( test_string. as_bytes( ) , xor_bytes( & ciphered_text, key) ) ;
21
49
}
22
50
}
0 commit comments