Move panic after index name validation into the separate function
@@ -61,15 +61,13 @@ impl<T> BaseIndex<T> {
/// [`&Snapshot`]: ../trait.Snapshot.html
/// [`&mut Fork`]: ../struct.Fork.html
pub fn new<S: AsRef<str>>(name: S, view: T) -> Self {
- if is_valid_name(&name) {
+ assert_valid_name(&name);
+
BaseIndex {
name: name.as_ref().to_string(),
prefix: None,
view,
}
- } else {
- panic!("Wrong characters using in name. Use: a-zA-Z0-9 and _");
- }
}
/// Creates a new index representation based on the name, common prefix of its keys
@@ -81,15 +79,13 @@ impl<T> BaseIndex<T> {
/// [`&Snapshot`]: ../trait.Snapshot.html
/// [`&mut Fork`]: ../struct.Fork.html
pub fn with_prefix<S: AsRef<str>>(name: S, prefix: Vec<u8>, view: T) -> Self {
- if is_valid_name(&name) {
+ assert_valid_name(&name);
+
BaseIndex {
name: name.as_ref().to_string(),
prefix: Some(prefix),
view,
}
- } else {
- panic!("Wrong characters using in name. Use: a-zA-Z0-9 and _");
- }
}
fn prefixed_key<K: StorageKey>(&self, key: &K) -> Vec<u8> {
@@ -252,6 +248,17 @@ fn is_valid_name<S: AsRef<str>>(name: S) -> bool {
})
}
+/// Calls the `is_valid_name` function with the given name and panics if it returns `false`.
+fn assert_valid_name<S: AsRef<str>>(name: S) {
+ if !is_valid_name(name) {
+ panic!("Wrong characters using in name. Use: a-zA-Z0-9 and _");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
#[test]
fn test_index_name_validator() {
assert!(is_valid_name("index_name"));
@@ -268,3 +275,15 @@ fn test_index_name_validator() {
assert!(!is_valid_name("indeX_1namE-"));
assert!(!is_valid_name("1in!dex_Namez"));
}
+
+ #[test]
+ fn check_valid_name() {
+ assert_valid_name("valid_name");
+ }
+
+ #[test]
+ #[should_panic(expected = "Wrong characters using in name. Use: a-zA-Z0-9 and _")]
+ fn check_invalid_name() {
+ assert_valid_name("invalid-name");
+ }
+}
