Skip to content
This repository was archived by the owner on Mar 23, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions runtime/complex.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func initComplexType(dict map[string]*Object) {
ComplexType.slots.Eq = &binaryOpSlot{complexEq}
ComplexType.slots.GE = &binaryOpSlot{complexCompareNotSupported}
ComplexType.slots.GT = &binaryOpSlot{complexCompareNotSupported}
ComplexType.slots.Hash = &unaryOpSlot{complexHash}
ComplexType.slots.LE = &binaryOpSlot{complexCompareNotSupported}
ComplexType.slots.LT = &binaryOpSlot{complexCompareNotSupported}
ComplexType.slots.NE = &binaryOpSlot{complexNE}
Expand Down Expand Up @@ -130,3 +131,12 @@ func complexCoerce(o *Object) (complex128, bool) {
}
return complex(floatO, 0.0), true
}

func complexHash(f *Frame, o *Object) (*Object, *BaseException) {
v := toComplexUnsafe(o).Value()
hashCombined := hashFloat(real(v)) + 1000003*hashFloat(imag(v))
if hashCombined == -1 {
hashCombined = -2
}
return NewInt(hashCombined).ToObject(), nil
}
15 changes: 15 additions & 0 deletions runtime/complex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,18 @@ func TestComplexRepr(t *testing.T) {
}
}
}

func TestComplexHash(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(complex(0.0, 0.0)), want: NewInt(0).ToObject()},
{args: wrapArgs(complex(0.0, 1.0)), want: NewInt(1000003).ToObject()},
{args: wrapArgs(complex(1.0, 0.0)), want: NewInt(1).ToObject()},
{args: wrapArgs(complex(3.1, -4.2)), want: NewInt(-1556830019620134).ToObject()},
{args: wrapArgs(complex(3.1, 4.2)), want: NewInt(1557030815934348).ToObject()},
}
for _, cas := range cases {
if err := runInvokeTestCase(wrapFuncForTest(complexHash), &cas); err != "" {
t.Error(err)
}
}
}