ferretro/ferretro_components/src/provided/stdlib/variables.rs

52 lines
1.6 KiB
Rust

use std::collections::BTreeMap;
use crate::prelude::*;
#[derive(Default)]
pub struct VariableStoreComponent {
base_variables: BTreeMap<String, Vec<String>>,
override_variables: BTreeMap<String, String>,
update: bool,
}
impl VariableStoreComponent {
pub fn insert(&mut self, key: impl ToString, value: impl ToString) {
let key = key.to_string();
let value = value.to_string();
if let Some(options) = self.base_variables.get(&key) {
if !options.contains(&value) {
panic!("Invalid value {:?} for variable {:?} (expected one of {:?})", value, key, options);
}
}
self.override_variables.insert(key, value);
self.update = true;
}
}
impl RetroComponent for VariableStoreComponent {}
impl RetroCallbacks for VariableStoreComponent {
fn set_variables(&mut self, variables: &[Variable2]) -> Option<bool> {
for v in variables {
if let Some(x) = self.override_variables.get(&v.key) {
if !v.options.contains(x) {
panic!("Invalid value {:?} for variable {:?} (expected one of {:?})", x, v.key, v.options);
}
}
self.base_variables.insert(v.key.to_owned(), v.options.to_owned());
}
Some(true)
}
fn get_variable(&mut self, key: &str) -> Option<String> {
self.update = false;
self.override_variables.get(key)
.or_else(|| self.base_variables.get(key)
.and_then(|opts| opts.first()))
.cloned()
}
fn get_variable_update(&mut self) -> Option<bool> {
Some(self.update)
}
}