Commit 90786d22 authored by Dylan Trotter's avatar Dylan Trotter Committed by GitHub

Implement xrange.__len__. (#159)

parent 468ce7d7
......@@ -182,6 +182,11 @@ func xrangeIter(f *Frame, o *Object) (*Object, *BaseException) {
return &(&rangeIterator{Object{typ: rangeIteratorType}, r.start, r.stop, r.step}).Object, nil
}
func xrangeLen(f *Frame, o *Object) (*Object, *BaseException) {
r := toXRangeUnsafe(o)
return NewInt((r.stop - r.start) / r.step).ToObject(), nil
}
func xrangeNew(f *Frame, _ *Type, args Args, _ KWArgs) (*Object, *BaseException) {
expectedTypes := []*Type{IntType, IntType, IntType}
argc := len(args)
......@@ -229,6 +234,7 @@ func initXRangeType(map[string]*Object) {
xrangeType.flags &^= typeFlagBasetype
xrangeType.slots.GetItem = &binaryOpSlot{xrangeGetItem}
xrangeType.slots.Iter = &unaryOpSlot{xrangeIter}
xrangeType.slots.Len = &unaryOpSlot{xrangeLen}
xrangeType.slots.New = &newSlot{xrangeNew}
xrangeType.slots.Repr = &unaryOpSlot{xrangeRepr}
}
......@@ -85,6 +85,20 @@ func TestXRangeGetItem(t *testing.T) {
}
}
func TestXRangeLen(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(newTestXRange(10)), want: NewInt(10).ToObject()},
{args: wrapArgs(newTestXRange(10, 12)), want: NewInt(2).ToObject()},
{args: wrapArgs(newTestXRange(5, 16, 5)), want: NewInt(3).ToObject()},
{args: wrapArgs(newTestXRange(5, -2, -3)), want: NewInt(3).ToObject()},
}
for _, cas := range cases {
if err := runInvokeMethodTestCase(xrangeType, "__len__", &cas); err != "" {
t.Error(err)
}
}
}
func TestXRangeNew(t *testing.T) {
fun := newBuiltinFunction("TestXRangeNew", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
xrange, raised := xrangeType.Call(f, args, nil)
......
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