pub const MAX_INSTANCE_ID_LEN: usize = 256;
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum InvalidInstanceId {
#[error("instance_id must not be empty")]
Empty,
#[error("instance_id length {len} exceeds maximum {max} bytes")]
TooLong {
len: usize,
max: usize,
},
}
pub fn validate_instance_id(instance_id: &str) -> Result<(), InvalidInstanceId> {
if instance_id.is_empty() {
return Err(InvalidInstanceId::Empty);
}
if instance_id.len() > MAX_INSTANCE_ID_LEN {
return Err(InvalidInstanceId::TooLong {
len: instance_id.len(),
max: MAX_INSTANCE_ID_LEN,
});
}
Ok(())
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
#[test]
fn accepts_typical_ids() {
validate_instance_id("a").unwrap();
validate_instance_id("order-12345").unwrap();
validate_instance_id("01HQK4P9P0V7S6XQGZ9N3M2RF7").unwrap(); }
#[test]
fn rejects_empty() {
assert_eq!(validate_instance_id(""), Err(InvalidInstanceId::Empty));
}
#[test]
fn accepts_exactly_max() {
let s = "x".repeat(MAX_INSTANCE_ID_LEN);
validate_instance_id(&s).unwrap();
}
#[test]
fn rejects_one_byte_too_long() {
let s = "x".repeat(MAX_INSTANCE_ID_LEN + 1);
let err = validate_instance_id(&s).unwrap_err();
assert_eq!(
err,
InvalidInstanceId::TooLong {
len: MAX_INSTANCE_ID_LEN + 1,
max: MAX_INSTANCE_ID_LEN,
}
);
}
}