split off and document GameVars::normalize_varname

This commit is contained in:
yuni 2024-04-14 18:23:38 +02:00
parent a13264a404
commit d6901bef00

View file

@ -237,7 +237,19 @@ impl GameVars {
self.db.insert(key.to_lowercase(), value);
}
pub fn set_in_scope(&mut self, fallback_scope: &str, key: &str, value: String) {
// This method ensures that the variable name contains a scope separator,
// and if a scope is missing, it prefixes the fallback scope.
//
// Some examples, assuming fallback_scope="Clippy", SCOPE_SEPARATOR="$":
//
// "" -> "clippy$"
// "foo" -> "clippy$foo"
// "FOO" -> "clippy$foo"
// "$foo" -> "clippy$foo"
// "$$foo" -> "$$foo"
// "PizzaClippy$foo" -> "pizzaclippy$foo" (unchanged)
// "$foo$foo$foo$foo" -> "$foo$foo$foo$foo" (unchanged)
pub fn normalize_varname(fallback_scope: &str, key: &str) -> String {
let parts: Vec<&str> = key.split(SCOPE_SEPARATOR).collect();
let key: String = if parts.len() == 1 {
// we got a key like "foo", turn it into "<scope>$foo"
@ -257,11 +269,14 @@ impl GameVars {
key.to_string()
}
} else {
// we got an empty string. this is bad, but handle gracefully by prefixing scope
// we got an empty string. this is bad, but handle gracefully
fallback_scope.to_string() + SCOPE_SEPARATOR
};
return key.to_lowercase();
}
let key = key.to_lowercase();
pub fn set_in_scope(&mut self, fallback_scope: &str, key: &str, value: String) {
let key = Self::normalize_varname(fallback_scope, key);
self.db.insert(key, value);
}
}