amaters_core/
validation.rs1use crate::error::{AmateRSError, ErrorContext, Result};
6use crate::types::{CipherBlob, Key};
7
8pub fn check_positive(value: usize, name: &str) -> Result<()> {
10 if value > 0 {
11 Ok(())
12 } else {
13 Err(AmateRSError::ValidationError(ErrorContext::new(format!(
14 "{} must be positive, got {}",
15 name, value
16 ))))
17 }
18}
19
20pub fn check_ciphertext_size(blob: &CipherBlob) -> Result<()> {
22 if blob.len() <= CipherBlob::MAX_SIZE {
23 Ok(())
24 } else {
25 Err(AmateRSError::ValidationError(ErrorContext::new(format!(
26 "Ciphertext size {} exceeds maximum {}",
27 blob.len(),
28 CipherBlob::MAX_SIZE
29 ))))
30 }
31}
32
33pub fn check_key_size(key: &Key) -> Result<()> {
35 if key.len() <= Key::MAX_SIZE {
36 Ok(())
37 } else {
38 Err(AmateRSError::ValidationError(ErrorContext::new(format!(
39 "Key size {} exceeds maximum {}",
40 key.len(),
41 Key::MAX_SIZE
42 ))))
43 }
44}
45
46pub fn check_not_empty(s: &str, name: &str) -> Result<()> {
48 if !s.is_empty() {
49 Ok(())
50 } else {
51 Err(AmateRSError::ValidationError(ErrorContext::new(format!(
52 "{} cannot be empty",
53 name
54 ))))
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_check_positive() {
64 assert!(check_positive(1, "test").is_ok());
65 assert!(check_positive(0, "test").is_err());
66 }
67
68 #[test]
69 fn test_check_ciphertext_size() {
70 let small = CipherBlob::new(vec![1, 2, 3]);
71 assert!(check_ciphertext_size(&small).is_ok());
72 }
73
74 #[test]
75 fn test_check_key_size() {
76 let key = Key::from_str("test");
77 assert!(check_key_size(&key).is_ok());
78 }
79
80 #[test]
81 fn test_check_not_empty() {
82 assert!(check_not_empty("test", "name").is_ok());
83 assert!(check_not_empty("", "name").is_err());
84 }
85}