use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
use fontoxide_misc::Tag;
use crate::{Error, Result};
#[derive(Debug, Clone)]
pub struct CountRef(Rc<RefCell<CountCell>>);
#[derive(Debug)]
struct CountCell {
value: Option<u64>,
size: usize,
name: &'static str,
}
impl CountRef {
pub fn new(name: &'static str, size: usize, value: Option<u64>) -> Self {
CountRef(Rc::new(RefCell::new(CountCell { value, size, name })))
}
pub fn set_value(&self, value: u64) -> Result<()> {
let mut c = self.0.borrow_mut();
match c.value {
None => {
c.value = Some(value);
Ok(())
}
Some(v) if v == value => Ok(()),
Some(v) => Err(Error::Assertion(format!("({:?}, {v}, {value})", c.name))),
}
}
pub fn value(&self) -> Option<u64> {
self.0.borrow().value
}
pub fn size(&self) -> usize {
self.0.borrow().size
}
pub fn set_size(&self, size: usize) {
self.0.borrow_mut().size = size;
}
pub fn data(&self) -> Result<Vec<u8>> {
let c = self.0.borrow();
let v = c.value.unwrap_or(0);
let too_big = || Error::Struct(format!("count {v} does not fit in {} bytes", c.size));
Ok(match c.size {
1 => vec![u8::try_from(v).map_err(|_| too_big())?],
2 => u16::try_from(v)
.map_err(|_| too_big())?
.to_be_bytes()
.to_vec(),
3 => {
if v >= 1 << 24 {
return Err(too_big());
}
(v as u32).to_be_bytes()[1..].to_vec()
}
4 => u32::try_from(v)
.map_err(|_| too_big())?
.to_be_bytes()
.to_vec(),
s => return Err(Error::value(format!("invalid count size {s}"))),
})
}
pub fn ptr_eq(&self, other: &CountRef) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Debug, Clone)]
pub enum StateValue {
Int(i64),
Count(CountRef),
ValueFormat(u16),
Tag(Option<Tag>),
Tags(Rc<Vec<Tag>>),
Lens(Rc<Vec<usize>>),
}
impl StateValue {
pub fn as_int(&self) -> Option<i64> {
match self {
StateValue::Int(i) => Some(*i),
StateValue::Count(c) => c.value().map(|v| v as i64),
StateValue::ValueFormat(f) => Some(*f as i64),
_ => None,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct State(BTreeMap<&'static str, StateValue>);
impl State {
pub fn new() -> Self {
State(BTreeMap::new())
}
pub fn get(&self, name: &str) -> Option<&StateValue> {
self.0.get(name)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn contains(&self, name: &str) -> bool {
self.0.contains_key(name)
}
pub fn set(&mut self, name: &'static str, value: StateValue) {
self.0.insert(name, value);
}
pub fn remove(&mut self, name: &str) {
self.0.remove(name);
}
}