1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use std::{rc::Rc, ops::{DerefMut, Deref}, iter::FromIterator, cell::RefCell};
use crate::{RantString, RantValue};
use fnv::FnvHashMap;

const DEFAULT_MAP_CAPACITY: usize = 16;
const DEFAULT_LIST_CAPACITY: usize = 16;

pub type RantMapRef = Rc<RefCell<RantMap>>;
pub type RantListRef = Rc<RefCell<RantList>>;

/// Represents Rant's `list` type, which stores an ordered collection of values.
#[derive(Debug)]
pub struct RantList(Vec<RantValue>);

impl RantList {
  pub fn new() -> Self {
    Self(Vec::with_capacity(DEFAULT_LIST_CAPACITY))
  }

  pub fn with_capacity(capacity: usize) -> Self {
    Self(Vec::with_capacity(capacity))
  }

}

impl Default for RantList {
  fn default() -> Self {
    Self::new()
  }
}

impl Deref for RantList {
  type Target = Vec<RantValue>;
  fn deref(&self) -> &Self::Target {
    &self.0
  }
}

impl DerefMut for RantList {
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.0
  }
}

impl FromIterator<RantValue> for RantList {
  fn from_iter<T: IntoIterator<Item = RantValue>>(iter: T) -> Self {
    let mut list = Self::new();
    for item in iter {
      list.push(item);
    }
    list
  }
}

/// Represents Rant's `map` type, which stores a collection of key-value pairs.
/// Map keys are always strings.
#[derive(Debug)]
pub struct RantMap {
  /// The physical contents of the map
  map: FnvHashMap<RantString, RantValue>,
  /// The prototype of the map
  proto: Option<RantMapRef>
}

impl RantMap {
  pub fn new() -> Self {
    Self {
      map: FnvHashMap::with_capacity_and_hasher(DEFAULT_MAP_CAPACITY, Default::default()),
      proto: None
    }
  }

  pub fn raw_len(&self) -> usize {
    self.map.len()
  }
  
  pub fn is_empty(&self) -> bool {
    self.map.is_empty()
  }

  pub fn proto(&self) -> Option<RantMapRef> {
    self.proto.clone()
  }

  pub fn set_proto(&mut self, proto: Option<RantMapRef>) {
    self.proto = proto;
  }

  #[inline]
  pub fn raw_set(&mut self, key: &str, val: RantValue) {
    self.map.insert(RantString::from(key), val);
  }

  #[inline]
  pub fn raw_get<'a>(&'a self, key: &str) -> Option<&'a RantValue> {
    self.map.get(key)
  }

  #[inline]
  pub fn raw_has_key(&self, key: &str) -> bool {
    self.map.contains_key(key)
  }

  pub fn raw_keys(&self) -> RantList {
    RantList::from_iter(self.map.keys().map(|k| RantValue::String(k.to_string())))
  }
}

impl Default for RantMap {
  fn default() -> Self {
    RantMap::new()
  }
}