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
use std::convert::From; use binding::hash::{aset, aref, new}; use types::Value; use super::any_object::AnyObject; use super::traits::Object; /// `Hash` pub struct Hash { value: Value } impl Hash { /// Creates a new instance of empty `Hash`. /// /// # Examples /// /// ``` /// use ruru::{Hash, VM}; /// # VM::init(); /// /// Hash::new(); /// ``` /// /// Ruby: /// /// ```ruby /// {} /// ``` pub fn new() -> Self { Hash { value: new() } } /// Retrieves an `AnyObject` from element stored at `key` key. /// /// # Examples /// /// ```no_run /// use ruru::{Fixnum, Hash, Symbol, VM}; /// # VM::init(); /// /// let mut hash = Hash::new(); /// /// hash.store(Symbol::new("key"), Fixnum::new(1)); /// /// assert_eq!(hash.at(Symbol::new("key")).as_fixnum(), Fixnum::new(1)); /// ``` /// /// Ruby: /// /// ```ruby /// hash = {} /// hash[:key] = 1 /// /// hash[:key] == 1 /// ``` pub fn at<T: Object>(&self, key: T) -> AnyObject { let value = aref(self.value(), key.value()); AnyObject::from(value) } /// Associates the `value` with the `key`. /// /// Both `key` and `value` must be types which implement `Object` trait. /// /// # Examples /// /// ```no_run /// use ruru::{Fixnum, Hash, Symbol, VM}; /// # VM::init(); /// /// let mut hash = Hash::new(); /// /// hash.store(Symbol::new("key"), Fixnum::new(1)); /// /// assert_eq!(hash.at(Symbol::new("key")).as_fixnum(), Fixnum::new(1)); /// ``` /// /// Ruby: /// /// ```ruby /// hash = {} /// hash[:key] = 1 /// /// hash[:key] == 1 /// ``` pub fn store<K: Object, V: Object>(&mut self, key: K, value: V) -> AnyObject { let value = aset(self.value(), key.value(), value.value()); AnyObject::from(value) } } impl From<Value> for Hash { fn from(value: Value) -> Self { Hash { value: value } } } impl Object for Hash { fn value(&self) -> Value { self.value } }