[types] Value equivalence via PartialEq!

This commit is contained in:
Eryn Wells 2018-08-25 11:18:59 -07:00
parent 1a3b7adc5a
commit 22f3c3a9e3
3 changed files with 52 additions and 1 deletions

View file

@ -13,6 +13,7 @@
//! available types in Scheme. These predicates are implemented as `is_*`
//! methods in a bunch of `Is*` traits defined below.
use std::ops::Deref;
use std::mem;
use std::any::Any;
use std::fmt;
@ -26,7 +27,8 @@ pub enum Obj {
pub trait Object:
fmt::Debug +
fmt::Display
fmt::Display +
PartialEq<Obj>
{
/// Cast this Object to an Any.
fn as_any(&self) -> &Any;
@ -52,6 +54,13 @@ impl Obj {
Obj::Ptr(obj) => obj.as_any().downcast_ref::<T>()
}
}
pub fn is_null(&self) -> bool {
match self {
Obj::Null => true,
_ => false
}
}
}
impl fmt::Display for Obj {
@ -63,6 +72,15 @@ impl fmt::Display for Obj {
}
}
impl PartialEq for Obj {
fn eq(&self, rhs: &Self) -> bool {
match self {
Obj::Null => rhs.is_null(),
Obj::Ptr(ref inner) => inner.deref() == rhs
}
}
}
//#[derive(Debug, PartialEq)]
//pub enum Object {
// ByteVector(Vec<u8>),

View file

@ -52,6 +52,23 @@ impl fmt::Display for Pair {
}
}
impl PartialEq<Obj> for Pair {
fn eq(&self, rhs: &Obj) -> bool {
match rhs {
Obj::Null => false,
Obj::Ptr(ref rhs) => {
if let Some(rhs_pair) = rhs.as_pair() {
let car_eq = self.car == rhs_pair.car;
let cdr_eq = self.cdr == rhs_pair.cdr;
car_eq && cdr_eq
} else {
false
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::Pair;

View file

@ -3,6 +3,7 @@
*/
use std::any::Any;
use std::ops::Deref;
use std::fmt;
use object::Object;
use super::*;
@ -33,6 +34,21 @@ impl fmt::Display for Sym {
}
}
impl PartialEq<Obj> for Sym {
fn eq(&self, rhs: &Obj) -> bool {
match rhs {
Obj::Null => false,
Obj::Ptr(ref inner) => {
if let Some(rhs_sym) = inner.deref().as_sym() {
self.0 == rhs_sym.0
} else {
false
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::Sym;