1
0
dust/src/context.rs

94 lines
2.3 KiB
Rust
Raw Normal View History

2024-02-25 18:49:26 +00:00
use std::{
collections::BTreeMap,
sync::{Arc, RwLock},
};
2024-03-06 23:15:25 +00:00
use crate::{
abstract_tree::{Identifier, Type},
error::RwLockPoisonError,
2024-03-09 11:55:19 +00:00
value::BuiltInFunction,
2024-03-06 23:15:25 +00:00
Value,
};
2024-02-25 18:49:26 +00:00
pub struct Context {
2024-03-06 23:15:25 +00:00
inner: Arc<RwLock<BTreeMap<Identifier, ValueData>>>,
}
#[derive(Clone, Debug)]
pub enum ValueData {
Type(Type),
Value(Value),
2024-02-25 18:49:26 +00:00
}
impl Context {
pub fn new() -> Self {
Self {
inner: Arc::new(RwLock::new(BTreeMap::new())),
}
}
2024-03-06 23:15:25 +00:00
pub fn with_data(data: BTreeMap<Identifier, ValueData>) -> Self {
2024-02-25 18:49:26 +00:00
Self {
2024-03-06 23:15:25 +00:00
inner: Arc::new(RwLock::new(data)),
}
}
pub fn get_data(
&self,
identifier: &Identifier,
) -> Result<Option<ValueData>, RwLockPoisonError> {
2024-03-09 11:55:19 +00:00
if let Some(value_data) = self.inner.read()?.get(identifier) {
return Ok(Some(value_data.clone()));
}
let value_data = match identifier.as_str() {
"output" => ValueData::Value(BuiltInFunction::output()),
_ => return Ok(None),
};
Ok(Some(value_data))
2024-03-06 23:15:25 +00:00
}
pub fn get_type(&self, identifier: &Identifier) -> Result<Option<Type>, RwLockPoisonError> {
if let Some(ValueData::Type(r#type)) = self.inner.read()?.get(identifier) {
2024-03-09 11:55:19 +00:00
return Ok(Some(r#type.clone()));
2024-03-06 23:15:25 +00:00
}
2024-03-09 11:55:19 +00:00
let r#type = match identifier.as_str() {
"output" => BuiltInFunction::Output.r#type(),
_ => return Ok(None),
};
Ok(Some(r#type))
2024-03-06 23:15:25 +00:00
}
pub fn get_value(&self, identifier: &Identifier) -> Result<Option<Value>, RwLockPoisonError> {
if let Some(ValueData::Value(value)) = self.inner.read()?.get(identifier) {
2024-03-09 11:55:19 +00:00
return Ok(Some(value.clone()));
2024-02-25 18:49:26 +00:00
}
2024-03-09 11:55:19 +00:00
let value = match identifier.as_str() {
"output" => BuiltInFunction::output(),
_ => return Ok(None),
};
Ok(Some(value))
2024-02-25 18:49:26 +00:00
}
2024-03-06 23:15:25 +00:00
pub fn set_type(&self, identifier: Identifier, r#type: Type) -> Result<(), RwLockPoisonError> {
self.inner
.write()?
.insert(identifier, ValueData::Type(r#type));
2024-02-25 18:49:26 +00:00
2024-03-06 23:15:25 +00:00
Ok(())
2024-02-25 18:49:26 +00:00
}
2024-03-06 23:15:25 +00:00
pub fn set_value(&self, identifier: Identifier, value: Value) -> Result<(), RwLockPoisonError> {
self.inner
.write()?
.insert(identifier, ValueData::Value(value));
2024-02-25 18:49:26 +00:00
Ok(())
}
}