Skip to content

py: Support __len__ of rangetype. #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 26, 2018
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
47 changes: 37 additions & 10 deletions py/range.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ package py
// A python Range object
// FIXME one day support BigInts too!
type Range struct {
Start Int
Stop Int
Step Int
//Length Object
Start Int
Stop Int
Step Int
Length Int
}

// A python Range iterator
Expand Down Expand Up @@ -53,10 +53,12 @@ func RangeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error) {
return nil, err
}
if len(args) == 1 {
length := computeRangeLength(0, startIndex, 1)
return &Range{
Start: Int(0),
Stop: startIndex,
Step: Int(1),
Start: Int(0),
Stop: startIndex,
Step: Int(1),
Length: length,
}, nil
}
stopIndex, err := Index(stop)
Expand All @@ -67,10 +69,12 @@ func RangeNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error) {
if err != nil {
return nil, err
}
length := computeRangeLength(startIndex, stopIndex, stepIndex)
return &Range{
Start: startIndex,
Stop: stopIndex,
Step: stepIndex,
Start: startIndex,
Stop: stopIndex,
Step: stepIndex,
Length: length,
}, nil
}

Expand All @@ -82,6 +86,10 @@ func (r *Range) M__iter__() (Object, error) {
}, nil
}

func (r *Range) M__len__() (Object, error) {
return r.Length, nil
}

// Range iterator
func (it *RangeIterator) M__iter__() (Object, error) {
return it, nil
Expand All @@ -97,6 +105,25 @@ func (it *RangeIterator) M__next__() (Object, error) {
return r, nil
}

func computeRangeLength(start, stop, step Int) Int {
var lo, hi Int
if step > 0 {
lo = start
hi = stop
step = step
} else {
lo = stop
hi = start
step = (-step)
}

if lo >= hi {
return Int(0)
}
res := (hi-lo-1)/step + 1
return res
}

// Check interface is satisfied
var _ I__iter__ = (*Range)(nil)
var _ I_iterator = (*RangeIterator)(nil)
16 changes: 16 additions & 0 deletions py/tests/range.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright 2018 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

doc="range"
a = range(255)
b = [e for e in a]
assert len(a) == len(b)
a = range(5, 100, 5)
b = [e for e in a]
assert len(a) == len(b)
a = range(100 ,0, 1)
b = [e for e in a]
assert len(a) == len(b)

doc="finished"