Commit cf0c37d1 authored by Marius Wachtler's avatar Marius Wachtler

Implement tuple hashing

parent ccc8fda6
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
#include "core/stats.h" #include "core/stats.h"
#include "core/types.h" #include "core/types.h"
#include "codegen/compvars.h"
#include "runtime/gc_runtime.h" #include "runtime/gc_runtime.h"
#include "runtime/objmodel.h" #include "runtime/objmodel.h"
#include "runtime/types.h" #include "runtime/types.h"
...@@ -174,6 +176,19 @@ Box* tupleContains(BoxedTuple* self, Box* elt) { ...@@ -174,6 +176,19 @@ Box* tupleContains(BoxedTuple* self, Box* elt) {
return False; return False;
} }
Box* tupleHash(BoxedTuple* self) {
assert(self->cls == tuple_cls);
int64_t rtn = 3527539;
for (Box* e : self->elts) {
BoxedInt* h = hash(e);
assert(h->cls == int_cls);
rtn ^= h->n + 0x9e3779b9 + (rtn << 6) + (rtn >> 2);
}
return boxInt(rtn);
}
void setupTuple() { void setupTuple() {
tuple_cls->giveAttr("__name__", boxStrConstant("tuple")); tuple_cls->giveAttr("__name__", boxStrConstant("tuple"));
...@@ -187,6 +202,7 @@ void setupTuple() { ...@@ -187,6 +202,7 @@ void setupTuple() {
tuple_cls->giveAttr("__eq__", new BoxedFunction(boxRTFunction((void*)tupleEq, NULL, 2, false))); tuple_cls->giveAttr("__eq__", new BoxedFunction(boxRTFunction((void*)tupleEq, NULL, 2, false)));
tuple_cls->giveAttr("__ne__", new BoxedFunction(boxRTFunction((void*)tupleNe, NULL, 2, false))); tuple_cls->giveAttr("__ne__", new BoxedFunction(boxRTFunction((void*)tupleNe, NULL, 2, false)));
tuple_cls->giveAttr("__hash__", new BoxedFunction(boxRTFunction((void*)tupleHash, BOXED_INT, 1, false)));
tuple_cls->giveAttr("__len__", new BoxedFunction(boxRTFunction((void*)tupleLen, NULL, 1, false))); tuple_cls->giveAttr("__len__", new BoxedFunction(boxRTFunction((void*)tupleLen, NULL, 1, false)));
tuple_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)tupleRepr, NULL, 1, false))); tuple_cls->giveAttr("__repr__", new BoxedFunction(boxRTFunction((void*)tupleRepr, NULL, 1, false)));
tuple_cls->setattr("__str__", tuple_cls->peekattr("__repr__"), NULL, NULL); tuple_cls->setattr("__str__", tuple_cls->peekattr("__repr__"), NULL, NULL);
......
...@@ -47,6 +47,9 @@ class T(object): ...@@ -47,6 +47,9 @@ class T(object):
print "eq", self.n, rhs.n print "eq", self.n, rhs.n
return self.n == rhs.n return self.n == rhs.n
def __hash__(self):
return hash(self.n)
def __repr__(self): def __repr__(self):
return "<T>" return "<T>"
...@@ -57,6 +60,7 @@ def t(l, r): ...@@ -57,6 +60,7 @@ def t(l, r):
print l >= r print l >= r
print l == r print l == r
print l != r print l != r
print "same hash: " , hash(l) == hash(r)
t(T(1), T(2)) t(T(1), T(2))
t(T(1), T(1)) t(T(1), T(1))
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment