Skip to main content

ezmsg/
validators.rs

1use crate::err::Error;
2
3fn is_topic_leading_char(c: char) -> bool {
4  c.is_alphabetic()
5}
6
7fn is_topic_char(c: char) -> bool {
8  c.is_alphanumeric() || c == '_' || c == '-'
9}
10
11/// Make sure that topic string is valid.
12pub fn validate_topic(topic: &str) -> Result<(), Error> {
13  let mut chars = topic.chars();
14  match chars.next() {
15    Some(c) => if !is_topic_leading_char(c) {
16      return Err(Error::BadFormat("Invalid leading character".to_string()));
17    }
18    None => {
19      return Err(Error::BadFormat("Empty or broken string".to_string()))
20    }
21  }
22  if chars.any(|c| !is_topic_char(c)) {
23    return Err(Error::BadFormat("Invalid heading".to_string()));
24  }
25  Ok(())
26}
27
28
29#[cfg(test)]
30mod tests {
31  use super::validate_topic;
32  use super::Error;
33
34  #[test]
35  fn ok_topic_1() {
36    assert!(validate_topic("Foobar").is_ok());
37  }
38
39  #[test]
40  fn broken_topic_1() {
41    if let Err(e) = validate_topic("") {
42      match e {
43        Error::BadFormat(s) => {
44          assert_eq!(s, "Empty or broken string");
45        }
46        _ => {
47          panic!("Unexpected error");
48        }
49      }
50    } else {
51      panic!("Unexpected success");
52    }
53  }
54}
55
56// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :