Skip to content
This repository was archived by the owner on Mar 23, 2023. It is now read-only.

Commit 6841671

Browse files
corona10trotterdylan
authored andcommitted
Implement complex hash. (#293)
1 parent 0def2c2 commit 6841671

2 files changed

Lines changed: 25 additions & 0 deletions

File tree

runtime/complex.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ func initComplexType(dict map[string]*Object) {
7272
ComplexType.slots.Eq = &binaryOpSlot{complexEq}
7373
ComplexType.slots.GE = &binaryOpSlot{complexCompareNotSupported}
7474
ComplexType.slots.GT = &binaryOpSlot{complexCompareNotSupported}
75+
ComplexType.slots.Hash = &unaryOpSlot{complexHash}
7576
ComplexType.slots.LE = &binaryOpSlot{complexCompareNotSupported}
7677
ComplexType.slots.LT = &binaryOpSlot{complexCompareNotSupported}
7778
ComplexType.slots.NE = &binaryOpSlot{complexNE}
@@ -130,3 +131,12 @@ func complexCoerce(o *Object) (complex128, bool) {
130131
}
131132
return complex(floatO, 0.0), true
132133
}
134+
135+
func complexHash(f *Frame, o *Object) (*Object, *BaseException) {
136+
v := toComplexUnsafe(o).Value()
137+
hashCombined := hashFloat(real(v)) + 1000003*hashFloat(imag(v))
138+
if hashCombined == -1 {
139+
hashCombined = -2
140+
}
141+
return NewInt(hashCombined).ToObject(), nil
142+
}

runtime/complex_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,18 @@ func TestComplexRepr(t *testing.T) {
9393
}
9494
}
9595
}
96+
97+
func TestComplexHash(t *testing.T) {
98+
cases := []invokeTestCase{
99+
{args: wrapArgs(complex(0.0, 0.0)), want: NewInt(0).ToObject()},
100+
{args: wrapArgs(complex(0.0, 1.0)), want: NewInt(1000003).ToObject()},
101+
{args: wrapArgs(complex(1.0, 0.0)), want: NewInt(1).ToObject()},
102+
{args: wrapArgs(complex(3.1, -4.2)), want: NewInt(-1556830019620134).ToObject()},
103+
{args: wrapArgs(complex(3.1, 4.2)), want: NewInt(1557030815934348).ToObject()},
104+
}
105+
for _, cas := range cases {
106+
if err := runInvokeTestCase(wrapFuncForTest(complexHash), &cas); err != "" {
107+
t.Error(err)
108+
}
109+
}
110+
}

0 commit comments

Comments
 (0)