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)
37}
48
59#[ cfg( test) ]
@@ -10,13 +14,37 @@ mod tests {
1014 fn test_simple ( ) {
1115 let test_string = "test string" ;
1216 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 ) ) ;
1418 }
1519
1620 #[ test]
1721 fn test_every_alphabet_with_space ( ) {
1822 let test_string = "The quick brown fox jumps over the lazy dog" ;
1923 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) ) ;
2149 }
2250}
0 commit comments