Skip to content

Commit f21e486

Browse files
authored
Merge pull request #15 from T3pp31/codex/add-validate_safe_inputs-function
safe API の入力検証を共通化するヘルパーを追加
2 parents a03612a + a360546 commit f21e486

File tree

1 file changed

+23
-15
lines changed

1 file changed

+23
-15
lines changed

src/caesar_cipher.rs

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -150,16 +150,7 @@ pub fn decrypt(text: &str, shift: i16) -> String {
150150
/// assert!(encrypt_safe("Hello", 26).is_err());
151151
/// ```
152152
pub fn encrypt_safe(text: &str, shift: i16) -> Result<String, CipherError> {
153-
if text.trim().is_empty() {
154-
return Err(CipherError::EmptyText);
155-
}
156-
157-
if !(-MAX_SHIFT..=MAX_SHIFT).contains(&shift) {
158-
return Err(CipherError::InvalidShift(format!(
159-
"Shift value {} is out of range (-{} to {})",
160-
shift, MAX_SHIFT, MAX_SHIFT
161-
)));
162-
}
153+
validate_safe_inputs(text, shift)?;
163154

164155
Ok(shift_text(text, shift))
165156
}
@@ -192,18 +183,35 @@ pub fn encrypt_safe(text: &str, shift: i16) -> Result<String, CipherError> {
192183
/// assert_eq!(result, "Hello");
193184
/// ```
194185
pub fn decrypt_safe(text: &str, shift: i16) -> Result<String, CipherError> {
186+
validate_safe_inputs(text, shift)?;
187+
188+
let negated = -(shift as i32);
189+
let normalized = negated.rem_euclid(ALPHABET_SIZE as i32) as i16;
190+
Ok(shift_text(text, normalized))
191+
}
192+
193+
/// Validates shared inputs for safe Caesar cipher APIs.
194+
///
195+
/// This private function centralizes validation and error message generation
196+
/// used by `encrypt_safe` and `decrypt_safe`.
197+
fn validate_safe_inputs(text: &str, shift: i16) -> Result<(), CipherError> {
195198
if text.trim().is_empty() {
196199
return Err(CipherError::EmptyText);
197200
}
198201

199202
if !(-MAX_SHIFT..=MAX_SHIFT).contains(&shift) {
200-
return Err(CipherError::InvalidShift(format!(
201-
"Shift value {} is out of range (-{} to {})",
202-
shift, MAX_SHIFT, MAX_SHIFT
203-
)));
203+
return Err(invalid_shift_error(shift));
204204
}
205205

206-
Ok(shift_text(text, -shift))
206+
Ok(())
207+
}
208+
209+
/// Creates a standardized invalid shift error message.
210+
fn invalid_shift_error(shift: i16) -> CipherError {
211+
CipherError::InvalidShift(format!(
212+
"Shift value {} is out of range (-{} to {})",
213+
shift, MAX_SHIFT, MAX_SHIFT
214+
))
207215
}
208216

209217
/// Internal implementation: Performs text-level Caesar cipher transformation

0 commit comments

Comments
 (0)