caesar_cipher_enc_dec 1.0.10

can easily use caesar cipher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
use clap::{Args, Parser, Subcommand};
use std::fs;
use std::io::{self, Write};

use crate::bounded_input::{read_file_bounded, read_line_bounded};
use crate::caesar_cipher::{decrypt, decrypt_safe, encrypt, encrypt_safe};
use crate::config::{
    DEFAULT_SHIFT, MAX_BRUTE_FORCE_SHIFT, MAX_INPUT_SIZE, MAX_SHIFT, MAX_SHIFT_LINE_SIZE, MIN_SHIFT,
};

/// Main CLI structure for the Caesar cipher application
///
/// This structure defines the command-line interface for the Caesar cipher tool,
/// supporting various operations like encryption, decryption, interactive mode, and brute force.
#[derive(Parser)]
#[command(name = "caesar_cipher")]
#[command(about = "A Caesar cipher encryption/decryption tool")]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

/// Common arguments shared between encrypt and decrypt commands
#[derive(Args)]
pub struct CipherArgs {
    /// Text to process
    #[arg(short, long, conflicts_with = "file")]
    pub text: Option<String>,

    /// Input file path
    #[arg(short = 'f', long, conflicts_with = "text")]
    pub file: Option<String>,

    /// Shift value (any integer; safe mode: -25 to 25, default: 3)
    #[arg(short, long, default_value_t = DEFAULT_SHIFT)]
    pub shift: i16,

    /// Output file path
    #[arg(short, long)]
    pub output: Option<String>,

    /// Use safe mode with error checking
    #[arg(long)]
    pub safe: bool,
}

/// Available commands for the Caesar cipher CLI
///
/// Each variant represents a different operation that can be performed
/// with the Caesar cipher tool.
#[derive(Subcommand)]
pub enum Commands {
    /// Encrypt text using Caesar cipher
    Encrypt(CipherArgs),
    /// Decrypt text using Caesar cipher
    Decrypt(CipherArgs),
    /// Interactive mode
    Interactive,
    /// Show all possible decryptions (brute force)
    BruteForce {
        /// Text to decrypt
        #[arg(short, long, conflicts_with = "file")]
        text: Option<String>,

        /// Input file path
        #[arg(short = 'f', long, conflicts_with = "text")]
        file: Option<String>,
    },
}

/// Runs the CLI application
///
/// This function parses command-line arguments and executes the appropriate
/// command based on user input. It handles encryption, decryption, interactive mode,
/// and brute force operations.
///
/// # Returns
///
/// Returns `Ok(())` on successful execution, or an error if something goes wrong.
///
/// # Errors
///
/// Returns an error if:
/// - File operations fail
/// - Invalid input is provided to safe functions
/// - Input/output operations fail
pub fn run_cli() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Encrypt(args) => {
            let input_text = get_input_text(args.text, args.file)?;
            let result = if args.safe {
                encrypt_safe(&input_text, args.shift)?
            } else {
                encrypt(&input_text, args.shift)
            };
            output_result(&result, args.output)?;
        }

        Commands::Decrypt(args) => {
            let input_text = get_input_text(args.text, args.file)?;
            let result = if args.safe {
                decrypt_safe(&input_text, args.shift)?
            } else {
                decrypt(&input_text, args.shift)
            };
            output_result(&result, args.output)?;
        }

        Commands::Interactive => {
            run_interactive_mode()?;
        }

        Commands::BruteForce { text, file } => {
            let input_text = get_input_text(text, file)?;
            run_brute_force(&input_text);
        }
    }

    Ok(())
}

/// Gets input text from either command-line argument, file, or stdin
///
/// This function handles the logic for obtaining input text from various sources.
/// It prioritizes direct text input, then file input, and falls back to stdin if neither is provided.
///
/// # Arguments
///
/// * `text` - Optional text string provided via command line
/// * `file` - Optional file path to read text from
///
/// # Returns
///
/// The input text as a String
///
/// # Errors
///
/// Returns an error if:
/// - File reading fails
/// - Stdin reading fails
fn get_input_text(
    text: Option<String>,
    file: Option<String>,
) -> Result<String, Box<dyn std::error::Error>> {
    if let Some(t) = text {
        if t.len() > MAX_INPUT_SIZE {
            return Err(format!(
                "Input text exceeds maximum size of {} bytes",
                MAX_INPUT_SIZE
            )
            .into());
        }
        return Ok(t);
    }

    if let Some(f) = file {
        let input = read_file_bounded(&f, MAX_INPUT_SIZE).map_err(|e| e.to_string())?;
        return Ok(trim_trailing_newline(&input).to_string());
    }

    print!("Enter text: ");
    io::stdout().flush()?;
    let mut stdin = io::stdin().lock();
    let input = read_line_bounded(&mut stdin, MAX_INPUT_SIZE).map_err(|e| e.to_string())?;
    Ok(trim_trailing_newline(&input).to_string())
}

/// Strips only trailing line endings from stdin/file-style input, preserving spaces.
fn trim_trailing_newline(input: &str) -> &str {
    input.trim_end_matches(['\n', '\r'])
}

/// Outputs the result to either a file or stdout
///
/// This function handles outputting the cipher result to the specified destination.
/// If an output file is provided, writes to that file; otherwise prints to stdout.
///
/// # Arguments
///
/// * `result` - The text result to output
/// * `output_file` - Optional file path to write the result to
///
/// # Returns
///
/// Returns `Ok(())` on success
///
/// # Errors
///
/// Returns an error if file writing fails
fn output_result(
    result: &str,
    output_file: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
    match output_file {
        Some(file) => {
            fs::write(&file, result)?;
            println!("Result written to file: {}", file);
        }
        None => {
            println!("{}", result);
        }
    }
    Ok(())
}

/// Prompts the user for text input
///
/// # Arguments
///
/// * `prompt` - The prompt message to display
///
/// # Returns
///
/// Input with trailing line endings removed (leading/trailing spaces preserved).
fn prompt_for_text(prompt: &str) -> io::Result<String> {
    print!("{}", prompt);
    io::stdout().flush()?;
    let mut stdin = io::stdin().lock();
    let input = read_line_bounded(&mut stdin, MAX_INPUT_SIZE)?;
    Ok(trim_trailing_newline(&input).to_string())
}

/// Validates shift input string and returns parsed value with optional warning
///
/// # Arguments
///
/// * `input` - Raw input string from user
///
/// # Returns
///
/// A tuple of (shift value, optional warning message).
/// Returns default shift with warning if input is invalid.
pub(crate) fn validate_shift_input(input: &str) -> (i16, Option<String>) {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return (DEFAULT_SHIFT, None);
    }

    match trimmed.parse::<i16>() {
        Ok(shift) => {
            if !(MIN_SHIFT..=MAX_SHIFT).contains(&shift) {
                let warning = format!(
                    "Warning: shift {} is outside the typical range ({} to {}). Value will be normalized.",
                    shift, MIN_SHIFT, MAX_SHIFT
                );
                (shift, Some(warning))
            } else {
                (shift, None)
            }
        }
        Err(_) => {
            let warning = format!("Invalid shift value, using default ({})", DEFAULT_SHIFT);
            (DEFAULT_SHIFT, Some(warning))
        }
    }
}

/// Prompts the user for a shift value with validation
///
/// # Returns
///
/// A valid shift value, or the default if input is invalid
fn prompt_for_shift() -> io::Result<i16> {
    print!("Enter shift value (default: {}): ", DEFAULT_SHIFT);
    io::stdout().flush()?;
    let mut stdin = io::stdin().lock();
    let shift_str = read_line_bounded(&mut stdin, MAX_SHIFT_LINE_SIZE)?;

    let (shift, warning) = validate_shift_input(&shift_str);
    if let Some(msg) = warning {
        println!("{}", msg);
    }
    Ok(shift)
}

/// Runs the interactive mode for the Caesar cipher
///
/// This function provides an interactive command-line interface where users
/// can repeatedly perform encryption, decryption, and brute force operations
/// without restarting the program.
///
/// # Returns
///
/// Returns `Ok(())` on successful completion
///
/// # Errors
///
/// Returns an error if input/output operations fail
fn run_interactive_mode() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Caesar Cipher Interactive Mode ===");
    println!("Type 'quit' to exit");

    loop {
        let choice =
            prompt_for_text("\nChoose operation (e)ncrypt, (d)ecrypt, (b)rute force, or (q)uit: ")?;
        let choice = choice.to_lowercase();

        match choice.as_str() {
            "e" | "encrypt" => {
                let text = prompt_for_text("Enter text to encrypt: ")?;
                let shift = prompt_for_shift()?;
                let result = encrypt(&text, shift);
                println!("Encrypted: {}", result);
            }

            "d" | "decrypt" => {
                let text = prompt_for_text("Enter text to decrypt: ")?;
                let shift = prompt_for_shift()?;
                let result = decrypt(&text, shift);
                println!("Decrypted: {}", result);
            }

            "b" | "brute" | "bruteforce" => {
                let text = prompt_for_text("Enter text to brute force decrypt: ")?;
                run_brute_force(&text);
            }

            "q" | "quit" => {
                println!("Goodbye!");
                break;
            }

            _ => {
                println!("Invalid option. Please choose e, d, b, or q.");
            }
        }
    }

    Ok(())
}

/// Performs brute force decryption on the given text
///
/// This function attempts to decrypt the input text using all possible
/// shift values (0-25) and displays the results. This is useful when
/// the shift value is unknown. Shift 0 shows the original text for reference.
///
/// # Arguments
///
/// * `text` - The encrypted text to brute force decrypt
fn run_brute_force(text: &str) {
    println!("\n=== Brute Force Decryption ===");
    println!("Original: {}", text);
    println!("Trying all possible shifts:");

    for shift in 0..=MAX_BRUTE_FORCE_SHIFT {
        let decrypted = decrypt(text, shift);
        println!("Shift {:2}: {}", shift, decrypted);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_get_input_text_from_string() {
        let result = get_input_text(Some("Hello".to_string()), None).unwrap();
        assert_eq!(result, "Hello");
    }

    #[test]
    fn test_get_input_text_from_file() {
        let mut temp_file = NamedTempFile::new().unwrap();
        writeln!(temp_file, "Test content").unwrap();

        let result =
            get_input_text(None, Some(temp_file.path().to_string_lossy().to_string())).unwrap();
        assert_eq!(result.trim(), "Test content");
    }

    #[test]
    fn test_get_input_text_prefers_text_when_both_provided() {
        let result = get_input_text(Some("Hello".to_string()), Some("file.txt".to_string()));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Hello");
    }

    #[test]
    fn test_trim_trailing_newline_preserves_leading_and_trailing_spaces() {
        let input = "  keep spaces  \n";
        let result = trim_trailing_newline(input);
        assert_eq!(result, "  keep spaces  ");
    }

    #[test]
    fn test_output_result_to_file() {
        let temp_file = NamedTempFile::new().unwrap();
        let file_path = temp_file.path().to_string_lossy().to_string();

        output_result("Test output", Some(file_path.clone())).unwrap();

        let content = fs::read_to_string(file_path).unwrap();
        assert_eq!(content, "Test output");
    }

    // -------------------------------------------------------------------------
    // Input size limit tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_read_file_bounded_rejects_directory() {
        // Given: A directory path
        let dir = tempfile::tempdir().unwrap();

        // When: Reading as a bounded file
        let result = crate::bounded_input::read_file_bounded(dir.path(), MAX_INPUT_SIZE);

        // Then: Rejects non-regular file
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("not a regular file"));
    }

    #[test]
    fn test_get_input_text_oversized_file_error() {
        // Given: A file that exceeds MAX_INPUT_SIZE
        use std::io::Write as _;
        let mut temp_file = NamedTempFile::new().unwrap();
        // Write MAX_INPUT_SIZE + 1 bytes to exceed the limit
        let oversized_data = vec![b'A'; MAX_INPUT_SIZE + 1];
        temp_file.write_all(&oversized_data).unwrap();
        temp_file.flush().unwrap();

        // When: Reading from oversized file
        let result = get_input_text(None, Some(temp_file.path().to_string_lossy().to_string()));

        // Then: Returns error about exceeding maximum size
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("exceeds maximum size"));
    }

    #[test]
    fn test_get_input_text_file_at_max_size_succeeds() {
        // Given: A file exactly at MAX_INPUT_SIZE (should succeed)
        use std::io::Write as _;
        let mut temp_file = NamedTempFile::new().unwrap();
        let data = vec![b'A'; MAX_INPUT_SIZE];
        temp_file.write_all(&data).unwrap();
        temp_file.flush().unwrap();

        // When: Reading from file at the limit
        let result = get_input_text(None, Some(temp_file.path().to_string_lossy().to_string()));

        // Then: Returns Ok
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), MAX_INPUT_SIZE);
    }

    // -------------------------------------------------------------------------
    // validate_shift_input tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_validate_shift_input_valid_value() {
        // Given: A valid shift value within range
        // When: Validating input "3"
        let (shift, warning) = validate_shift_input("3");
        // Then: Returns 3 with no warning
        assert_eq!(shift, 3);
        assert!(warning.is_none());
    }

    #[test]
    fn test_validate_shift_input_zero() {
        // Given: Shift value of 0 (boundary)
        // When: Validating input "0"
        let (shift, warning) = validate_shift_input("0");
        // Then: Returns 0 with no warning
        assert_eq!(shift, 0);
        assert!(warning.is_none());
    }

    #[test]
    fn test_validate_shift_input_max_boundary() {
        // Given: Maximum valid shift value (25)
        // When: Validating input "25"
        let (shift, warning) = validate_shift_input("25");
        // Then: Returns 25 with no warning
        assert_eq!(shift, 25);
        assert!(warning.is_none());
    }

    #[test]
    fn test_validate_shift_input_min_boundary() {
        // Given: Minimum valid shift value (-25)
        // When: Validating input "-25"
        let (shift, warning) = validate_shift_input("-25");
        // Then: Returns -25 with no warning
        assert_eq!(shift, -25);
        assert!(warning.is_none());
    }

    #[test]
    fn test_validate_shift_input_out_of_range_positive() {
        // Given: Shift value above range (26)
        // When: Validating input "26"
        let (shift, warning) = validate_shift_input("26");
        // Then: Returns 26 with a warning
        assert_eq!(shift, 26);
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("Warning"));
    }

    #[test]
    fn test_validate_shift_input_out_of_range_negative() {
        // Given: Shift value below range (-26)
        // When: Validating input "-26"
        let (shift, warning) = validate_shift_input("-26");
        // Then: Returns -26 with a warning
        assert_eq!(shift, -26);
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("Warning"));
    }

    #[test]
    fn test_validate_shift_input_far_out_of_range() {
        // Given: Shift value far out of range (9999)
        // When: Validating input "9999"
        let (shift, warning) = validate_shift_input("9999");
        // Then: Returns 9999 with a warning containing the value
        assert_eq!(shift, 9999);
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("9999"));
    }

    #[test]
    fn test_validate_shift_input_invalid_string() {
        // Given: Non-numeric input
        // When: Validating input "abc"
        let (shift, warning) = validate_shift_input("abc");
        // Then: Returns default shift with a warning
        assert_eq!(shift, DEFAULT_SHIFT);
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("Invalid"));
    }

    #[test]
    fn test_validate_shift_input_empty_string() {
        // Given: Empty input
        // When: Validating input ""
        let (shift, warning) = validate_shift_input("");
        // Then: Returns default shift with no warning
        assert_eq!(shift, DEFAULT_SHIFT);
        assert!(warning.is_none());
    }

    #[test]
    fn test_validate_shift_input_whitespace_only() {
        // Given: Whitespace-only input
        // When: Validating input "  "
        let (shift, warning) = validate_shift_input("  ");
        // Then: Returns default shift with no warning (treated as empty)
        assert_eq!(shift, DEFAULT_SHIFT);
        assert!(warning.is_none());
    }

    #[test]
    fn test_validate_shift_input_with_surrounding_whitespace() {
        // Given: Valid value with surrounding whitespace
        // When: Validating input " 5 "
        let (shift, warning) = validate_shift_input(" 5 ");
        // Then: Returns 5 with no warning
        assert_eq!(shift, 5);
        assert!(warning.is_none());
    }
}